File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.99: download - view: text, annotated - select for diffs
Thu Aug 4 23:26:51 2016 UTC (7 years, 10 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.1226, 1.1227

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.99 2016/08/04 23:26:51 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 Encode();
   77: use Authen::Captcha;
   78: use Captcha::reCAPTCHA;
   79: use Crypt::DES;
   80: use DynaLoader; # for Crypt::DES version
   81: 
   82: # ---------------------------------------------- Designs
   83: use vars qw(%defaultdesign);
   84: 
   85: my $readit;
   86: 
   87: 
   88: ##
   89: ## Global Variables
   90: ##
   91: 
   92: 
   93: # ----------------------------------------------- SSI with retries:
   94: #
   95: 
   96: =pod
   97: 
   98: =head1 Server Side include with retries:
   99: 
  100: =over 4
  101: 
  102: =item * &ssi_with_retries(resource,retries form)
  103: 
  104: Performs an ssi with some number of retries.  Retries continue either
  105: until the result is ok or until the retry count supplied by the
  106: caller is exhausted.  
  107: 
  108: Inputs:
  109: 
  110: =over 4
  111: 
  112: resource   - Identifies the resource to insert.
  113: 
  114: retries    - Count of the number of retries allowed.
  115: 
  116: form       - Hash that identifies the rendering options.
  117: 
  118: =back
  119: 
  120: Returns:
  121: 
  122: =over 4
  123: 
  124: content    - The content of the response.  If retries were exhausted this is empty.
  125: 
  126: response   - The response from the last attempt (which may or may not have been successful.
  127: 
  128: =back
  129: 
  130: =back
  131: 
  132: =cut
  133: 
  134: sub ssi_with_retries {
  135:     my ($resource, $retries, %form) = @_;
  136: 
  137: 
  138:     my $ok = 0;			# True if we got a good response.
  139:     my $content;
  140:     my $response;
  141: 
  142:     # Try to get the ssi done. within the retries count:
  143: 
  144:     do {
  145: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  146: 	$ok      = $response->is_success;
  147:         if (!$ok) {
  148:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  149:         }
  150: 	$retries--;
  151:     } while (!$ok && ($retries > 0));
  152: 
  153:     if (!$ok) {
  154: 	$content = '';		# On error return an empty content.
  155:     }
  156:     return ($content, $response);
  157: 
  158: }
  159: 
  160: 
  161: 
  162: # ----------------------------------------------- Filetypes/Languages/Copyright
  163: my %language;
  164: my %supported_language;
  165: my %latex_language;		# For choosing hyphenation in <transl..>
  166: my %latex_language_bykey;	# for choosing hyphenation from metadata
  167: my %cprtag;
  168: my %scprtag;
  169: my %fe; my %fd; my %fm;
  170: my %category_extensions;
  171: 
  172: # ---------------------------------------------- Thesaurus variables
  173: #
  174: # %Keywords:
  175: #      A hash used by &keyword to determine if a word is considered a keyword.
  176: # $thesaurus_db_file 
  177: #      Scalar containing the full path to the thesaurus database.
  178: 
  179: my %Keywords;
  180: my $thesaurus_db_file;
  181: 
  182: #
  183: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  184: # thesaurus.tab, and filecategories.tab.
  185: #
  186: BEGIN {
  187:     # Variable initialization
  188:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  189:     #
  190:     unless ($readit) {
  191: # ------------------------------------------------------------------- languages
  192:     {
  193:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  194:                                    '/language.tab';
  195:         if ( open(my $fh,"<$langtabfile") ) {
  196:             while (my $line = <$fh>) {
  197:                 next if ($line=~/^\#/);
  198:                 chomp($line);
  199:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  200:                 $language{$key}=$val.' - '.$enc;
  201:                 if ($sup) {
  202:                     $supported_language{$key}=$sup;
  203:                 }
  204: 		if ($latex) {
  205: 		    $latex_language_bykey{$key} = $latex;
  206: 		    $latex_language{$two} = $latex;
  207: 		}
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ------------------------------------------------------------------ copyrights
  213:     {
  214:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/copyright.tab';
  216:         if ( open (my $fh,"<$copyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line=~/^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $cprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: # ----------------------------------------------------------- source copyrights
  227:     {
  228:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  229:                                   '/source_copyright.tab';
  230:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  231:             while (my $line = <$fh>) {
  232:                 next if ($line =~ /^\#/);
  233:                 chomp($line);
  234:                 my ($key,$val)=(split(/\s+/,$line,2));
  235:                 $scprtag{$key}=$val;
  236:             }
  237:             close($fh);
  238:         }
  239:     }
  240: 
  241: # -------------------------------------------------------------- default domain designs
  242:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  243:     my $designfile = $designdir.'/default.tab';
  244:     if ( open (my $fh,"<$designfile") ) {
  245:         while (my $line = <$fh>) {
  246:             next if ($line =~ /^\#/);
  247:             chomp($line);
  248:             my ($key,$val)=(split(/\=/,$line));
  249:             if ($val) { $defaultdesign{$key}=$val; }
  250:         }
  251:         close($fh);
  252:     }
  253: 
  254: # ------------------------------------------------------------- file categories
  255:     {
  256:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  257:                                   '/filecategories.tab';
  258:         if ( open (my $fh,"<$categoryfile") ) {
  259: 	    while (my $line = <$fh>) {
  260: 		next if ($line =~ /^\#/);
  261: 		chomp($line);
  262:                 my ($extension,$category)=(split(/\s+/,$line,2));
  263:                 push @{$category_extensions{lc($category)}},$extension;
  264:             }
  265:             close($fh);
  266:         }
  267: 
  268:     }
  269: # ------------------------------------------------------------------ file types
  270:     {
  271:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  272:                '/filetypes.tab';
  273:         if ( open (my $fh,"<$typesfile") ) {
  274:             while (my $line = <$fh>) {
  275: 		next if ($line =~ /^\#/);
  276: 		chomp($line);
  277:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  278:                 if ($descr ne '') {
  279:                     $fe{$ending}=lc($emb);
  280:                     $fd{$ending}=$descr;
  281:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  282:                 }
  283:             }
  284:             close($fh);
  285:         }
  286:     }
  287:     &Apache::lonnet::logthis(
  288:              "<span style='color:yellow;'>INFO: Read file types</span>");
  289:     $readit=1;
  290:     }  # end of unless($readit) 
  291:     
  292: }
  293: 
  294: ###############################################################
  295: ##           HTML and Javascript Helper Functions            ##
  296: ###############################################################
  297: 
  298: =pod 
  299: 
  300: =head1 HTML and Javascript Functions
  301: 
  302: =over 4
  303: 
  304: =item * &browser_and_searcher_javascript()
  305: 
  306: X<browsing, javascript>X<searching, javascript>Returns a string
  307: containing javascript with two functions, C<openbrowser> and
  308: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  309: tags.
  310: 
  311: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  312: 
  313: inputs: formname, elementname, only, omit
  314: 
  315: formname and elementname indicate the name of the html form and name of
  316: the element that the results of the browsing selection are to be placed in. 
  317: 
  318: Specifying 'only' will restrict the browser to displaying only files
  319: with the given extension.  Can be a comma separated list.
  320: 
  321: Specifying 'omit' will restrict the browser to NOT displaying files
  322: with the given extension.  Can be a comma separated list.
  323: 
  324: =item * &opensearcher(formname,elementname) [javascript]
  325: 
  326: Inputs: formname, elementname
  327: 
  328: formname and elementname specify the name of the html form and the name
  329: of the element the selection from the search results will be placed in.
  330: 
  331: =cut
  332: 
  333: sub browser_and_searcher_javascript {
  334:     my ($mode)=@_;
  335:     if (!defined($mode)) { $mode='edit'; }
  336:     my $resurl=&escape_single(&lastresurl());
  337:     return <<END;
  338: // <!-- BEGIN LON-CAPA Internal
  339:     var editbrowser = null;
  340:     function openbrowser(formname,elementname,only,omit,titleelement) {
  341:         var url = '$resurl/?';
  342:         if (editbrowser == null) {
  343:             url += 'launch=1&';
  344:         }
  345:         url += 'catalogmode=interactive&';
  346:         url += 'mode=$mode&';
  347:         url += 'inhibitmenu=yes&';
  348:         url += 'form=' + formname + '&';
  349:         if (only != null) {
  350:             url += 'only=' + only + '&';
  351:         } else {
  352:             url += 'only=&';
  353: 	}
  354:         if (omit != null) {
  355:             url += 'omit=' + omit + '&';
  356:         } else {
  357:             url += 'omit=&';
  358: 	}
  359:         if (titleelement != null) {
  360:             url += 'titleelement=' + titleelement + '&';
  361:         } else {
  362: 	    url += 'titleelement=&';
  363: 	}
  364:         url += 'element=' + elementname + '';
  365:         var title = 'Browser';
  366:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  367:         options += ',width=700,height=600';
  368:         editbrowser = open(url,title,options,'1');
  369:         editbrowser.focus();
  370:     }
  371:     var editsearcher;
  372:     function opensearcher(formname,elementname,titleelement) {
  373:         var url = '/adm/searchcat?';
  374:         if (editsearcher == null) {
  375:             url += 'launch=1&';
  376:         }
  377:         url += 'catalogmode=interactive&';
  378:         url += 'mode=$mode&';
  379:         url += 'form=' + formname + '&';
  380:         if (titleelement != null) {
  381:             url += 'titleelement=' + titleelement + '&';
  382:         } else {
  383: 	    url += 'titleelement=&';
  384: 	}
  385:         url += 'element=' + elementname + '';
  386:         var title = 'Search';
  387:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  388:         options += ',width=700,height=600';
  389:         editsearcher = open(url,title,options,'1');
  390:         editsearcher.focus();
  391:     }
  392: // END LON-CAPA Internal -->
  393: END
  394: }
  395: 
  396: sub lastresurl {
  397:     if ($env{'environment.lastresurl'}) {
  398: 	return $env{'environment.lastresurl'}
  399:     } else {
  400: 	return '/res';
  401:     }
  402: }
  403: 
  404: sub storeresurl {
  405:     my $resurl=&Apache::lonnet::clutter(shift);
  406:     unless ($resurl=~/^\/res/) { return 0; }
  407:     $resurl=~s/\/$//;
  408:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  409:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  410:     return 1;
  411: }
  412: 
  413: sub studentbrowser_javascript {
  414:    unless (
  415:             (($env{'request.course.id'}) && 
  416:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  417: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  418: 					  '/'.$env{'request.course.sec'})
  419: 	      ))
  420:          || ($env{'request.role'}=~/^(au|dc|su)/)
  421:           ) { return ''; }  
  422:    return (<<'ENDSTDBRW');
  423: <script type="text/javascript" language="Javascript">
  424: // <![CDATA[
  425:     var stdeditbrowser;
  426:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  427:         var url = '/adm/pickstudent?';
  428:         var filter;
  429: 	if (!ignorefilter) {
  430: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  431: 	}
  432:         if (filter != null) {
  433:            if (filter != '') {
  434:                url += 'filter='+filter+'&';
  435: 	   }
  436:         }
  437:         url += 'form=' + formname + '&unameelement='+uname+
  438:                                     '&udomelement='+udom+
  439:                                     '&clicker='+clicker;
  440: 	if (roleflag) { url+="&roles=1"; }
  441:         if (courseadvonly) { url+="&courseadvonly=1"; }
  442:         var title = 'Student_Browser';
  443:         var options = 'scrollbars=1,resizable=1,menubar=0';
  444:         options += ',width=700,height=600';
  445:         stdeditbrowser = open(url,title,options,'1');
  446:         stdeditbrowser.focus();
  447:     }
  448: // ]]>
  449: </script>
  450: ENDSTDBRW
  451: }
  452: 
  453: sub resourcebrowser_javascript {
  454:    unless ($env{'request.course.id'}) { return ''; }
  455:    return (<<'ENDRESBRW');
  456: <script type="text/javascript" language="Javascript">
  457: // <![CDATA[
  458:     var reseditbrowser;
  459:     function openresbrowser(formname,reslink) {
  460:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  461:         var title = 'Resource_Browser';
  462:         var options = 'scrollbars=1,resizable=1,menubar=0';
  463:         options += ',width=700,height=500';
  464:         reseditbrowser = open(url,title,options,'1');
  465:         reseditbrowser.focus();
  466:     }
  467: // ]]>
  468: </script>
  469: ENDRESBRW
  470: }
  471: 
  472: sub selectstudent_link {
  473:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  474:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  475:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  476:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  477:    if ($env{'request.course.id'}) {  
  478:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  479: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  480: 					'/'.$env{'request.course.sec'})) {
  481: 	   return '';
  482:        }
  483:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  484:        if ($courseadvonly)  {
  485:            $callargs .= ",'',1,1";
  486:        }
  487:        return '<span class="LC_nobreak">'.
  488:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  489:               &mt('Select User').'</a></span>';
  490:    }
  491:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  492:        $callargs .= ",'',1"; 
  493:        return '<span class="LC_nobreak">'.
  494:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  495:               &mt('Select User').'</a></span>';
  496:    }
  497:    return '';
  498: }
  499: 
  500: sub selectresource_link {
  501:    my ($form,$reslink,$arg)=@_;
  502:    
  503:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  504:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  505:    unless ($env{'request.course.id'}) { return $arg; }
  506:    return '<span class="LC_nobreak">'.
  507:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  508:               $arg.'</a></span>';
  509: }
  510: 
  511: 
  512: 
  513: sub authorbrowser_javascript {
  514:     return <<"ENDAUTHORBRW";
  515: <script type="text/javascript" language="JavaScript">
  516: // <![CDATA[
  517: var stdeditbrowser;
  518: 
  519: function openauthorbrowser(formname,udom) {
  520:     var url = '/adm/pickauthor?';
  521:     url += 'form='+formname+'&roledom='+udom;
  522:     var title = 'Author_Browser';
  523:     var options = 'scrollbars=1,resizable=1,menubar=0';
  524:     options += ',width=700,height=600';
  525:     stdeditbrowser = open(url,title,options,'1');
  526:     stdeditbrowser.focus();
  527: }
  528: 
  529: // ]]>
  530: </script>
  531: ENDAUTHORBRW
  532: }
  533: 
  534: sub coursebrowser_javascript {
  535:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  536:         $credits_element,$instcode) = @_;
  537:     my $wintitle = 'Course_Browser';
  538:     if ($crstype eq 'Community') {
  539:         $wintitle = 'Community_Browser';
  540:     }
  541:     my $id_functions = &javascript_index_functions();
  542:     my $output = '
  543: <script type="text/javascript" language="JavaScript">
  544: // <![CDATA[
  545:     var stdeditbrowser;'."\n";
  546: 
  547:     $output .= <<"ENDSTDBRW";
  548:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  549:         var url = '/adm/pickcourse?';
  550:         var formid = getFormIdByName(formname);
  551:         var domainfilter = getDomainFromSelectbox(formname,udom);
  552:         if (domainfilter != null) {
  553:            if (domainfilter != '') {
  554:                url += 'domainfilter='+domainfilter+'&';
  555: 	   }
  556:         }
  557:         url += 'form=' + formname + '&cnumelement='+uname+
  558: 	                            '&cdomelement='+udom+
  559:                                     '&cnameelement='+desc;
  560:         if (extra_element !=null && extra_element != '') {
  561:             if (formname == 'rolechoice' || formname == 'studentform') {
  562:                 url += '&roleelement='+extra_element;
  563:                 if (domainfilter == null || domainfilter == '') {
  564:                     url += '&domainfilter='+extra_element;
  565:                 }
  566:             }
  567:             else {
  568:                 if (formname == 'portform') {
  569:                     url += '&setroles='+extra_element;
  570:                 } else {
  571:                     if (formname == 'rules') {
  572:                         url += '&fixeddom='+extra_element; 
  573:                     }
  574:                 }
  575:             }     
  576:         }
  577:         if (type != null && type != '') {
  578:             url += '&type='+type;
  579:         }
  580:         if (type_elem != null && type_elem != '') {
  581:             url += '&typeelement='+type_elem;
  582:         }
  583:         if (formname == 'ccrs') {
  584:             var ownername = document.forms[formid].ccuname.value;
  585:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  586:             url += '&cloner='+ownername+':'+ownerdom+'&crscode='+document.forms[formid].crscode.value;
  587:         }
  588:         if (formname == 'requestcrs') {
  589:             url += '&crsdom=$domainfilter&crscode=$instcode';
  590:         }
  591:         if (multflag !=null && multflag != '') {
  592:             url += '&multiple='+multflag;
  593:         }
  594:         var title = '$wintitle';
  595:         var options = 'scrollbars=1,resizable=1,menubar=0';
  596:         options += ',width=700,height=600';
  597:         stdeditbrowser = open(url,title,options,'1');
  598:         stdeditbrowser.focus();
  599:     }
  600: $id_functions
  601: ENDSTDBRW
  602:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  603:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  604:                                       $credits_element);
  605:     }
  606:     $output .= '
  607: // ]]>
  608: </script>';
  609:     return $output;
  610: }
  611: 
  612: sub javascript_index_functions {
  613:     return <<"ENDJS";
  614: 
  615: function getFormIdByName(formname) {
  616:     for (var i=0;i<document.forms.length;i++) {
  617:         if (document.forms[i].name == formname) {
  618:             return i;
  619:         }
  620:     }
  621:     return -1;
  622: }
  623: 
  624: function getIndexByName(formid,item) {
  625:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  626:         if (document.forms[formid].elements[i].name == item) {
  627:             return i;
  628:         }
  629:     }
  630:     return -1;
  631: }
  632: 
  633: function getDomainFromSelectbox(formname,udom) {
  634:     var userdom;
  635:     var formid = getFormIdByName(formname);
  636:     if (formid > -1) {
  637:         var domid = getIndexByName(formid,udom);
  638:         if (domid > -1) {
  639:             if (document.forms[formid].elements[domid].type == 'select-one') {
  640:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  641:             }
  642:             if (document.forms[formid].elements[domid].type == 'hidden') {
  643:                 userdom=document.forms[formid].elements[domid].value;
  644:             }
  645:         }
  646:     }
  647:     return userdom;
  648: }
  649: 
  650: ENDJS
  651: 
  652: }
  653: 
  654: sub javascript_array_indexof {
  655:     return <<ENDJS;
  656: <script type="text/javascript" language="JavaScript">
  657: // <![CDATA[
  658: 
  659: if (!Array.prototype.indexOf) {
  660:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  661:         "use strict";
  662:         if (this === void 0 || this === null) {
  663:             throw new TypeError();
  664:         }
  665:         var t = Object(this);
  666:         var len = t.length >>> 0;
  667:         if (len === 0) {
  668:             return -1;
  669:         }
  670:         var n = 0;
  671:         if (arguments.length > 0) {
  672:             n = Number(arguments[1]);
  673:             if (n !== n) { // shortcut for verifying if it's NaN
  674:                 n = 0;
  675:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  676:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  677:             }
  678:         }
  679:         if (n >= len) {
  680:             return -1;
  681:         }
  682:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  683:         for (; k < len; k++) {
  684:             if (k in t && t[k] === searchElement) {
  685:                 return k;
  686:             }
  687:         }
  688:         return -1;
  689:     }
  690: }
  691: 
  692: // ]]>
  693: </script>
  694: 
  695: ENDJS
  696: 
  697: }
  698: 
  699: sub userbrowser_javascript {
  700:     my $id_functions = &javascript_index_functions();
  701:     return <<"ENDUSERBRW";
  702: 
  703: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  704:     var url = '/adm/pickuser?';
  705:     var userdom = getDomainFromSelectbox(formname,udom);
  706:     if (userdom != null) {
  707:        if (userdom != '') {
  708:            url += 'srchdom='+userdom+'&';
  709:        }
  710:     }
  711:     url += 'form=' + formname + '&unameelement='+uname+
  712:                                 '&udomelement='+udom+
  713:                                 '&ulastelement='+ulast+
  714:                                 '&ufirstelement='+ufirst+
  715:                                 '&uemailelement='+uemail+
  716:                                 '&hideudomelement='+hideudom+
  717:                                 '&coursedom='+crsdom;
  718:     if ((caller != null) && (caller != undefined)) {
  719:         url += '&caller='+caller;
  720:     }
  721:     var title = 'User_Browser';
  722:     var options = 'scrollbars=1,resizable=1,menubar=0';
  723:     options += ',width=700,height=600';
  724:     var stdeditbrowser = open(url,title,options,'1');
  725:     stdeditbrowser.focus();
  726: }
  727: 
  728: function fix_domain (formname,udom,origdom,uname) {
  729:     var formid = getFormIdByName(formname);
  730:     if (formid > -1) {
  731:         var unameid = getIndexByName(formid,uname);
  732:         var domid = getIndexByName(formid,udom);
  733:         var hidedomid = getIndexByName(formid,origdom);
  734:         if (hidedomid > -1) {
  735:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  736:             var unameval = document.forms[formid].elements[unameid].value;
  737:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  738:                 if (domid > -1) {
  739:                     var slct = document.forms[formid].elements[domid];
  740:                     if (slct.type == 'select-one') {
  741:                         var i;
  742:                         for (i=0;i<slct.length;i++) {
  743:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  744:                         }
  745:                     }
  746:                     if (slct.type == 'hidden') {
  747:                         slct.value = fixeddom;
  748:                     }
  749:                 }
  750:             }
  751:         }
  752:     }
  753:     return;
  754: }
  755: 
  756: $id_functions
  757: ENDUSERBRW
  758: }
  759: 
  760: sub setsec_javascript {
  761:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  762:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  763:         $communityrolestr);
  764:     if ($role_element ne '') {
  765:         my @allroles = ('st','ta','ep','in','ad');
  766:         foreach my $crstype ('Course','Community') {
  767:             if ($crstype eq 'Community') {
  768:                 foreach my $role (@allroles) {
  769:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  770:                 }
  771:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  772:             } else {
  773:                 foreach my $role (@allroles) {
  774:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  775:                 }
  776:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  777:             }
  778:         }
  779:         $rolestr = '"'.join('","',@allroles).'"';
  780:         $courserolestr = '"'.join('","',@courserolenames).'"';
  781:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  782:     }
  783:     my $setsections = qq|
  784: function setSect(sectionlist) {
  785:     var sectionsArray = new Array();
  786:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  787:         sectionsArray = sectionlist.split(",");
  788:     }
  789:     var numSections = sectionsArray.length;
  790:     document.$formname.$sec_element.length = 0;
  791:     if (numSections == 0) {
  792:         document.$formname.$sec_element.multiple=false;
  793:         document.$formname.$sec_element.size=1;
  794:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  795:     } else {
  796:         if (numSections == 1) {
  797:             document.$formname.$sec_element.multiple=false;
  798:             document.$formname.$sec_element.size=1;
  799:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  800:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  801:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  802:         } else {
  803:             for (var i=0; i<numSections; i++) {
  804:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  805:             }
  806:             document.$formname.$sec_element.multiple=true
  807:             if (numSections < 3) {
  808:                 document.$formname.$sec_element.size=numSections;
  809:             } else {
  810:                 document.$formname.$sec_element.size=3;
  811:             }
  812:             document.$formname.$sec_element.options[0].selected = false
  813:         }
  814:     }
  815: }
  816: 
  817: function setRole(crstype) {
  818: |;
  819:     if ($role_element eq '') {
  820:         $setsections .= '    return;
  821: }
  822: ';
  823:     } else {
  824:         $setsections .= qq|
  825:     var elementLength = document.$formname.$role_element.length;
  826:     var allroles = Array($rolestr);
  827:     var courserolenames = Array($courserolestr);
  828:     var communityrolenames = Array($communityrolestr);
  829:     if (elementLength != undefined) {
  830:         if (document.$formname.$role_element.options[5].value == 'cc') {
  831:             if (crstype == 'Course') {
  832:                 return;
  833:             } else {
  834:                 allroles[5] = 'co';
  835:                 for (var i=0; i<6; i++) {
  836:                     document.$formname.$role_element.options[i].value = allroles[i];
  837:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  838:                 }
  839:             }
  840:         } else {
  841:             if (crstype == 'Community') {
  842:                 return;
  843:             } else {
  844:                 allroles[5] = 'cc';
  845:                 for (var i=0; i<6; i++) {
  846:                     document.$formname.$role_element.options[i].value = allroles[i];
  847:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  848:                 }
  849:             }
  850:         }
  851:     }
  852:     return;
  853: }
  854: |;
  855:     }
  856:     if ($credits_element) {
  857:         $setsections .= qq|
  858: function setCredits(defaultcredits) {
  859:     document.$formname.$credits_element.value = defaultcredits;
  860:     return;
  861: }
  862: |;
  863:     }
  864:     return $setsections;
  865: }
  866: 
  867: sub selectcourse_link {
  868:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  869:        $typeelement) = @_;
  870:    my $type = $selecttype;
  871:    my $linktext = &mt('Select Course');
  872:    if ($selecttype eq 'Community') {
  873:        $linktext = &mt('Select Community');
  874:    } elsif ($selecttype eq 'Course/Community') {
  875:        $linktext = &mt('Select Course/Community');
  876:        $type = '';
  877:    } elsif ($selecttype eq 'Select') {
  878:        $linktext = &mt('Select');
  879:        $type = '';
  880:    }
  881:    return '<span class="LC_nobreak">'
  882:          ."<a href='"
  883:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  884:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  885:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  886:          ."'>".$linktext.'</a>'
  887:          .'</span>';
  888: }
  889: 
  890: sub selectauthor_link {
  891:    my ($form,$udom)=@_;
  892:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  893:           &mt('Select Author').'</a>';
  894: }
  895: 
  896: sub selectuser_link {
  897:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  898:         $coursedom,$linktext,$caller) = @_;
  899:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  900:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  901:            ');">'.$linktext.'</a>';
  902: }
  903: 
  904: sub check_uncheck_jscript {
  905:     my $jscript = <<"ENDSCRT";
  906: function checkAll(field) {
  907:     if (field.length > 0) {
  908:         for (i = 0; i < field.length; i++) {
  909:             if (!field[i].disabled) {
  910:                 field[i].checked = true;
  911:             }
  912:         }
  913:     } else {
  914:         if (!field.disabled) {
  915:             field.checked = true;
  916:         }
  917:     }
  918: }
  919:  
  920: function uncheckAll(field) {
  921:     if (field.length > 0) {
  922:         for (i = 0; i < field.length; i++) {
  923:             field[i].checked = false ;
  924:         }
  925:     } else {
  926:         field.checked = false ;
  927:     }
  928: }
  929: ENDSCRT
  930:     return $jscript;
  931: }
  932: 
  933: sub select_timezone {
  934:    my ($name,$selected,$onchange,$includeempty)=@_;
  935:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  936:    if ($includeempty) {
  937:        $output .= '<option value=""';
  938:        if (($selected eq '') || ($selected eq 'local')) {
  939:            $output .= ' selected="selected" ';
  940:        }
  941:        $output .= '> </option>';
  942:    }
  943:    my @timezones = DateTime::TimeZone->all_names;
  944:    foreach my $tzone (@timezones) {
  945:        $output.= '<option value="'.$tzone.'"';
  946:        if ($tzone eq $selected) {
  947:            $output.=' selected="selected"';
  948:        }
  949:        $output.=">$tzone</option>\n";
  950:    }
  951:    $output.="</select>";
  952:    return $output;
  953: }
  954: 
  955: sub select_datelocale {
  956:     my ($name,$selected,$onchange,$includeempty)=@_;
  957:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  958:     if ($includeempty) {
  959:         $output .= '<option value=""';
  960:         if ($selected eq '') {
  961:             $output .= ' selected="selected" ';
  962:         }
  963:         $output .= '> </option>';
  964:     }
  965:     my (@possibles,%locale_names);
  966:     my @locales = DateTime::Locale::Catalog::Locales;
  967:     foreach my $locale (@locales) {
  968:         if (ref($locale) eq 'HASH') {
  969:             my $id = $locale->{'id'};
  970:             if ($id ne '') {
  971:                 my $en_terr = $locale->{'en_territory'};
  972:                 my $native_terr = $locale->{'native_territory'};
  973:                 my @languages = &Apache::lonlocal::preferred_languages();
  974:                 if (grep(/^en$/,@languages) || !@languages) {
  975:                     if ($en_terr ne '') {
  976:                         $locale_names{$id} = '('.$en_terr.')';
  977:                     } elsif ($native_terr ne '') {
  978:                         $locale_names{$id} = $native_terr;
  979:                     }
  980:                 } else {
  981:                     if ($native_terr ne '') {
  982:                         $locale_names{$id} = $native_terr.' ';
  983:                     } elsif ($en_terr ne '') {
  984:                         $locale_names{$id} = '('.$en_terr.')';
  985:                     }
  986:                 }
  987:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  988:                 push (@possibles,$id);
  989:             }
  990:         }
  991:     }
  992:     foreach my $item (sort(@possibles)) {
  993:         $output.= '<option value="'.$item.'"';
  994:         if ($item eq $selected) {
  995:             $output.=' selected="selected"';
  996:         }
  997:         $output.=">$item";
  998:         if ($locale_names{$item} ne '') {
  999:             $output.='  '.$locale_names{$item};
 1000:         }
 1001:         $output.="</option>\n";
 1002:     }
 1003:     $output.="</select>";
 1004:     return $output;
 1005: }
 1006: 
 1007: sub select_language {
 1008:     my ($name,$selected,$includeempty) = @_;
 1009:     my %langchoices;
 1010:     if ($includeempty) {
 1011:         %langchoices = ('' => 'No language preference');
 1012:     }
 1013:     foreach my $id (&languageids()) {
 1014:         my $code = &supportedlanguagecode($id);
 1015:         if ($code) {
 1016:             $langchoices{$code} = &plainlanguagedescription($id);
 1017:         }
 1018:     }
 1019:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1020:     return &select_form($selected,$name,\%langchoices);
 1021: }
 1022: 
 1023: =pod
 1024: 
 1025: =item * &linked_select_forms(...)
 1026: 
 1027: linked_select_forms returns a string containing a <script></script> block
 1028: and html for two <select> menus.  The select menus will be linked in that
 1029: changing the value of the first menu will result in new values being placed
 1030: in the second menu.  The values in the select menu will appear in alphabetical
 1031: order unless a defined order is provided.
 1032: 
 1033: linked_select_forms takes the following ordered inputs:
 1034: 
 1035: =over 4
 1036: 
 1037: =item * $formname, the name of the <form> tag
 1038: 
 1039: =item * $middletext, the text which appears between the <select> tags
 1040: 
 1041: =item * $firstdefault, the default value for the first menu
 1042: 
 1043: =item * $firstselectname, the name of the first <select> tag
 1044: 
 1045: =item * $secondselectname, the name of the second <select> tag
 1046: 
 1047: =item * $hashref, a reference to a hash containing the data for the menus.
 1048: 
 1049: =item * $menuorder, the order of values in the first menu
 1050: 
 1051: =item * $onchangefirst, additional javascript call to execute for an onchange
 1052:         event for the first <select> tag
 1053: 
 1054: =item * $onchangesecond, additional javascript call to execute for an onchange
 1055:         event for the second <select> tag
 1056: 
 1057: =back 
 1058: 
 1059: Below is an example of such a hash.  Only the 'text', 'default', and 
 1060: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1061: values for the first select menu.  The text that coincides with the 
 1062: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1063: and text for the second menu are given in the hash pointed to by 
 1064: $menu{$choice1}->{'select2'}.  
 1065: 
 1066:  my %menu = ( A1 => { text =>"Choice A1" ,
 1067:                        default => "B3",
 1068:                        select2 => { 
 1069:                            B1 => "Choice B1",
 1070:                            B2 => "Choice B2",
 1071:                            B3 => "Choice B3",
 1072:                            B4 => "Choice B4"
 1073:                            },
 1074:                        order => ['B4','B3','B1','B2'],
 1075:                    },
 1076:                A2 => { text =>"Choice A2" ,
 1077:                        default => "C2",
 1078:                        select2 => { 
 1079:                            C1 => "Choice C1",
 1080:                            C2 => "Choice C2",
 1081:                            C3 => "Choice C3"
 1082:                            },
 1083:                        order => ['C2','C1','C3'],
 1084:                    },
 1085:                A3 => { text =>"Choice A3" ,
 1086:                        default => "D6",
 1087:                        select2 => { 
 1088:                            D1 => "Choice D1",
 1089:                            D2 => "Choice D2",
 1090:                            D3 => "Choice D3",
 1091:                            D4 => "Choice D4",
 1092:                            D5 => "Choice D5",
 1093:                            D6 => "Choice D6",
 1094:                            D7 => "Choice D7"
 1095:                            },
 1096:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1097:                    }
 1098:                );
 1099: 
 1100: =cut
 1101: 
 1102: sub linked_select_forms {
 1103:     my ($formname,
 1104:         $middletext,
 1105:         $firstdefault,
 1106:         $firstselectname,
 1107:         $secondselectname, 
 1108:         $hashref,
 1109:         $menuorder,
 1110:         $onchangefirst,
 1111:         $onchangesecond
 1112:         ) = @_;
 1113:     my $second = "document.$formname.$secondselectname";
 1114:     my $first = "document.$formname.$firstselectname";
 1115:     # output the javascript to do the changing
 1116:     my $result = '';
 1117:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1118:     $result.="// <![CDATA[\n";
 1119:     $result.="var select2data = new Object();\n";
 1120:     $" = '","';
 1121:     my $debug = '';
 1122:     foreach my $s1 (sort(keys(%$hashref))) {
 1123:         $result.="select2data.d_$s1 = new Object();\n";        
 1124:         $result.="select2data.d_$s1.def = new String('".
 1125:             $hashref->{$s1}->{'default'}."');\n";
 1126:         $result.="select2data.d_$s1.values = new Array(";
 1127:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1128:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1129:             @s2values = @{$hashref->{$s1}->{'order'}};
 1130:         }
 1131:         $result.="\"@s2values\");\n";
 1132:         $result.="select2data.d_$s1.texts = new Array(";        
 1133:         my @s2texts;
 1134:         foreach my $value (@s2values) {
 1135:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1136:         }
 1137:         $result.="\"@s2texts\");\n";
 1138:     }
 1139:     $"=' ';
 1140:     $result.= <<"END";
 1141: 
 1142: function select1_changed() {
 1143:     // Determine new choice
 1144:     var newvalue = "d_" + $first.value;
 1145:     // update select2
 1146:     var values     = select2data[newvalue].values;
 1147:     var texts      = select2data[newvalue].texts;
 1148:     var select2def = select2data[newvalue].def;
 1149:     var i;
 1150:     // out with the old
 1151:     for (i = 0; i < $second.options.length; i++) {
 1152:         $second.options[i] = null;
 1153:     }
 1154:     // in with the nuclear
 1155:     for (i=0;i<values.length; i++) {
 1156:         $second.options[i] = new Option(values[i]);
 1157:         $second.options[i].value = values[i];
 1158:         $second.options[i].text = texts[i];
 1159:         if (values[i] == select2def) {
 1160:             $second.options[i].selected = true;
 1161:         }
 1162:     }
 1163: }
 1164: // ]]>
 1165: </script>
 1166: END
 1167:     # output the initial values for the selection lists
 1168:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1169:     my @order = sort(keys(%{$hashref}));
 1170:     if (ref($menuorder) eq 'ARRAY') {
 1171:         @order = @{$menuorder};
 1172:     }
 1173:     foreach my $value (@order) {
 1174:         $result.="    <option value=\"$value\" ";
 1175:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1176:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1177:     }
 1178:     $result .= "</select>\n";
 1179:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1180:     $result .= $middletext;
 1181:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1182:     if ($onchangesecond) {
 1183:         $result .= ' onchange="'.$onchangesecond.'"';
 1184:     }
 1185:     $result .= ">\n";
 1186:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1187:     
 1188:     my @secondorder = sort(keys(%select2));
 1189:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1190:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1191:     }
 1192:     foreach my $value (@secondorder) {
 1193:         $result.="    <option value=\"$value\" ";        
 1194:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1195:         $result.=">".&mt($select2{$value})."</option>\n";
 1196:     }
 1197:     $result .= "</select>\n";
 1198:     #    return $debug;
 1199:     return $result;
 1200: }   #  end of sub linked_select_forms {
 1201: 
 1202: =pod
 1203: 
 1204: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1205: 
 1206: Returns a string corresponding to an HTML link to the given help
 1207: $topic, where $topic corresponds to the name of a .tex file in
 1208: /home/httpd/html/adm/help/tex, with underscores replaced by
 1209: spaces. 
 1210: 
 1211: $text will optionally be linked to the same topic, allowing you to
 1212: link text in addition to the graphic. If you do not want to link
 1213: text, but wish to specify one of the later parameters, pass an
 1214: empty string. 
 1215: 
 1216: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1217: the link will not open a new window. If false, the link will open
 1218: a new window using Javascript. (Default is false.) 
 1219: 
 1220: $width and $height are optional numerical parameters that will
 1221: override the width and height of the popped up window, which may
 1222: be useful for certain help topics with big pictures included.
 1223: 
 1224: $imgid is the id of the img tag used for the help icon. This may be
 1225: used in a javascript call to switch the image src.  See 
 1226: lonhtmlcommon::htmlareaselectactive() for an example.
 1227: 
 1228: =cut
 1229: 
 1230: sub help_open_topic {
 1231:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1232:     $text = "" if (not defined $text);
 1233:     $stayOnPage = 0 if (not defined $stayOnPage);
 1234:     $width = 500 if (not defined $width);
 1235:     $height = 400 if (not defined $height);
 1236:     my $filename = $topic;
 1237:     $filename =~ s/ /_/g;
 1238: 
 1239:     my $template = "";
 1240:     my $link;
 1241:     
 1242:     $topic=~s/\W/\_/g;
 1243: 
 1244:     if (!$stayOnPage) {
 1245:         if ($env{'browser.mobile'}) {
 1246: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1247:         } else {
 1248:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1249:         }
 1250:     } elsif ($stayOnPage eq 'popup') {
 1251:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1252:     } else {
 1253: 	$link = "/adm/help/${filename}.hlp";
 1254:     }
 1255: 
 1256:     # Add the text
 1257:     if ($text ne "") {	
 1258: 	$template.='<span class="LC_help_open_topic">'
 1259:                   .'<a target="_top" href="'.$link.'">'
 1260:                   .$text.'</a>';
 1261:     }
 1262: 
 1263:     # (Always) Add the graphic
 1264:     my $title = &mt('Online Help');
 1265:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1266:     if ($imgid ne '') {
 1267:         $imgid = ' id="'.$imgid.'"';
 1268:     }
 1269:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1270:               .'<img src="'.$helpicon.'" border="0"'
 1271:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1272:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1273:               .' /></a>';
 1274:     if ($text ne "") {	
 1275:         $template.='</span>';
 1276:     }
 1277:     return $template;
 1278: 
 1279: }
 1280: 
 1281: # This is a quicky function for Latex cheatsheet editing, since it 
 1282: # appears in at least four places
 1283: sub helpLatexCheatsheet {
 1284:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1285:     my $out;
 1286:     my $addOther = '';
 1287:     if ($topic) {
 1288: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1289:     }
 1290:     $out = '<span>' # Start cheatsheet
 1291: 	  .$addOther
 1292:           .'<span>'
 1293: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1294: 	  .'</span> <span>'
 1295: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1296: 	  .'</span>';
 1297:     unless ($not_author) {
 1298:         $out .= ' <span>'
 1299: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1300: 	       .'</span> <span>'
 1301:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1302:                .'</span>';
 1303:     }
 1304:     $out .= '</span>'; # End cheatsheet
 1305:     return $out;
 1306: }
 1307: 
 1308: sub general_help {
 1309:     my $helptopic='Student_Intro';
 1310:     if ($env{'request.role'}=~/^(ca|au)/) {
 1311: 	$helptopic='Authoring_Intro';
 1312:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1313: 	$helptopic='Course_Coordination_Intro';
 1314:     } elsif ($env{'request.role'}=~/^dc/) {
 1315:         $helptopic='Domain_Coordination_Intro';
 1316:     }
 1317:     return $helptopic;
 1318: }
 1319: 
 1320: sub update_help_link {
 1321:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1322:     my $origurl = $ENV{'REQUEST_URI'};
 1323:     $origurl=~s|^/~|/priv/|;
 1324:     my $timestamp = time;
 1325:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1326:         $$datum = &escape($$datum);
 1327:     }
 1328: 
 1329:     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";
 1330:     my $output .= <<"ENDOUTPUT";
 1331: <script type="text/javascript">
 1332: // <![CDATA[
 1333: banner_link = '$banner_link';
 1334: // ]]>
 1335: </script>
 1336: ENDOUTPUT
 1337:     return $output;
 1338: }
 1339: 
 1340: # now just updates the help link and generates a blue icon
 1341: sub help_open_menu {
 1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1343: 	= @_;    
 1344:     $stayOnPage = 1;
 1345:     my $output;
 1346:     if ($component_help) {
 1347: 	if (!$text) {
 1348: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1349: 				       $width,$height);
 1350: 	} else {
 1351: 	    my $help_text;
 1352: 	    $help_text=&unescape($topic);
 1353: 	    $output='<table><tr><td>'.
 1354: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1355: 				 $width,$height).'</td></tr></table>';
 1356: 	}
 1357:     }
 1358:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1359:     return $output.$banner_link;
 1360: }
 1361: 
 1362: sub top_nav_help {
 1363:     my ($text) = @_;
 1364:     $text = &mt($text);
 1365:     my $stay_on_page;
 1366:     unless ($env{'environment.remote'} eq 'on') {
 1367:         $stay_on_page = 1;
 1368:     }
 1369:     my ($link,$banner_link);
 1370:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1371:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1372: 	                         : "javascript:helpMenu('open')";
 1373:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1374:     }
 1375:     my $title = &mt('Get help');
 1376:     if ($link) {
 1377:         return <<"END";
 1378: $banner_link
 1379: <a href="$link" title="$title">$text</a>
 1380: END
 1381:     } else {
 1382:         return '&nbsp;'.$text.'&nbsp;';
 1383:     }
 1384: }
 1385: 
 1386: sub help_menu_js {
 1387:     my ($httphost) = @_;
 1388:     my $stayOnPage = 1;
 1389:     my $width = 620;
 1390:     my $height = 600;
 1391:     my $helptopic=&general_help();
 1392:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1393:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1394:     my $start_page =
 1395:         &Apache::loncommon::start_page('Help Menu', undef,
 1396: 				       {'frameset'    => 1,
 1397: 					'js_ready'    => 1,
 1398:                                         'use_absolute' => $httphost, 
 1399: 					'add_entries' => {
 1400: 					    'border' => '0',
 1401: 					    'rows'   => "110,*",},});
 1402:     my $end_page =
 1403:         &Apache::loncommon::end_page({'frameset' => 1,
 1404: 				      'js_ready' => 1,});
 1405: 
 1406:     my $template .= <<"ENDTEMPLATE";
 1407: <script type="text/javascript">
 1408: // <![CDATA[
 1409: // <!-- BEGIN LON-CAPA Internal
 1410: var banner_link = '';
 1411: function helpMenu(target) {
 1412:     var caller = this;
 1413:     if (target == 'open') {
 1414:         var newWindow = null;
 1415:         try {
 1416:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1417:         }
 1418:         catch(error) {
 1419:             writeHelp(caller);
 1420:             return;
 1421:         }
 1422:         if (newWindow) {
 1423:             caller = newWindow;
 1424:         }
 1425:     }
 1426:     writeHelp(caller);
 1427:     return;
 1428: }
 1429: function writeHelp(caller) {
 1430:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1431:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1432:     caller.document.close();
 1433:     caller.focus();
 1434: }
 1435: // END LON-CAPA Internal -->
 1436: // ]]>
 1437: </script>
 1438: ENDTEMPLATE
 1439:     return $template;
 1440: }
 1441: 
 1442: sub help_open_bug {
 1443:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1444:     unless ($env{'user.adv'}) { return ''; }
 1445:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1446:     $text = "" if (not defined $text);
 1447: 	$stayOnPage=1;
 1448:     $width = 600 if (not defined $width);
 1449:     $height = 600 if (not defined $height);
 1450: 
 1451:     $topic=~s/\W+/\+/g;
 1452:     my $link='';
 1453:     my $template='';
 1454:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1455: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1456:     if (!$stayOnPage)
 1457:     {
 1458: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1459:     }
 1460:     else
 1461:     {
 1462: 	$link = $url;
 1463:     }
 1464:     # Add the text
 1465:     if ($text ne "")
 1466:     {
 1467: 	$template .= 
 1468:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1469:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1470:     }
 1471: 
 1472:     # Add the graphic
 1473:     my $title = &mt('Report a Bug');
 1474:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1475:     $template .= <<"ENDTEMPLATE";
 1476:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1477: ENDTEMPLATE
 1478:     if ($text ne '') { $template.='</td></tr></table>' };
 1479:     return $template;
 1480: 
 1481: }
 1482: 
 1483: sub help_open_faq {
 1484:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1485:     unless ($env{'user.adv'}) { return ''; }
 1486:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1487:     $text = "" if (not defined $text);
 1488: 	$stayOnPage=1;
 1489:     $width = 350 if (not defined $width);
 1490:     $height = 400 if (not defined $height);
 1491: 
 1492:     $topic=~s/\W+/\+/g;
 1493:     my $link='';
 1494:     my $template='';
 1495:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1496:     if (!$stayOnPage)
 1497:     {
 1498: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1499:     }
 1500:     else
 1501:     {
 1502: 	$link = $url;
 1503:     }
 1504: 
 1505:     # Add the text
 1506:     if ($text ne "")
 1507:     {
 1508: 	$template .= 
 1509:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1510:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1511:     }
 1512: 
 1513:     # Add the graphic
 1514:     my $title = &mt('View the FAQ');
 1515:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1516:     $template .= <<"ENDTEMPLATE";
 1517:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1518: ENDTEMPLATE
 1519:     if ($text ne '') { $template.='</td></tr></table>' };
 1520:     return $template;
 1521: 
 1522: }
 1523: 
 1524: ###############################################################
 1525: ###############################################################
 1526: 
 1527: =pod
 1528: 
 1529: =item * &change_content_javascript():
 1530: 
 1531: This and the next function allow you to create small sections of an
 1532: otherwise static HTML page that you can update on the fly with
 1533: Javascript, even in Netscape 4.
 1534: 
 1535: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1536: must be written to the HTML page once. It will prove the Javascript
 1537: function "change(name, content)". Calling the change function with the
 1538: name of the section 
 1539: you want to update, matching the name passed to C<changable_area>, and
 1540: the new content you want to put in there, will put the content into
 1541: that area.
 1542: 
 1543: B<Note>: Netscape 4 only reserves enough space for the changable area
 1544: to contain room for the original contents. You need to "make space"
 1545: for whatever changes you wish to make, and be B<sure> to check your
 1546: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1547: it's adequate for updating a one-line status display, but little more.
 1548: This script will set the space to 100% width, so you only need to
 1549: worry about height in Netscape 4.
 1550: 
 1551: Modern browsers are much less limiting, and if you can commit to the
 1552: user not using Netscape 4, this feature may be used freely with
 1553: pretty much any HTML.
 1554: 
 1555: =cut
 1556: 
 1557: sub change_content_javascript {
 1558:     # If we're on Netscape 4, we need to use Layer-based code
 1559:     if ($env{'browser.type'} eq 'netscape' &&
 1560: 	$env{'browser.version'} =~ /^4\./) {
 1561: 	return (<<NETSCAPE4);
 1562: 	function change(name, content) {
 1563: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1564: 	    doc.open();
 1565: 	    doc.write(content);
 1566: 	    doc.close();
 1567: 	}
 1568: NETSCAPE4
 1569:     } else {
 1570: 	# Otherwise, we need to use semi-standards-compliant code
 1571: 	# (technically, "innerHTML" isn't standard but the equivalent
 1572: 	# is really scary, and every useful browser supports it
 1573: 	return (<<DOMBASED);
 1574: 	function change(name, content) {
 1575: 	    element = document.getElementById(name);
 1576: 	    element.innerHTML = content;
 1577: 	}
 1578: DOMBASED
 1579:     }
 1580: }
 1581: 
 1582: =pod
 1583: 
 1584: =item * &changable_area($name,$origContent):
 1585: 
 1586: This provides a "changable area" that can be modified on the fly via
 1587: the Javascript code provided in C<change_content_javascript>. $name is
 1588: the name you will use to reference the area later; do not repeat the
 1589: same name on a given HTML page more then once. $origContent is what
 1590: the area will originally contain, which can be left blank.
 1591: 
 1592: =cut
 1593: 
 1594: sub changable_area {
 1595:     my ($name, $origContent) = @_;
 1596: 
 1597:     if ($env{'browser.type'} eq 'netscape' &&
 1598: 	$env{'browser.version'} =~ /^4\./) {
 1599: 	# If this is netscape 4, we need to use the Layer tag
 1600: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1601:     } else {
 1602: 	return "<span id='$name'>$origContent</span>";
 1603:     }
 1604: }
 1605: 
 1606: =pod
 1607: 
 1608: =item * &viewport_geometry_js 
 1609: 
 1610: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1611: 
 1612: =cut
 1613: 
 1614: 
 1615: sub viewport_geometry_js { 
 1616:     return <<"GEOMETRY";
 1617: var Geometry = {};
 1618: function init_geometry() {
 1619:     if (Geometry.init) { return };
 1620:     Geometry.init=1;
 1621:     if (window.innerHeight) {
 1622:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1623:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1624:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1625:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1626:     }
 1627:     else if (document.documentElement && document.documentElement.clientHeight) {
 1628:         Geometry.getViewportHeight =
 1629:             function() { return document.documentElement.clientHeight; };
 1630:         Geometry.getViewportWidth =
 1631:             function() { return document.documentElement.clientWidth; };
 1632: 
 1633:         Geometry.getHorizontalScroll =
 1634:             function() { return document.documentElement.scrollLeft; };
 1635:         Geometry.getVerticalScroll =
 1636:             function() { return document.documentElement.scrollTop; };
 1637:     }
 1638:     else if (document.body.clientHeight) {
 1639:         Geometry.getViewportHeight =
 1640:             function() { return document.body.clientHeight; };
 1641:         Geometry.getViewportWidth =
 1642:             function() { return document.body.clientWidth; };
 1643:         Geometry.getHorizontalScroll =
 1644:             function() { return document.body.scrollLeft; };
 1645:         Geometry.getVerticalScroll =
 1646:             function() { return document.body.scrollTop; };
 1647:     }
 1648: }
 1649: 
 1650: GEOMETRY
 1651: }
 1652: 
 1653: =pod
 1654: 
 1655: =item * &viewport_size_js()
 1656: 
 1657: 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. 
 1658: 
 1659: =cut
 1660: 
 1661: sub viewport_size_js {
 1662:     my $geometry = &viewport_geometry_js();
 1663:     return <<"DIMS";
 1664: 
 1665: $geometry
 1666: 
 1667: function getViewportDims(width,height) {
 1668:     init_geometry();
 1669:     width.value = Geometry.getViewportWidth();
 1670:     height.value = Geometry.getViewportHeight();
 1671:     return;
 1672: }
 1673: 
 1674: DIMS
 1675: }
 1676: 
 1677: =pod
 1678: 
 1679: =item * &resize_textarea_js()
 1680: 
 1681: emits the needed javascript to resize a textarea to be as big as possible
 1682: 
 1683: creates a function resize_textrea that takes two IDs first should be
 1684: the id of the element to resize, second should be the id of a div that
 1685: surrounds everything that comes after the textarea, this routine needs
 1686: to be attached to the <body> for the onload and onresize events.
 1687: 
 1688: =back
 1689: 
 1690: =cut
 1691: 
 1692: sub resize_textarea_js {
 1693:     my $geometry = &viewport_geometry_js();
 1694:     return <<"RESIZE";
 1695:     <script type="text/javascript">
 1696: // <![CDATA[
 1697: $geometry
 1698: 
 1699: function getX(element) {
 1700:     var x = 0;
 1701:     while (element) {
 1702: 	x += element.offsetLeft;
 1703: 	element = element.offsetParent;
 1704:     }
 1705:     return x;
 1706: }
 1707: function getY(element) {
 1708:     var y = 0;
 1709:     while (element) {
 1710: 	y += element.offsetTop;
 1711: 	element = element.offsetParent;
 1712:     }
 1713:     return y;
 1714: }
 1715: 
 1716: 
 1717: function resize_textarea(textarea_id,bottom_id) {
 1718:     init_geometry();
 1719:     var textarea        = document.getElementById(textarea_id);
 1720:     //alert(textarea);
 1721: 
 1722:     var textarea_top    = getY(textarea);
 1723:     var textarea_height = textarea.offsetHeight;
 1724:     var bottom          = document.getElementById(bottom_id);
 1725:     var bottom_top      = getY(bottom);
 1726:     var bottom_height   = bottom.offsetHeight;
 1727:     var window_height   = Geometry.getViewportHeight();
 1728:     var fudge           = 23;
 1729:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1730:     if (new_height < 300) {
 1731: 	new_height = 300;
 1732:     }
 1733:     textarea.style.height=new_height+'px';
 1734: }
 1735: // ]]>
 1736: </script>
 1737: RESIZE
 1738: 
 1739: }
 1740: 
 1741: =pod
 1742: 
 1743: =head1 Excel and CSV file utility routines
 1744: 
 1745: =cut
 1746: 
 1747: ###############################################################
 1748: ###############################################################
 1749: 
 1750: =pod
 1751: 
 1752: =over 4
 1753: 
 1754: =item * &csv_translate($text) 
 1755: 
 1756: Translate $text to allow it to be output as a 'comma separated values' 
 1757: format.
 1758: 
 1759: =cut
 1760: 
 1761: ###############################################################
 1762: ###############################################################
 1763: sub csv_translate {
 1764:     my $text = shift;
 1765:     $text =~ s/\"/\"\"/g;
 1766:     $text =~ s/\n/ /g;
 1767:     return $text;
 1768: }
 1769: 
 1770: ###############################################################
 1771: ###############################################################
 1772: 
 1773: =pod
 1774: 
 1775: =item * &define_excel_formats()
 1776: 
 1777: Define some commonly used Excel cell formats.
 1778: 
 1779: Currently supported formats:
 1780: 
 1781: =over 4
 1782: 
 1783: =item header
 1784: 
 1785: =item bold
 1786: 
 1787: =item h1
 1788: 
 1789: =item h2
 1790: 
 1791: =item h3
 1792: 
 1793: =item h4
 1794: 
 1795: =item i
 1796: 
 1797: =item date
 1798: 
 1799: =back
 1800: 
 1801: Inputs: $workbook
 1802: 
 1803: Returns: $format, a hash reference.
 1804: 
 1805: 
 1806: =cut
 1807: 
 1808: ###############################################################
 1809: ###############################################################
 1810: sub define_excel_formats {
 1811:     my ($workbook) = @_;
 1812:     my $format;
 1813:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1814:                                                 bottom    => 1,
 1815:                                                 align     => 'center');
 1816:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1817:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1818:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1819:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1820:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1821:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1822:     $format->{'date'} = $workbook->add_format(num_format=>
 1823:                                             'mm/dd/yyyy hh:mm:ss');
 1824:     return $format;
 1825: }
 1826: 
 1827: ###############################################################
 1828: ###############################################################
 1829: 
 1830: =pod
 1831: 
 1832: =item * &create_workbook()
 1833: 
 1834: Create an Excel worksheet.  If it fails, output message on the
 1835: request object and return undefs.
 1836: 
 1837: Inputs: Apache request object
 1838: 
 1839: Returns (undef) on failure, 
 1840:     Excel worksheet object, scalar with filename, and formats 
 1841:     from &Apache::loncommon::define_excel_formats on success
 1842: 
 1843: =cut
 1844: 
 1845: ###############################################################
 1846: ###############################################################
 1847: sub create_workbook {
 1848:     my ($r) = @_;
 1849:         #
 1850:     # Create the excel spreadsheet
 1851:     my $filename = '/prtspool/'.
 1852:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1853:         time.'_'.rand(1000000000).'.xls';
 1854:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1855:     if (! defined($workbook)) {
 1856:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1857:         $r->print(
 1858:             '<p class="LC_error">'
 1859:            .&mt('Problems occurred in creating the new Excel file.')
 1860:            .' '.&mt('This error has been logged.')
 1861:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1862:            .'</p>'
 1863:         );
 1864:         return (undef);
 1865:     }
 1866:     #
 1867:     $workbook->set_tempdir(LONCAPA::tempdir());
 1868:     #
 1869:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1870:     return ($workbook,$filename,$format);
 1871: }
 1872: 
 1873: ###############################################################
 1874: ###############################################################
 1875: 
 1876: =pod
 1877: 
 1878: =item * &create_text_file()
 1879: 
 1880: Create a file to write to and eventually make available to the user.
 1881: If file creation fails, outputs an error message on the request object and 
 1882: return undefs.
 1883: 
 1884: Inputs: Apache request object, and file suffix
 1885: 
 1886: Returns (undef) on failure, 
 1887:     Filehandle and filename on success.
 1888: 
 1889: =cut
 1890: 
 1891: ###############################################################
 1892: ###############################################################
 1893: sub create_text_file {
 1894:     my ($r,$suffix) = @_;
 1895:     if (! defined($suffix)) { $suffix = 'txt'; };
 1896:     my $fh;
 1897:     my $filename = '/prtspool/'.
 1898:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1899:         time.'_'.rand(1000000000).'.'.$suffix;
 1900:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1901:     if (! defined($fh)) {
 1902:         $r->log_error("Couldn't open $filename for output $!");
 1903:         $r->print(
 1904:             '<p class="LC_error">'
 1905:            .&mt('Problems occurred in creating the output file.')
 1906:            .' '.&mt('This error has been logged.')
 1907:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1908:            .'</p>'
 1909:         );
 1910:     }
 1911:     return ($fh,$filename)
 1912: }
 1913: 
 1914: 
 1915: =pod 
 1916: 
 1917: =back
 1918: 
 1919: =cut
 1920: 
 1921: ###############################################################
 1922: ##        Home server <option> list generating code          ##
 1923: ###############################################################
 1924: 
 1925: # ------------------------------------------
 1926: 
 1927: sub domain_select {
 1928:     my ($name,$value,$multiple)=@_;
 1929:     my %domains=map { 
 1930: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1931:     } &Apache::lonnet::all_domains();
 1932:     if ($multiple) {
 1933: 	$domains{''}=&mt('Any domain');
 1934: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1935: 	return &multiple_select_form($name,$value,4,\%domains);
 1936:     } else {
 1937: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1938: 	return &select_form($name,$value,\%domains);
 1939:     }
 1940: }
 1941: 
 1942: #-------------------------------------------
 1943: 
 1944: =pod
 1945: 
 1946: =head1 Routines for form select boxes
 1947: 
 1948: =over 4
 1949: 
 1950: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1951: 
 1952: Returns a string containing a <select> element int multiple mode
 1953: 
 1954: 
 1955: Args:
 1956:   $name - name of the <select> element
 1957:   $value - scalar or array ref of values that should already be selected
 1958:   $size - number of rows long the select element is
 1959:   $hash - the elements should be 'option' => 'shown text'
 1960:           (shown text should already have been &mt())
 1961:   $order - (optional) array ref of the order to show the elements in
 1962: 
 1963: =cut
 1964: 
 1965: #-------------------------------------------
 1966: sub multiple_select_form {
 1967:     my ($name,$value,$size,$hash,$order)=@_;
 1968:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1969:     my $output='';
 1970:     if (! defined($size)) {
 1971:         $size = 4;
 1972:         if (scalar(keys(%$hash))<4) {
 1973:             $size = scalar(keys(%$hash));
 1974:         }
 1975:     }
 1976:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1977:     my @order;
 1978:     if (ref($order) eq 'ARRAY')  {
 1979:         @order = @{$order};
 1980:     } else {
 1981:         @order = sort(keys(%$hash));
 1982:     }
 1983:     if (exists($$hash{'select_form_order'})) {
 1984:         @order = @{$$hash{'select_form_order'}};
 1985:     }
 1986:         
 1987:     foreach my $key (@order) {
 1988:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1989:         $output.='selected="selected" ' if ($selected{$key});
 1990:         $output.='>'.$hash->{$key}."</option>\n";
 1991:     }
 1992:     $output.="</select>\n";
 1993:     return $output;
 1994: }
 1995: 
 1996: #-------------------------------------------
 1997: 
 1998: =pod
 1999: 
 2000: =item * &select_form($defdom,$name,$hashref,$onchange)
 2001: 
 2002: Returns a string containing a <select name='$name' size='1'> form to 
 2003: allow a user to select options from a ref to a hash containing:
 2004: option_name => displayed text. An optional $onchange can include
 2005: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2006: 
 2007: See lonrights.pm for an example invocation and use.
 2008: 
 2009: =cut
 2010: 
 2011: #-------------------------------------------
 2012: sub select_form {
 2013:     my ($def,$name,$hashref,$onchange) = @_;
 2014:     return unless (ref($hashref) eq 'HASH');
 2015:     if ($onchange) {
 2016:         $onchange = ' onchange="'.$onchange.'"';
 2017:     }
 2018:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2019:     my @keys;
 2020:     if (exists($hashref->{'select_form_order'})) {
 2021: 	@keys=@{$hashref->{'select_form_order'}};
 2022:     } else {
 2023: 	@keys=sort(keys(%{$hashref}));
 2024:     }
 2025:     foreach my $key (@keys) {
 2026:         $selectform.=
 2027: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2028:             ($key eq $def ? 'selected="selected" ' : '').
 2029:                 ">".$hashref->{$key}."</option>\n";
 2030:     }
 2031:     $selectform.="</select>";
 2032:     return $selectform;
 2033: }
 2034: 
 2035: # For display filters
 2036: 
 2037: sub display_filter {
 2038:     my ($context) = @_;
 2039:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2040:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2041:     my $phraseinput = 'hidden';
 2042:     my $includeinput = 'hidden';
 2043:     my ($checked,$includetypestext);
 2044:     if ($env{'form.displayfilter'} eq 'containing') {
 2045:         $phraseinput = 'text'; 
 2046:         if ($context eq 'parmslog') {
 2047:             $includeinput = 'checkbox';
 2048:             if ($env{'form.includetypes'}) {
 2049:                 $checked = ' checked="checked"';
 2050:             }
 2051:             $includetypestext = &mt('Include parameter types');
 2052:         }
 2053:     } else {
 2054:         $includetypestext = '&nbsp;';
 2055:     }
 2056:     my ($additional,$secondid,$thirdid);
 2057:     if ($context eq 'parmslog') {
 2058:         $additional = 
 2059:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2060:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2061:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2062:             '</label>';
 2063:         $secondid = 'includetypes';
 2064:         $thirdid = 'includetypestext';
 2065:     }
 2066:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2067:                                                     '$secondid','$thirdid')";
 2068:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2069: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2070: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2071: 	   '</label></span> <span class="LC_nobreak">'.
 2072:            &mt('Filter: [_1]',
 2073: 	   &select_form($env{'form.displayfilter'},
 2074: 			'displayfilter',
 2075: 			{'currentfolder' => 'Current folder/page',
 2076: 			 'containing' => 'Containing phrase',
 2077: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2078: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2079:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2080:                          '" />'.$additional;
 2081: }
 2082: 
 2083: sub display_filter_js {
 2084:     my $includetext = &mt('Include parameter types');
 2085:     return <<"ENDJS";
 2086:   
 2087: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2088:     var firstType = 'hidden';
 2089:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2090:         firstType = 'text';
 2091:     }
 2092:     firstObject = document.getElementById(firstid);
 2093:     if (typeof(firstObject) == 'object') {
 2094:         if (firstObject.type != firstType) {
 2095:             changeInputType(firstObject,firstType);
 2096:         }
 2097:     }
 2098:     if (context == 'parmslog') {
 2099:         var secondType = 'hidden';
 2100:         if (firstType == 'text') {
 2101:             secondType = 'checkbox';
 2102:         }
 2103:         secondObject = document.getElementById(secondid);  
 2104:         if (typeof(secondObject) == 'object') {
 2105:             if (secondObject.type != secondType) {
 2106:                 changeInputType(secondObject,secondType);
 2107:             }
 2108:         }
 2109:         var textItem = document.getElementById(thirdid);
 2110:         var currtext = textItem.innerHTML;
 2111:         var newtext;
 2112:         if (firstType == 'text') {
 2113:             newtext = '$includetext';
 2114:         } else {
 2115:             newtext = '&nbsp;';
 2116:         }
 2117:         if (currtext != newtext) {
 2118:             textItem.innerHTML = newtext;
 2119:         }
 2120:     }
 2121:     return;
 2122: }
 2123: 
 2124: function changeInputType(oldObject,newType) {
 2125:     var newObject = document.createElement('input');
 2126:     newObject.type = newType;
 2127:     if (oldObject.size) {
 2128:         newObject.size = oldObject.size;
 2129:     }
 2130:     if (oldObject.value) {
 2131:         newObject.value = oldObject.value;
 2132:     }
 2133:     if (oldObject.name) {
 2134:         newObject.name = oldObject.name;
 2135:     }
 2136:     if (oldObject.id) {
 2137:         newObject.id = oldObject.id;
 2138:     }
 2139:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2140:     return;
 2141: }
 2142: 
 2143: ENDJS
 2144: }
 2145: 
 2146: sub gradeleveldescription {
 2147:     my $gradelevel=shift;
 2148:     my %gradelevels=(0 => 'Not specified',
 2149: 		     1 => 'Grade 1',
 2150: 		     2 => 'Grade 2',
 2151: 		     3 => 'Grade 3',
 2152: 		     4 => 'Grade 4',
 2153: 		     5 => 'Grade 5',
 2154: 		     6 => 'Grade 6',
 2155: 		     7 => 'Grade 7',
 2156: 		     8 => 'Grade 8',
 2157: 		     9 => 'Grade 9',
 2158: 		     10 => 'Grade 10',
 2159: 		     11 => 'Grade 11',
 2160: 		     12 => 'Grade 12',
 2161: 		     13 => 'Grade 13',
 2162: 		     14 => '100 Level',
 2163: 		     15 => '200 Level',
 2164: 		     16 => '300 Level',
 2165: 		     17 => '400 Level',
 2166: 		     18 => 'Graduate Level');
 2167:     return &mt($gradelevels{$gradelevel});
 2168: }
 2169: 
 2170: sub select_level_form {
 2171:     my ($deflevel,$name)=@_;
 2172:     unless ($deflevel) { $deflevel=0; }
 2173:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2174:     for (my $i=0; $i<=18; $i++) {
 2175:         $selectform.="<option value=\"$i\" ".
 2176:             ($i==$deflevel ? 'selected="selected" ' : '').
 2177:                 ">".&gradeleveldescription($i)."</option>\n";
 2178:     }
 2179:     $selectform.="</select>";
 2180:     return $selectform;
 2181: }
 2182: 
 2183: #-------------------------------------------
 2184: 
 2185: =pod
 2186: 
 2187: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2188: 
 2189: Returns a string containing a <select name='$name' size='1'> form to 
 2190: allow a user to select the domain to preform an operation in.  
 2191: See loncreateuser.pm for an example invocation and use.
 2192: 
 2193: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2194: selected");
 2195: 
 2196: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2197: 
 2198: 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.
 2199: 
 2200: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2201: 
 2202: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2203: 
 2204: =cut
 2205: 
 2206: #-------------------------------------------
 2207: sub select_dom_form {
 2208:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2209:     if ($onchange) {
 2210:         $onchange = ' onchange="'.$onchange.'"';
 2211:     }
 2212:     my (@domains,%exclude);
 2213:     if (ref($incdoms) eq 'ARRAY') {
 2214:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2215:     } else {
 2216:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2217:     }
 2218:     if ($includeempty) { @domains=('',@domains); }
 2219:     if (ref($excdoms) eq 'ARRAY') {
 2220:         map { $exclude{$_} = 1; } @{$excdoms};
 2221:     }
 2222:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2223:     foreach my $dom (@domains) {
 2224:         next if ($exclude{$dom});
 2225:         $selectdomain.="<option value=\"$dom\" ".
 2226:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2227:         if ($showdomdesc) {
 2228:             if ($dom ne '') {
 2229:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2230:                 if ($domdesc ne '') {
 2231:                     $selectdomain .= ' ('.$domdesc.')';
 2232:                 }
 2233:             } 
 2234:         }
 2235:         $selectdomain .= "</option>\n";
 2236:     }
 2237:     $selectdomain.="</select>";
 2238:     return $selectdomain;
 2239: }
 2240: 
 2241: #-------------------------------------------
 2242: 
 2243: =pod
 2244: 
 2245: =item * &home_server_form_item($domain,$name,$defaultflag)
 2246: 
 2247: input: 4 arguments (two required, two optional) - 
 2248:     $domain - domain of new user
 2249:     $name - name of form element
 2250:     $default - Value of 'default' causes a default item to be first 
 2251:                             option, and selected by default. 
 2252:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2253:                             if 1 server found, or default, if 0 found.
 2254: output: returns 2 items: 
 2255: (a) form element which contains either:
 2256:    (i) <select name="$name">
 2257:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2258:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2259:        </select>
 2260:        form item if there are multiple library servers in $domain, or
 2261:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2262:        if there is only one library server in $domain.
 2263: 
 2264: (b) number of library servers found.
 2265: 
 2266: See loncreateuser.pm for example of use.
 2267: 
 2268: =cut
 2269: 
 2270: #-------------------------------------------
 2271: sub home_server_form_item {
 2272:     my ($domain,$name,$default,$hide) = @_;
 2273:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2274:     my $result;
 2275:     my $numlib = keys(%servers);
 2276:     if ($numlib > 1) {
 2277:         $result .= '<select name="'.$name.'" />'."\n";
 2278:         if ($default) {
 2279:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2280:                        '</option>'."\n";
 2281:         }
 2282:         foreach my $hostid (sort(keys(%servers))) {
 2283:             $result.= '<option value="'.$hostid.'">'.
 2284: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2285:         }
 2286:         $result .= '</select>'."\n";
 2287:     } elsif ($numlib == 1) {
 2288:         my $hostid;
 2289:         foreach my $item (keys(%servers)) {
 2290:             $hostid = $item;
 2291:         }
 2292:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2293:                    $hostid.'" />';
 2294:                    if (!$hide) {
 2295:                        $result .= $hostid.' '.$servers{$hostid};
 2296:                    }
 2297:                    $result .= "\n";
 2298:     } elsif ($default) {
 2299:         $result .= '<input type="hidden" name="'.$name.
 2300:                    '" value="default" />';
 2301:                    if (!$hide) {
 2302:                        $result .= &mt('default');
 2303:                    }
 2304:                    $result .= "\n";
 2305:     }
 2306:     return ($result,$numlib);
 2307: }
 2308: 
 2309: =pod
 2310: 
 2311: =back 
 2312: 
 2313: =cut
 2314: 
 2315: ###############################################################
 2316: ##                  Decoding User Agent                      ##
 2317: ###############################################################
 2318: 
 2319: =pod
 2320: 
 2321: =head1 Decoding the User Agent
 2322: 
 2323: =over 4
 2324: 
 2325: =item * &decode_user_agent()
 2326: 
 2327: Inputs: $r
 2328: 
 2329: Outputs:
 2330: 
 2331: =over 4
 2332: 
 2333: =item * $httpbrowser
 2334: 
 2335: =item * $clientbrowser
 2336: 
 2337: =item * $clientversion
 2338: 
 2339: =item * $clientmathml
 2340: 
 2341: =item * $clientunicode
 2342: 
 2343: =item * $clientos
 2344: 
 2345: =item * $clientmobile
 2346: 
 2347: =item * $clientinfo
 2348: 
 2349: =item * $clientosversion
 2350: 
 2351: =back
 2352: 
 2353: =back 
 2354: 
 2355: =cut
 2356: 
 2357: ###############################################################
 2358: ###############################################################
 2359: sub decode_user_agent {
 2360:     my ($r)=@_;
 2361:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2362:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2363:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2364:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2365:     my $clientbrowser='unknown';
 2366:     my $clientversion='0';
 2367:     my $clientmathml='';
 2368:     my $clientunicode='0';
 2369:     my $clientmobile=0;
 2370:     my $clientosversion='';
 2371:     for (my $i=0;$i<=$#browsertype;$i++) {
 2372:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2373: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2374: 	    $clientbrowser=$bname;
 2375:             $httpbrowser=~/$vreg/i;
 2376: 	    $clientversion=$1;
 2377:             $clientmathml=($clientversion>=$minv);
 2378:             $clientunicode=($clientversion>=$univ);
 2379: 	}
 2380:     }
 2381:     my $clientos='unknown';
 2382:     my $clientinfo;
 2383:     if (($httpbrowser=~/linux/i) ||
 2384:         ($httpbrowser=~/unix/i) ||
 2385:         ($httpbrowser=~/ux/i) ||
 2386:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2387:     if (($httpbrowser=~/vax/i) ||
 2388:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2389:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2390:     if (($httpbrowser=~/mac/i) ||
 2391:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2392:     if ($httpbrowser=~/win/i) {
 2393:         $clientos='win';
 2394:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2395:             $clientosversion = $1;
 2396:         }
 2397:     }
 2398:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2399:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2400:         $clientmobile=lc($1);
 2401:     }
 2402:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2403:         $clientinfo = 'firefox-'.$1;
 2404:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2405:         $clientinfo = 'chromeframe-'.$1;
 2406:     }
 2407:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2408:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2409:             $clientosversion);
 2410: }
 2411: 
 2412: ###############################################################
 2413: ##    Authentication changing form generation subroutines    ##
 2414: ###############################################################
 2415: ##
 2416: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2417: ## hash, and have reasonable default values.
 2418: ##
 2419: ##    formname = the name given in the <form> tag.
 2420: #-------------------------------------------
 2421: 
 2422: =pod
 2423: 
 2424: =head1 Authentication Routines
 2425: 
 2426: =over 4
 2427: 
 2428: =item * &authform_xxxxxx()
 2429: 
 2430: The authform_xxxxxx subroutines provide javascript and html forms which 
 2431: handle some of the conveniences required for authentication forms.  
 2432: This is not an optimal method, but it works.  
 2433: 
 2434: =over 4
 2435: 
 2436: =item * authform_header
 2437: 
 2438: =item * authform_authorwarning
 2439: 
 2440: =item * authform_nochange
 2441: 
 2442: =item * authform_kerberos
 2443: 
 2444: =item * authform_internal
 2445: 
 2446: =item * authform_filesystem
 2447: 
 2448: =back
 2449: 
 2450: See loncreateuser.pm for invocation and use examples.
 2451: 
 2452: =cut
 2453: 
 2454: #-------------------------------------------
 2455: sub authform_header{  
 2456:     my %in = (
 2457:         formname => 'cu',
 2458:         kerb_def_dom => '',
 2459:         @_,
 2460:     );
 2461:     $in{'formname'} = 'document.' . $in{'formname'};
 2462:     my $result='';
 2463: 
 2464: #---------------------------------------------- Code for upper case translation
 2465:     my $Javascript_toUpperCase;
 2466:     unless ($in{kerb_def_dom}) {
 2467:         $Javascript_toUpperCase =<<"END";
 2468:         switch (choice) {
 2469:            case 'krb': currentform.elements[choicearg].value =
 2470:                currentform.elements[choicearg].value.toUpperCase();
 2471:                break;
 2472:            default:
 2473:         }
 2474: END
 2475:     } else {
 2476:         $Javascript_toUpperCase = "";
 2477:     }
 2478: 
 2479:     my $radioval = "'nochange'";
 2480:     if (defined($in{'curr_authtype'})) {
 2481:         if ($in{'curr_authtype'} ne '') {
 2482:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2483:         }
 2484:     }
 2485:     my $argfield = 'null';
 2486:     if (defined($in{'mode'})) {
 2487:         if ($in{'mode'} eq 'modifycourse')  {
 2488:             if (defined($in{'curr_autharg'})) {
 2489:                 if ($in{'curr_autharg'} ne '') {
 2490:                     $argfield = "'$in{'curr_autharg'}'";
 2491:                 }
 2492:             }
 2493:         }
 2494:     }
 2495: 
 2496:     $result.=<<"END";
 2497: var current = new Object();
 2498: current.radiovalue = $radioval;
 2499: current.argfield = $argfield;
 2500: 
 2501: function changed_radio(choice,currentform) {
 2502:     var choicearg = choice + 'arg';
 2503:     // If a radio button in changed, we need to change the argfield
 2504:     if (current.radiovalue != choice) {
 2505:         current.radiovalue = choice;
 2506:         if (current.argfield != null) {
 2507:             currentform.elements[current.argfield].value = '';
 2508:         }
 2509:         if (choice == 'nochange') {
 2510:             current.argfield = null;
 2511:         } else {
 2512:             current.argfield = choicearg;
 2513:             switch(choice) {
 2514:                 case 'krb': 
 2515:                     currentform.elements[current.argfield].value = 
 2516:                         "$in{'kerb_def_dom'}";
 2517:                 break;
 2518:               default:
 2519:                 break;
 2520:             }
 2521:         }
 2522:     }
 2523:     return;
 2524: }
 2525: 
 2526: function changed_text(choice,currentform) {
 2527:     var choicearg = choice + 'arg';
 2528:     if (currentform.elements[choicearg].value !='') {
 2529:         $Javascript_toUpperCase
 2530:         // clear old field
 2531:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2532:             currentform.elements[current.argfield].value = '';
 2533:         }
 2534:         current.argfield = choicearg;
 2535:     }
 2536:     set_auth_radio_buttons(choice,currentform);
 2537:     return;
 2538: }
 2539: 
 2540: function set_auth_radio_buttons(newvalue,currentform) {
 2541:     var numauthchoices = currentform.login.length;
 2542:     if (typeof numauthchoices  == "undefined") {
 2543:         return;
 2544:     } 
 2545:     var i=0;
 2546:     while (i < numauthchoices) {
 2547:         if (currentform.login[i].value == newvalue) { break; }
 2548:         i++;
 2549:     }
 2550:     if (i == numauthchoices) {
 2551:         return;
 2552:     }
 2553:     current.radiovalue = newvalue;
 2554:     currentform.login[i].checked = true;
 2555:     return;
 2556: }
 2557: END
 2558:     return $result;
 2559: }
 2560: 
 2561: sub authform_authorwarning {
 2562:     my $result='';
 2563:     $result='<i>'.
 2564:         &mt('As a general rule, only authors or co-authors should be '.
 2565:             'filesystem authenticated '.
 2566:             '(which allows access to the server filesystem).')."</i>\n";
 2567:     return $result;
 2568: }
 2569: 
 2570: sub authform_nochange {
 2571:     my %in = (
 2572:               formname => 'document.cu',
 2573:               kerb_def_dom => 'MSU.EDU',
 2574:               @_,
 2575:           );
 2576:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2577:     my $result;
 2578:     if (!$authnum) {
 2579:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2580:     } else {
 2581:         $result = '<label>'.&mt('[_1] Do not change login data',
 2582:                   '<input type="radio" name="login" value="nochange" '.
 2583:                   'checked="checked" onclick="'.
 2584:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2585: 	    '</label>';
 2586:     }
 2587:     return $result;
 2588: }
 2589: 
 2590: sub authform_kerberos {
 2591:     my %in = (
 2592:               formname => 'document.cu',
 2593:               kerb_def_dom => 'MSU.EDU',
 2594:               kerb_def_auth => 'krb4',
 2595:               @_,
 2596:               );
 2597:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2598:         $autharg,$jscall);
 2599:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2600:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2601:        $check5 = ' checked="checked"';
 2602:     } else {
 2603:        $check4 = ' checked="checked"';
 2604:     }
 2605:     $krbarg = $in{'kerb_def_dom'};
 2606:     if (defined($in{'curr_authtype'})) {
 2607:         if ($in{'curr_authtype'} eq 'krb') {
 2608:             $krbcheck = ' checked="checked"';
 2609:             if (defined($in{'mode'})) {
 2610:                 if ($in{'mode'} eq 'modifyuser') {
 2611:                     $krbcheck = '';
 2612:                 }
 2613:             }
 2614:             if (defined($in{'curr_kerb_ver'})) {
 2615:                 if ($in{'curr_krb_ver'} eq '5') {
 2616:                     $check5 = ' checked="checked"';
 2617:                     $check4 = '';
 2618:                 } else {
 2619:                     $check4 = ' checked="checked"';
 2620:                     $check5 = '';
 2621:                 }
 2622:             }
 2623:             if (defined($in{'curr_autharg'})) {
 2624:                 $krbarg = $in{'curr_autharg'};
 2625:             }
 2626:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2627:                 if (defined($in{'curr_autharg'})) {
 2628:                     $result = 
 2629:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2630:         $in{'curr_autharg'},$krbver);
 2631:                 } else {
 2632:                     $result =
 2633:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2634:                 }
 2635:                 return $result; 
 2636:             }
 2637:         }
 2638:     } else {
 2639:         if ($authnum == 1) {
 2640:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2641:         }
 2642:     }
 2643:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2644:         return;
 2645:     } elsif ($authtype eq '') {
 2646:         if (defined($in{'mode'})) {
 2647:             if ($in{'mode'} eq 'modifycourse') {
 2648:                 if ($authnum == 1) {
 2649:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2650:                 }
 2651:             }
 2652:         }
 2653:     }
 2654:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2655:     if ($authtype eq '') {
 2656:         $authtype = '<input type="radio" name="login" value="krb" '.
 2657:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2658:                     $krbcheck.' />';
 2659:     }
 2660:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2661:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2662:          $in{'curr_authtype'} eq 'krb5') ||
 2663:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2664:          $in{'curr_authtype'} eq 'krb4')) {
 2665:         $result .= &mt
 2666:         ('[_1] Kerberos authenticated with domain [_2] '.
 2667:          '[_3] Version 4 [_4] Version 5 [_5]',
 2668:          '<label>'.$authtype,
 2669:          '</label><input type="text" size="10" name="krbarg" '.
 2670:              'value="'.$krbarg.'" '.
 2671:              'onchange="'.$jscall.'" />',
 2672:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2673:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2674: 	 '</label>');
 2675:     } elsif ($can_assign{'krb4'}) {
 2676:         $result .= &mt
 2677:         ('[_1] Kerberos authenticated with domain [_2] '.
 2678:          '[_3] Version 4 [_4]',
 2679:          '<label>'.$authtype,
 2680:          '</label><input type="text" size="10" name="krbarg" '.
 2681:              'value="'.$krbarg.'" '.
 2682:              'onchange="'.$jscall.'" />',
 2683:          '<label><input type="hidden" name="krbver" value="4" />',
 2684:          '</label>');
 2685:     } elsif ($can_assign{'krb5'}) {
 2686:         $result .= &mt
 2687:         ('[_1] Kerberos authenticated with domain [_2] '.
 2688:          '[_3] Version 5 [_4]',
 2689:          '<label>'.$authtype,
 2690:          '</label><input type="text" size="10" name="krbarg" '.
 2691:              'value="'.$krbarg.'" '.
 2692:              'onchange="'.$jscall.'" />',
 2693:          '<label><input type="hidden" name="krbver" value="5" />',
 2694:          '</label>');
 2695:     }
 2696:     return $result;
 2697: }
 2698: 
 2699: sub authform_internal {
 2700:     my %in = (
 2701:                 formname => 'document.cu',
 2702:                 kerb_def_dom => 'MSU.EDU',
 2703:                 @_,
 2704:                 );
 2705:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2706:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2707:     if (defined($in{'curr_authtype'})) {
 2708:         if ($in{'curr_authtype'} eq 'int') {
 2709:             if ($can_assign{'int'}) {
 2710:                 $intcheck = 'checked="checked" ';
 2711:                 if (defined($in{'mode'})) {
 2712:                     if ($in{'mode'} eq 'modifyuser') {
 2713:                         $intcheck = '';
 2714:                     }
 2715:                 }
 2716:                 if (defined($in{'curr_autharg'})) {
 2717:                     $intarg = $in{'curr_autharg'};
 2718:                 }
 2719:             } else {
 2720:                 $result = &mt('Currently internally authenticated.');
 2721:                 return $result;
 2722:             }
 2723:         }
 2724:     } else {
 2725:         if ($authnum == 1) {
 2726:             $authtype = '<input type="hidden" name="login" value="int" />';
 2727:         }
 2728:     }
 2729:     if (!$can_assign{'int'}) {
 2730:         return;
 2731:     } elsif ($authtype eq '') {
 2732:         if (defined($in{'mode'})) {
 2733:             if ($in{'mode'} eq 'modifycourse') {
 2734:                 if ($authnum == 1) {
 2735:                     $authtype = '<input type="radio" name="login" value="int" />';
 2736:                 }
 2737:             }
 2738:         }
 2739:     }
 2740:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2741:     if ($authtype eq '') {
 2742:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2743:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2744:     }
 2745:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2746:                $intarg.'" onchange="'.$jscall.'" />';
 2747:     $result = &mt
 2748:         ('[_1] Internally authenticated (with initial password [_2])',
 2749:          '<label>'.$authtype,'</label>'.$autharg);
 2750:     $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>';
 2751:     return $result;
 2752: }
 2753: 
 2754: sub authform_local {
 2755:     my %in = (
 2756:               formname => 'document.cu',
 2757:               kerb_def_dom => 'MSU.EDU',
 2758:               @_,
 2759:               );
 2760:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2761:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2762:     if (defined($in{'curr_authtype'})) {
 2763:         if ($in{'curr_authtype'} eq 'loc') {
 2764:             if ($can_assign{'loc'}) {
 2765:                 $loccheck = 'checked="checked" ';
 2766:                 if (defined($in{'mode'})) {
 2767:                     if ($in{'mode'} eq 'modifyuser') {
 2768:                         $loccheck = '';
 2769:                     }
 2770:                 }
 2771:                 if (defined($in{'curr_autharg'})) {
 2772:                     $locarg = $in{'curr_autharg'};
 2773:                 }
 2774:             } else {
 2775:                 $result = &mt('Currently using local (institutional) authentication.');
 2776:                 return $result;
 2777:             }
 2778:         }
 2779:     } else {
 2780:         if ($authnum == 1) {
 2781:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2782:         }
 2783:     }
 2784:     if (!$can_assign{'loc'}) {
 2785:         return;
 2786:     } elsif ($authtype eq '') {
 2787:         if (defined($in{'mode'})) {
 2788:             if ($in{'mode'} eq 'modifycourse') {
 2789:                 if ($authnum == 1) {
 2790:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2791:                 }
 2792:             }
 2793:         }
 2794:     }
 2795:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2796:     if ($authtype eq '') {
 2797:         $authtype = '<input type="radio" name="login" value="loc" '.
 2798:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2799:                     $jscall.'" />';
 2800:     }
 2801:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2802:                $locarg.'" onchange="'.$jscall.'" />';
 2803:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2804:                   '<label>'.$authtype,'</label>'.$autharg);
 2805:     return $result;
 2806: }
 2807: 
 2808: sub authform_filesystem {
 2809:     my %in = (
 2810:               formname => 'document.cu',
 2811:               kerb_def_dom => 'MSU.EDU',
 2812:               @_,
 2813:               );
 2814:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2815:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2816:     if (defined($in{'curr_authtype'})) {
 2817:         if ($in{'curr_authtype'} eq 'fsys') {
 2818:             if ($can_assign{'fsys'}) {
 2819:                 $fsyscheck = 'checked="checked" ';
 2820:                 if (defined($in{'mode'})) {
 2821:                     if ($in{'mode'} eq 'modifyuser') {
 2822:                         $fsyscheck = '';
 2823:                     }
 2824:                 }
 2825:             } else {
 2826:                 $result = &mt('Currently Filesystem Authenticated.');
 2827:                 return $result;
 2828:             }           
 2829:         }
 2830:     } else {
 2831:         if ($authnum == 1) {
 2832:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2833:         }
 2834:     }
 2835:     if (!$can_assign{'fsys'}) {
 2836:         return;
 2837:     } elsif ($authtype eq '') {
 2838:         if (defined($in{'mode'})) {
 2839:             if ($in{'mode'} eq 'modifycourse') {
 2840:                 if ($authnum == 1) {
 2841:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2842:                 }
 2843:             }
 2844:         }
 2845:     }
 2846:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2847:     if ($authtype eq '') {
 2848:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2849:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2850:                     $jscall.'" />';
 2851:     }
 2852:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2853:                ' onchange="'.$jscall.'" />';
 2854:     $result = &mt
 2855:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2856:          '<label><input type="radio" name="login" value="fsys" '.
 2857:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2858:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2859:                   'onchange="'.$jscall.'" />');
 2860:     return $result;
 2861: }
 2862: 
 2863: sub get_assignable_auth {
 2864:     my ($dom) = @_;
 2865:     if ($dom eq '') {
 2866:         $dom = $env{'request.role.domain'};
 2867:     }
 2868:     my %can_assign = (
 2869:                           krb4 => 1,
 2870:                           krb5 => 1,
 2871:                           int  => 1,
 2872:                           loc  => 1,
 2873:                      );
 2874:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2875:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2876:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2877:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2878:             my $context;
 2879:             if ($env{'request.role'} =~ /^au/) {
 2880:                 $context = 'author';
 2881:             } elsif ($env{'request.role'} =~ /^dc/) {
 2882:                 $context = 'domain';
 2883:             } elsif ($env{'request.course.id'}) {
 2884:                 $context = 'course';
 2885:             }
 2886:             if ($context) {
 2887:                 if (ref($authhash->{$context}) eq 'HASH') {
 2888:                    %can_assign = %{$authhash->{$context}}; 
 2889:                 }
 2890:             }
 2891:         }
 2892:     }
 2893:     my $authnum = 0;
 2894:     foreach my $key (keys(%can_assign)) {
 2895:         if ($can_assign{$key}) {
 2896:             $authnum ++;
 2897:         }
 2898:     }
 2899:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2900:         $authnum --;
 2901:     }
 2902:     return ($authnum,%can_assign);
 2903: }
 2904: 
 2905: ###############################################################
 2906: ##    Get Kerberos Defaults for Domain                 ##
 2907: ###############################################################
 2908: ##
 2909: ## Returns default kerberos version and an associated argument
 2910: ## as listed in file domain.tab. If not listed, provides
 2911: ## appropriate default domain and kerberos version.
 2912: ##
 2913: #-------------------------------------------
 2914: 
 2915: =pod
 2916: 
 2917: =item * &get_kerberos_defaults()
 2918: 
 2919: get_kerberos_defaults($target_domain) returns the default kerberos
 2920: version and domain. If not found, it defaults to version 4 and the 
 2921: domain of the server.
 2922: 
 2923: =over 4
 2924: 
 2925: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2926: 
 2927: =back
 2928: 
 2929: =back
 2930: 
 2931: =cut
 2932: 
 2933: #-------------------------------------------
 2934: sub get_kerberos_defaults {
 2935:     my $domain=shift;
 2936:     my ($krbdef,$krbdefdom);
 2937:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2938:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2939:         $krbdef = $domdefaults{'auth_def'};
 2940:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2941:     } else {
 2942:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2943:         my $krbdefdom=$1;
 2944:         $krbdefdom=~tr/a-z/A-Z/;
 2945:         $krbdef = "krb4";
 2946:     }
 2947:     return ($krbdef,$krbdefdom);
 2948: }
 2949: 
 2950: 
 2951: ###############################################################
 2952: ##                Thesaurus Functions                        ##
 2953: ###############################################################
 2954: 
 2955: =pod
 2956: 
 2957: =head1 Thesaurus Functions
 2958: 
 2959: =over 4
 2960: 
 2961: =item * &initialize_keywords()
 2962: 
 2963: Initializes the package variable %Keywords if it is empty.  Uses the
 2964: package variable $thesaurus_db_file.
 2965: 
 2966: =cut
 2967: 
 2968: ###################################################
 2969: 
 2970: sub initialize_keywords {
 2971:     return 1 if (scalar keys(%Keywords));
 2972:     # If we are here, %Keywords is empty, so fill it up
 2973:     #   Make sure the file we need exists...
 2974:     if (! -e $thesaurus_db_file) {
 2975:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2976:                                  " failed because it does not exist");
 2977:         return 0;
 2978:     }
 2979:     #   Set up the hash as a database
 2980:     my %thesaurus_db;
 2981:     if (! tie(%thesaurus_db,'GDBM_File',
 2982:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2983:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2984:                                  $thesaurus_db_file);
 2985:         return 0;
 2986:     } 
 2987:     #  Get the average number of appearances of a word.
 2988:     my $avecount = $thesaurus_db{'average.count'};
 2989:     #  Put keywords (those that appear > average) into %Keywords
 2990:     while (my ($word,$data)=each (%thesaurus_db)) {
 2991:         my ($count,undef) = split /:/,$data;
 2992:         $Keywords{$word}++ if ($count > $avecount);
 2993:     }
 2994:     untie %thesaurus_db;
 2995:     # Remove special values from %Keywords.
 2996:     foreach my $value ('total.count','average.count') {
 2997:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2998:   }
 2999:     return 1;
 3000: }
 3001: 
 3002: ###################################################
 3003: 
 3004: =pod
 3005: 
 3006: =item * &keyword($word)
 3007: 
 3008: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3009: than the average number of times in the thesaurus database.  Calls 
 3010: &initialize_keywords
 3011: 
 3012: =cut
 3013: 
 3014: ###################################################
 3015: 
 3016: sub keyword {
 3017:     return if (!&initialize_keywords());
 3018:     my $word=lc(shift());
 3019:     $word=~s/\W//g;
 3020:     return exists($Keywords{$word});
 3021: }
 3022: 
 3023: ###############################################################
 3024: 
 3025: =pod 
 3026: 
 3027: =item * &get_related_words()
 3028: 
 3029: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3030: an array of words.  If the keyword is not in the thesaurus, an empty array
 3031: will be returned.  The order of the words returned is determined by the
 3032: database which holds them.
 3033: 
 3034: Uses global $thesaurus_db_file.
 3035: 
 3036: 
 3037: =cut
 3038: 
 3039: ###############################################################
 3040: sub get_related_words {
 3041:     my $keyword = shift;
 3042:     my %thesaurus_db;
 3043:     if (! -e $thesaurus_db_file) {
 3044:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3045:                                  "failed because the file does not exist");
 3046:         return ();
 3047:     }
 3048:     if (! tie(%thesaurus_db,'GDBM_File',
 3049:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3050:         return ();
 3051:     } 
 3052:     my @Words=();
 3053:     my $count=0;
 3054:     if (exists($thesaurus_db{$keyword})) {
 3055: 	# The first element is the number of times
 3056: 	# the word appears.  We do not need it now.
 3057: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3058: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3059: 	my $threshold=$mostfrequentcount/10;
 3060:         foreach my $possibleword (@RelatedWords) {
 3061:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3062:             if ($wordcount>$threshold) {
 3063: 		push(@Words,$word);
 3064:                 $count++;
 3065:                 if ($count>10) { last; }
 3066: 	    }
 3067:         }
 3068:     }
 3069:     untie %thesaurus_db;
 3070:     return @Words;
 3071: }
 3072: 
 3073: =pod
 3074: 
 3075: =back
 3076: 
 3077: =cut
 3078: 
 3079: # -------------------------------------------------------------- Plaintext name
 3080: =pod
 3081: 
 3082: =head1 User Name Functions
 3083: 
 3084: =over 4
 3085: 
 3086: =item * &plainname($uname,$udom,$first)
 3087: 
 3088: Takes a users logon name and returns it as a string in
 3089: "first middle last generation" form 
 3090: if $first is set to 'lastname' then it returns it as
 3091: 'lastname generation, firstname middlename' if their is a lastname
 3092: 
 3093: =cut
 3094: 
 3095: 
 3096: ###############################################################
 3097: sub plainname {
 3098:     my ($uname,$udom,$first)=@_;
 3099:     return if (!defined($uname) || !defined($udom));
 3100:     my %names=&getnames($uname,$udom);
 3101:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3102: 					  $names{'middlename'},
 3103: 					  $names{'lastname'},
 3104: 					  $names{'generation'},$first);
 3105:     $name=~s/^\s+//;
 3106:     $name=~s/\s+$//;
 3107:     $name=~s/\s+/ /g;
 3108:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3109:     return $name;
 3110: }
 3111: 
 3112: # -------------------------------------------------------------------- Nickname
 3113: =pod
 3114: 
 3115: =item * &nickname($uname,$udom)
 3116: 
 3117: Gets a users name and returns it as a string as
 3118: 
 3119: "&quot;nickname&quot;"
 3120: 
 3121: if the user has a nickname or
 3122: 
 3123: "first middle last generation"
 3124: 
 3125: if the user does not
 3126: 
 3127: =cut
 3128: 
 3129: sub nickname {
 3130:     my ($uname,$udom)=@_;
 3131:     return if (!defined($uname) || !defined($udom));
 3132:     my %names=&getnames($uname,$udom);
 3133:     my $name=$names{'nickname'};
 3134:     if ($name) {
 3135:        $name='&quot;'.$name.'&quot;'; 
 3136:     } else {
 3137:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3138: 	     $names{'lastname'}.' '.$names{'generation'};
 3139:        $name=~s/\s+$//;
 3140:        $name=~s/\s+/ /g;
 3141:     }
 3142:     return $name;
 3143: }
 3144: 
 3145: sub getnames {
 3146:     my ($uname,$udom)=@_;
 3147:     return if (!defined($uname) || !defined($udom));
 3148:     if ($udom eq 'public' && $uname eq 'public') {
 3149: 	return ('lastname' => &mt('Public'));
 3150:     }
 3151:     my $id=$uname.':'.$udom;
 3152:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3153:     if ($cached) {
 3154: 	return %{$names};
 3155:     } else {
 3156: 	my %loadnames=&Apache::lonnet::get('environment',
 3157:                     ['firstname','middlename','lastname','generation','nickname'],
 3158: 					 $udom,$uname);
 3159: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3160: 	return %loadnames;
 3161:     }
 3162: }
 3163: 
 3164: # -------------------------------------------------------------------- getemails
 3165: 
 3166: =pod
 3167: 
 3168: =item * &getemails($uname,$udom)
 3169: 
 3170: Gets a user's email information and returns it as a hash with keys:
 3171: notification, critnotification, permanentemail
 3172: 
 3173: For notification and critnotification, values are comma-separated lists 
 3174: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3175:  
 3176: 
 3177: =cut
 3178: 
 3179: 
 3180: sub getemails {
 3181:     my ($uname,$udom)=@_;
 3182:     if ($udom eq 'public' && $uname eq 'public') {
 3183: 	return;
 3184:     }
 3185:     if (!$udom) { $udom=$env{'user.domain'}; }
 3186:     if (!$uname) { $uname=$env{'user.name'}; }
 3187:     my $id=$uname.':'.$udom;
 3188:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3189:     if ($cached) {
 3190: 	return %{$names};
 3191:     } else {
 3192: 	my %loadnames=&Apache::lonnet::get('environment',
 3193:                     			   ['notification','critnotification',
 3194: 					    'permanentemail'],
 3195: 					   $udom,$uname);
 3196: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3197: 	return %loadnames;
 3198:     }
 3199: }
 3200: 
 3201: sub flush_email_cache {
 3202:     my ($uname,$udom)=@_;
 3203:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3204:     if (!$uname) { $uname=$env{'user.name'};   }
 3205:     return if ($udom eq 'public' && $uname eq 'public');
 3206:     my $id=$uname.':'.$udom;
 3207:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3208: }
 3209: 
 3210: # -------------------------------------------------------------------- getlangs
 3211: 
 3212: =pod
 3213: 
 3214: =item * &getlangs($uname,$udom)
 3215: 
 3216: Gets a user's language preference and returns it as a hash with key:
 3217: language.
 3218: 
 3219: =cut
 3220: 
 3221: 
 3222: sub getlangs {
 3223:     my ($uname,$udom) = @_;
 3224:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3225:     if (!$uname) { $uname=$env{'user.name'};   }
 3226:     my $id=$uname.':'.$udom;
 3227:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3228:     if ($cached) {
 3229:         return %{$langs};
 3230:     } else {
 3231:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3232:                                            $udom,$uname);
 3233:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3234:         return %loadlangs;
 3235:     }
 3236: }
 3237: 
 3238: sub flush_langs_cache {
 3239:     my ($uname,$udom)=@_;
 3240:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3241:     if (!$uname) { $uname=$env{'user.name'};   }
 3242:     return if ($udom eq 'public' && $uname eq 'public');
 3243:     my $id=$uname.':'.$udom;
 3244:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3245: }
 3246: 
 3247: # ------------------------------------------------------------------ Screenname
 3248: 
 3249: =pod
 3250: 
 3251: =item * &screenname($uname,$udom)
 3252: 
 3253: Gets a users screenname and returns it as a string
 3254: 
 3255: =cut
 3256: 
 3257: sub screenname {
 3258:     my ($uname,$udom)=@_;
 3259:     if ($uname eq $env{'user.name'} &&
 3260: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3261:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3262:     return $names{'screenname'};
 3263: }
 3264: 
 3265: 
 3266: # ------------------------------------------------------------- Confirm Wrapper
 3267: =pod
 3268: 
 3269: =item * &confirmwrapper($message)
 3270: 
 3271: Wrap messages about completion of operation in box
 3272: 
 3273: =cut
 3274: 
 3275: sub confirmwrapper {
 3276:     my ($message)=@_;
 3277:     if ($message) {
 3278:         return "\n".'<div class="LC_confirm_box">'."\n"
 3279:                .$message."\n"
 3280:                .'</div>'."\n";
 3281:     } else {
 3282:         return $message;
 3283:     }
 3284: }
 3285: 
 3286: # ------------------------------------------------------------- Message Wrapper
 3287: 
 3288: sub messagewrapper {
 3289:     my ($link,$username,$domain,$subject,$text)=@_;
 3290:     return 
 3291:         '<a href="/adm/email?compose=individual&amp;'.
 3292:         'recname='.$username.'&amp;recdom='.$domain.
 3293: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3294:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3295: }
 3296: 
 3297: # --------------------------------------------------------------- Notes Wrapper
 3298: 
 3299: sub noteswrapper {
 3300:     my ($link,$un,$do)=@_;
 3301:     return 
 3302: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3303: }
 3304: 
 3305: # ------------------------------------------------------------- Aboutme Wrapper
 3306: 
 3307: sub aboutmewrapper {
 3308:     my ($link,$username,$domain,$target,$class)=@_;
 3309:     if (!defined($username)  && !defined($domain)) {
 3310:         return;
 3311:     }
 3312:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3313: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3314: }
 3315: 
 3316: # ------------------------------------------------------------ Syllabus Wrapper
 3317: 
 3318: sub syllabuswrapper {
 3319:     my ($linktext,$coursedir,$domain)=@_;
 3320:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3321: }
 3322: 
 3323: # -----------------------------------------------------------------------------
 3324: 
 3325: sub track_student_link {
 3326:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3327:     my $link ="/adm/trackstudent?";
 3328:     my $title = 'View recent activity';
 3329:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3330:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3331:         $link .= "selected_student=$sname:$sdom";
 3332:         $title .= ' of this student';
 3333:     } 
 3334:     if (defined($target) && $target !~ /^\s*$/) {
 3335:         $target = qq{target="$target"};
 3336:     } else {
 3337:         $target = '';
 3338:     }
 3339:     if ($start) { $link.='&amp;start='.$start; }
 3340:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3341:     $title = &mt($title);
 3342:     $linktext = &mt($linktext);
 3343:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3344: 	&help_open_topic('View_recent_activity');
 3345: }
 3346: 
 3347: sub slot_reservations_link {
 3348:     my ($linktext,$sname,$sdom,$target) = @_;
 3349:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3350:     my $title = 'View slot reservation history';
 3351:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3352:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3353:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3354:         $title .= ' of this student';
 3355:     }
 3356:     if (defined($target) && $target !~ /^\s*$/) {
 3357:         $target = qq{target="$target"};
 3358:     } else {
 3359:         $target = '';
 3360:     }
 3361:     $title = &mt($title);
 3362:     $linktext = &mt($linktext);
 3363:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3364: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3365: 
 3366: }
 3367: 
 3368: # ===================================================== Display a student photo
 3369: 
 3370: 
 3371: sub student_image_tag {
 3372:     my ($domain,$user)=@_;
 3373:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3374:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3375: 	return '<img src="'.$imgsrc.'" align="right" />';
 3376:     } else {
 3377: 	return '';
 3378:     }
 3379: }
 3380: 
 3381: =pod
 3382: 
 3383: =back
 3384: 
 3385: =head1 Access .tab File Data
 3386: 
 3387: =over 4
 3388: 
 3389: =item * &languageids() 
 3390: 
 3391: returns list of all language ids
 3392: 
 3393: =cut
 3394: 
 3395: sub languageids {
 3396:     return sort(keys(%language));
 3397: }
 3398: 
 3399: =pod
 3400: 
 3401: =item * &languagedescription() 
 3402: 
 3403: returns description of a specified language id
 3404: 
 3405: =cut
 3406: 
 3407: sub languagedescription {
 3408:     my $code=shift;
 3409:     return  ($supported_language{$code}?'* ':'').
 3410:             $language{$code}.
 3411: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3412: }
 3413: 
 3414: =pod
 3415: 
 3416: =item * &plainlanguagedescription
 3417: 
 3418: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3419: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3420: 
 3421: =cut
 3422: 
 3423: sub plainlanguagedescription {
 3424:     my $code=shift;
 3425:     return $language{$code};
 3426: }
 3427: 
 3428: =pod
 3429: 
 3430: =item * &supportedlanguagecode
 3431: 
 3432: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3433: code.
 3434: 
 3435: =cut
 3436: 
 3437: sub supportedlanguagecode {
 3438:     my $code=shift;
 3439:     return $supported_language{$code};
 3440: }
 3441: 
 3442: =pod
 3443: 
 3444: =item * &latexlanguage()
 3445: 
 3446: Given a language key code returns the correspondnig language to use
 3447: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3448: is no supported hyphenation for the language code.
 3449: 
 3450: =cut
 3451: 
 3452: sub latexlanguage {
 3453:     my $code = shift;
 3454:     return $latex_language{$code};
 3455: }
 3456: 
 3457: =pod
 3458: 
 3459: =item * &latexhyphenation()
 3460: 
 3461: Same as above but what's supplied is the language as it might be stored
 3462: in the metadata.
 3463: 
 3464: =cut
 3465: 
 3466: sub latexhyphenation {
 3467:     my $key = shift;
 3468:     return $latex_language_bykey{$key};
 3469: }
 3470: 
 3471: =pod
 3472: 
 3473: =item * &copyrightids() 
 3474: 
 3475: returns list of all copyrights
 3476: 
 3477: =cut
 3478: 
 3479: sub copyrightids {
 3480:     return sort(keys(%cprtag));
 3481: }
 3482: 
 3483: =pod
 3484: 
 3485: =item * &copyrightdescription() 
 3486: 
 3487: returns description of a specified copyright id
 3488: 
 3489: =cut
 3490: 
 3491: sub copyrightdescription {
 3492:     return &mt($cprtag{shift(@_)});
 3493: }
 3494: 
 3495: =pod
 3496: 
 3497: =item * &source_copyrightids() 
 3498: 
 3499: returns list of all source copyrights
 3500: 
 3501: =cut
 3502: 
 3503: sub source_copyrightids {
 3504:     return sort(keys(%scprtag));
 3505: }
 3506: 
 3507: =pod
 3508: 
 3509: =item * &source_copyrightdescription() 
 3510: 
 3511: returns description of a specified source copyright id
 3512: 
 3513: =cut
 3514: 
 3515: sub source_copyrightdescription {
 3516:     return &mt($scprtag{shift(@_)});
 3517: }
 3518: 
 3519: =pod
 3520: 
 3521: =item * &filecategories() 
 3522: 
 3523: returns list of all file categories
 3524: 
 3525: =cut
 3526: 
 3527: sub filecategories {
 3528:     return sort(keys(%category_extensions));
 3529: }
 3530: 
 3531: =pod
 3532: 
 3533: =item * &filecategorytypes() 
 3534: 
 3535: returns list of file types belonging to a given file
 3536: category
 3537: 
 3538: =cut
 3539: 
 3540: sub filecategorytypes {
 3541:     my ($cat) = @_;
 3542:     return @{$category_extensions{lc($cat)}};
 3543: }
 3544: 
 3545: =pod
 3546: 
 3547: =item * &fileembstyle() 
 3548: 
 3549: returns embedding style for a specified file type
 3550: 
 3551: =cut
 3552: 
 3553: sub fileembstyle {
 3554:     return $fe{lc(shift(@_))};
 3555: }
 3556: 
 3557: sub filemimetype {
 3558:     return $fm{lc(shift(@_))};
 3559: }
 3560: 
 3561: 
 3562: sub filecategoryselect {
 3563:     my ($name,$value)=@_;
 3564:     return &select_form($value,$name,
 3565:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3566: }
 3567: 
 3568: =pod
 3569: 
 3570: =item * &filedescription() 
 3571: 
 3572: returns description for a specified file type
 3573: 
 3574: =cut
 3575: 
 3576: sub filedescription {
 3577:     my $file_description = $fd{lc(shift())};
 3578:     $file_description =~ s:([\[\]]):~$1:g;
 3579:     return &mt($file_description);
 3580: }
 3581: 
 3582: =pod
 3583: 
 3584: =item * &filedescriptionex() 
 3585: 
 3586: returns description for a specified file type with
 3587: extra formatting
 3588: 
 3589: =cut
 3590: 
 3591: sub filedescriptionex {
 3592:     my $ex=shift;
 3593:     my $file_description = $fd{lc($ex)};
 3594:     $file_description =~ s:([\[\]]):~$1:g;
 3595:     return '.'.$ex.' '.&mt($file_description);
 3596: }
 3597: 
 3598: # End of .tab access
 3599: =pod
 3600: 
 3601: =back
 3602: 
 3603: =cut
 3604: 
 3605: # ------------------------------------------------------------------ File Types
 3606: sub fileextensions {
 3607:     return sort(keys(%fe));
 3608: }
 3609: 
 3610: # ----------------------------------------------------------- Display Languages
 3611: # returns a hash with all desired display languages
 3612: #
 3613: 
 3614: sub display_languages {
 3615:     my %languages=();
 3616:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3617: 	$languages{$lang}=1;
 3618:     }
 3619:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3620:     if ($env{'form.displaylanguage'}) {
 3621: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3622: 	    $languages{$lang}=1;
 3623:         }
 3624:     }
 3625:     return %languages;
 3626: }
 3627: 
 3628: sub languages {
 3629:     my ($possible_langs) = @_;
 3630:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3631:     if (!ref($possible_langs)) {
 3632: 	if( wantarray ) {
 3633: 	    return @preferred_langs;
 3634: 	} else {
 3635: 	    return $preferred_langs[0];
 3636: 	}
 3637:     }
 3638:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3639:     my @preferred_possibilities;
 3640:     foreach my $preferred_lang (@preferred_langs) {
 3641: 	if (exists($possibilities{$preferred_lang})) {
 3642: 	    push(@preferred_possibilities, $preferred_lang);
 3643: 	}
 3644:     }
 3645:     if( wantarray ) {
 3646: 	return @preferred_possibilities;
 3647:     }
 3648:     return $preferred_possibilities[0];
 3649: }
 3650: 
 3651: sub user_lang {
 3652:     my ($touname,$toudom,$fromcid) = @_;
 3653:     my @userlangs;
 3654:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3655:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3656:                     $env{'course.'.$fromcid.'.languages'}));
 3657:     } else {
 3658:         my %langhash = &getlangs($touname,$toudom);
 3659:         if ($langhash{'languages'} ne '') {
 3660:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3661:         } else {
 3662:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3663:             if ($domdefs{'lang_def'} ne '') {
 3664:                 @userlangs = ($domdefs{'lang_def'});
 3665:             }
 3666:         }
 3667:     }
 3668:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3669:     my $user_lh = Apache::localize->get_handle(@languages);
 3670:     return $user_lh;
 3671: }
 3672: 
 3673: 
 3674: ###############################################################
 3675: ##               Student Answer Attempts                     ##
 3676: ###############################################################
 3677: 
 3678: =pod
 3679: 
 3680: =head1 Alternate Problem Views
 3681: 
 3682: =over 4
 3683: 
 3684: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3685:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 3686: 
 3687: Return string with previous attempt on problem. Arguments:
 3688: 
 3689: =over 4
 3690: 
 3691: =item * $symb: Problem, including path
 3692: 
 3693: =item * $username: username of the desired student
 3694: 
 3695: =item * $domain: domain of the desired student
 3696: 
 3697: =item * $course: Course ID
 3698: 
 3699: =item * $getattempt: Leave blank for all attempts, otherwise put
 3700:     something
 3701: 
 3702: =item * $regexp: if string matches this regexp, the string will be
 3703:     sent to $gradesub
 3704: 
 3705: =item * $gradesub: routine that processes the string if it matches $regexp
 3706: 
 3707: =item * $usec: section of the desired student
 3708: 
 3709: =item * $identifier: counter for student (multiple students one problem) or
 3710:     problem (one student; whole sequence).
 3711: 
 3712: =back
 3713: 
 3714: The output string is a table containing all desired attempts, if any.
 3715: 
 3716: =cut
 3717: 
 3718: sub get_previous_attempt {
 3719:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 3720:   my $prevattempts='';
 3721:   no strict 'refs';
 3722:   if ($symb) {
 3723:     my (%returnhash)=
 3724:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3725:     if ($returnhash{'version'}) {
 3726:       my %lasthash=();
 3727:       my $version;
 3728:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3729:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 3730:             if ($key =~ /\.rawrndseed$/) {
 3731:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 3732:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 3733:             } else {
 3734:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 3735:             }
 3736:         }
 3737:       }
 3738:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3739:       $prevattempts.='<th>'.&mt('History').'</th>';
 3740:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 3741:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3742:       foreach my $key (sort(keys(%lasthash))) {
 3743: 	my ($ign,@parts) = split(/\./,$key);
 3744: 	if ($#parts > 0) {
 3745: 	  my $data=$parts[-1];
 3746:           next if ($data eq 'foilorder');
 3747: 	  pop(@parts);
 3748:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3749:           if ($data eq 'type') {
 3750:               unless ($showsurv) {
 3751:                   my $id = join(',',@parts);
 3752:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3753:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3754:                       $lasthidden{$ign.'.'.$id} = 1;
 3755:                   }
 3756:               }
 3757:               if ($identifier ne '') {
 3758:                   my $id = join(',',@parts);
 3759:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 3760:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 3761:                       $hidestatus{$ign.'.'.$id} = 1;
 3762:                   }
 3763:               }
 3764:           } elsif ($data eq 'regrader') {
 3765:               if (($identifier ne '') && (@parts)) {
 3766:                   my $id = join(',',@parts);
 3767:                   $regraded{$ign.'.'.$id} = 1;
 3768:               }
 3769:           } 
 3770: 	} else {
 3771: 	  if ($#parts == 0) {
 3772: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3773: 	  } else {
 3774: 	    $prevattempts.='<th>'.$ign.'</th>';
 3775: 	  }
 3776: 	}
 3777:       }
 3778:       $prevattempts.=&end_data_table_header_row();
 3779:       if ($getattempt eq '') {
 3780:         my (%solved,%resets,%probstatus);
 3781:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 3782:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 3783:                 foreach my $id (keys(%regraded)) {
 3784:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 3785:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 3786:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 3787:                         push(@{$resets{$id}},$version);
 3788:                     }
 3789:                 }
 3790:             }
 3791:         }
 3792: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3793:             my (@hidden,@unsolved);
 3794:             if (%typeparts) {
 3795:                 foreach my $id (keys(%typeparts)) {
 3796:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 3797:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3798:                         push(@hidden,$id);
 3799:                     } elsif ($identifier ne '') {
 3800:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 3801:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 3802:                                 ($hidestatus{$id})) {
 3803:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 3804:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 3805:                                 push(@{$solved{$id}},$version);
 3806:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 3807:                                      (ref($solved{$id}) eq 'ARRAY')) {
 3808:                                 my $skip;
 3809:                                 if (ref($resets{$id}) eq 'ARRAY') {
 3810:                                     foreach my $reset (@{$resets{$id}}) {
 3811:                                         if ($reset > $solved{$id}[-1]) {
 3812:                                             $skip=1;
 3813:                                             last;
 3814:                                         }
 3815:                                     }
 3816:                                 }
 3817:                                 unless ($skip) {
 3818:                                     my ($ign,$partslist) = split(/\./,$id,2);
 3819:                                     push(@unsolved,$partslist);
 3820:                                 }
 3821:                             }
 3822:                         }
 3823:                     }
 3824:                 }
 3825:             }
 3826:             $prevattempts.=&start_data_table_row().
 3827:                            '<td>'.&mt('Transaction [_1]',$version);
 3828:             if (@unsolved) {
 3829:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 3830:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 3831:                                  &mt('Hide').'</label></span>';
 3832:             }
 3833:             $prevattempts .= '</td>';
 3834:             if (@hidden) {
 3835:                 foreach my $key (sort(keys(%lasthash))) {
 3836:                     next if ($key =~ /\.foilorder$/);
 3837:                     my $hide;
 3838:                     foreach my $id (@hidden) {
 3839:                         if ($key =~ /^\Q$id\E/) {
 3840:                             $hide = 1;
 3841:                             last;
 3842:                         }
 3843:                     }
 3844:                     if ($hide) {
 3845:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3846:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3847:                             my $value = &format_previous_attempt_value($key,
 3848:                                              $returnhash{$version.':'.$key});
 3849:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3850:                         } else {
 3851:                             $prevattempts.='<td>&nbsp;</td>';
 3852:                         }
 3853:                     } else {
 3854:                         if ($key =~ /\./) {
 3855:                             my $value = $returnhash{$version.':'.$key};
 3856:                             if ($key =~ /\.rndseed$/) {
 3857:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 3858:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 3859:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 3860:                                 }
 3861:                             }
 3862:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 3863:                                            '&nbsp;</td>';
 3864:                         } else {
 3865:                             $prevattempts.='<td>&nbsp;</td>';
 3866:                         }
 3867:                     }
 3868:                 }
 3869:             } else {
 3870: 	        foreach my $key (sort(keys(%lasthash))) {
 3871:                     next if ($key =~ /\.foilorder$/);
 3872:                     my $value = $returnhash{$version.':'.$key};
 3873:                     if ($key =~ /\.rndseed$/) {
 3874:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 3875:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 3876:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 3877:                         }
 3878:                     }
 3879:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 3880:                                    '&nbsp;</td>';
 3881: 	        }
 3882:             }
 3883: 	    $prevattempts.=&end_data_table_row();
 3884: 	 }
 3885:       }
 3886:       my @currhidden = keys(%lasthidden);
 3887:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3888:       foreach my $key (sort(keys(%lasthash))) {
 3889:           next if ($key =~ /\.foilorder$/);
 3890:           if (%typeparts) {
 3891:               my $hidden;
 3892:               foreach my $id (@currhidden) {
 3893:                   if ($key =~ /^\Q$id\E/) {
 3894:                       $hidden = 1;
 3895:                       last;
 3896:                   }
 3897:               }
 3898:               if ($hidden) {
 3899:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3900:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3901:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3902:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3903:                           $value = &$gradesub($value);
 3904:                       }
 3905:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3906:                   } else {
 3907:                       $prevattempts.='<td>&nbsp;</td>';
 3908:                   }
 3909:               } else {
 3910:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3911:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3912:                       $value = &$gradesub($value);
 3913:                   }
 3914:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3915:               }
 3916:           } else {
 3917: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3918: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3919:                   $value = &$gradesub($value);
 3920:               }
 3921: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3922:           }
 3923:       }
 3924:       $prevattempts.= &end_data_table_row().&end_data_table();
 3925:     } else {
 3926:       $prevattempts=
 3927: 	  &start_data_table().&start_data_table_row().
 3928: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3929: 	  &end_data_table_row().&end_data_table();
 3930:     }
 3931:   } else {
 3932:     $prevattempts=
 3933: 	  &start_data_table().&start_data_table_row().
 3934: 	  '<td>'.&mt('No data.').'</td>'.
 3935: 	  &end_data_table_row().&end_data_table();
 3936:   }
 3937: }
 3938: 
 3939: sub format_previous_attempt_value {
 3940:     my ($key,$value) = @_;
 3941:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3942: 	$value = &Apache::lonlocal::locallocaltime($value);
 3943:     } elsif (ref($value) eq 'ARRAY') {
 3944: 	$value = '('.join(', ', @{ $value }).')';
 3945:     } elsif ($key =~ /answerstring$/) {
 3946:         my %answers = &Apache::lonnet::str2hash($value);
 3947:         my @anskeys = sort(keys(%answers));
 3948:         if (@anskeys == 1) {
 3949:             my $answer = $answers{$anskeys[0]};
 3950:             if ($answer =~ m{\0}) {
 3951:                 $answer =~ s{\0}{,}g;
 3952:             }
 3953:             my $tag_internal_answer_name = 'INTERNAL';
 3954:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3955:                 $value = $answer; 
 3956:             } else {
 3957:                 $value = $anskeys[0].'='.$answer;
 3958:             }
 3959:         } else {
 3960:             foreach my $ans (@anskeys) {
 3961:                 my $answer = $answers{$ans};
 3962:                 if ($answer =~ m{\0}) {
 3963:                     $answer =~ s{\0}{,}g;
 3964:                 }
 3965:                 $value .=  $ans.'='.$answer.'<br />';;
 3966:             } 
 3967:         }
 3968:     } else {
 3969: 	$value = &unescape($value);
 3970:     }
 3971:     return $value;
 3972: }
 3973: 
 3974: 
 3975: sub relative_to_absolute {
 3976:     my ($url,$output)=@_;
 3977:     my $parser=HTML::TokeParser->new(\$output);
 3978:     my $token;
 3979:     my $thisdir=$url;
 3980:     my @rlinks=();
 3981:     while ($token=$parser->get_token) {
 3982: 	if ($token->[0] eq 'S') {
 3983: 	    if ($token->[1] eq 'a') {
 3984: 		if ($token->[2]->{'href'}) {
 3985: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3986: 		}
 3987: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3988: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3989: 	    } elsif ($token->[1] eq 'base') {
 3990: 		$thisdir=$token->[2]->{'href'};
 3991: 	    }
 3992: 	}
 3993:     }
 3994:     $thisdir=~s-/[^/]*$--;
 3995:     foreach my $link (@rlinks) {
 3996: 	unless (($link=~/^https?\:\/\//i) ||
 3997: 		($link=~/^\//) ||
 3998: 		($link=~/^javascript:/i) ||
 3999: 		($link=~/^mailto:/i) ||
 4000: 		($link=~/^\#/)) {
 4001: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4002: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4003: 	}
 4004:     }
 4005: # -------------------------------------------------- Deal with Applet codebases
 4006:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4007:     return $output;
 4008: }
 4009: 
 4010: =pod
 4011: 
 4012: =item * &get_student_view()
 4013: 
 4014: show a snapshot of what student was looking at
 4015: 
 4016: =cut
 4017: 
 4018: sub get_student_view {
 4019:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4020:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4021:   my (%form);
 4022:   my @elements=('symb','courseid','domain','username');
 4023:   foreach my $element (@elements) {
 4024:       $form{'grade_'.$element}=eval '$'.$element #'
 4025:   }
 4026:   if (defined($moreenv)) {
 4027:       %form=(%form,%{$moreenv});
 4028:   }
 4029:   if (defined($target)) { $form{'grade_target'} = $target; }
 4030:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4031:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4032:   $userview=~s/\<body[^\>]*\>//gi;
 4033:   $userview=~s/\<\/body\>//gi;
 4034:   $userview=~s/\<html\>//gi;
 4035:   $userview=~s/\<\/html\>//gi;
 4036:   $userview=~s/\<head\>//gi;
 4037:   $userview=~s/\<\/head\>//gi;
 4038:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4039:   $userview=&relative_to_absolute($feedurl,$userview);
 4040:   if (wantarray) {
 4041:      return ($userview,$response);
 4042:   } else {
 4043:      return $userview;
 4044:   }
 4045: }
 4046: 
 4047: sub get_student_view_with_retries {
 4048:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4049: 
 4050:     my $ok = 0;                 # True if we got a good response.
 4051:     my $content;
 4052:     my $response;
 4053: 
 4054:     # Try to get the student_view done. within the retries count:
 4055:     
 4056:     do {
 4057:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4058:          $ok      = $response->is_success;
 4059:          if (!$ok) {
 4060:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4061:          }
 4062:          $retries--;
 4063:     } while (!$ok && ($retries > 0));
 4064:     
 4065:     if (!$ok) {
 4066:        $content = '';          # On error return an empty content.
 4067:     }
 4068:     if (wantarray) {
 4069:        return ($content, $response);
 4070:     } else {
 4071:        return $content;
 4072:     }
 4073: }
 4074: 
 4075: =pod
 4076: 
 4077: =item * &get_student_answers() 
 4078: 
 4079: show a snapshot of how student was answering problem
 4080: 
 4081: =cut
 4082: 
 4083: sub get_student_answers {
 4084:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4085:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4086:   my (%moreenv);
 4087:   my @elements=('symb','courseid','domain','username');
 4088:   foreach my $element (@elements) {
 4089:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4090:   }
 4091:   $moreenv{'grade_target'}='answer';
 4092:   %moreenv=(%form,%moreenv);
 4093:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4094:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4095:   return $userview;
 4096: }
 4097: 
 4098: =pod
 4099: 
 4100: =item * &submlink()
 4101: 
 4102: Inputs: $text $uname $udom $symb $target
 4103: 
 4104: Returns: A link to grades.pm such as to see the SUBM view of a student
 4105: 
 4106: =cut
 4107: 
 4108: ###############################################
 4109: sub submlink {
 4110:     my ($text,$uname,$udom,$symb,$target)=@_;
 4111:     if (!($uname && $udom)) {
 4112: 	(my $cursymb, my $courseid,$udom,$uname)=
 4113: 	    &Apache::lonnet::whichuser($symb);
 4114: 	if (!$symb) { $symb=$cursymb; }
 4115:     }
 4116:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4117:     $symb=&escape($symb);
 4118:     if ($target) { $target=" target=\"$target\""; }
 4119:     return
 4120:         '<a href="/adm/grades?command=submission'.
 4121:         '&amp;symb='.$symb.
 4122:         '&amp;student='.$uname.
 4123:         '&amp;userdom='.$udom.'"'.
 4124:         $target.'>'.$text.'</a>';
 4125: }
 4126: ##############################################
 4127: 
 4128: =pod
 4129: 
 4130: =item * &pgrdlink()
 4131: 
 4132: Inputs: $text $uname $udom $symb $target
 4133: 
 4134: Returns: A link to grades.pm such as to see the PGRD view of a student
 4135: 
 4136: =cut
 4137: 
 4138: ###############################################
 4139: sub pgrdlink {
 4140:     my $link=&submlink(@_);
 4141:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4142:     return $link;
 4143: }
 4144: ##############################################
 4145: 
 4146: =pod
 4147: 
 4148: =item * &pprmlink()
 4149: 
 4150: Inputs: $text $uname $udom $symb $target
 4151: 
 4152: Returns: A link to parmset.pm such as to see the PPRM view of a
 4153: student and a specific resource
 4154: 
 4155: =cut
 4156: 
 4157: ###############################################
 4158: sub pprmlink {
 4159:     my ($text,$uname,$udom,$symb,$target)=@_;
 4160:     if (!($uname && $udom)) {
 4161: 	(my $cursymb, my $courseid,$udom,$uname)=
 4162: 	    &Apache::lonnet::whichuser($symb);
 4163: 	if (!$symb) { $symb=$cursymb; }
 4164:     }
 4165:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4166:     $symb=&escape($symb);
 4167:     if ($target) { $target="target=\"$target\""; }
 4168:     return '<a href="/adm/parmset?command=set&amp;'.
 4169: 	'symb='.$symb.'&amp;uname='.$uname.
 4170: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4171: }
 4172: ##############################################
 4173: 
 4174: =pod
 4175: 
 4176: =back
 4177: 
 4178: =cut
 4179: 
 4180: ###############################################
 4181: 
 4182: 
 4183: sub timehash {
 4184:     my ($thistime) = @_;
 4185:     my $timezone = &Apache::lonlocal::gettimezone();
 4186:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4187:                      ->set_time_zone($timezone);
 4188:     my $wday = $dt->day_of_week();
 4189:     if ($wday == 7) { $wday = 0; }
 4190:     return ( 'second' => $dt->second(),
 4191:              'minute' => $dt->minute(),
 4192:              'hour'   => $dt->hour(),
 4193:              'day'     => $dt->day_of_month(),
 4194:              'month'   => $dt->month(),
 4195:              'year'    => $dt->year(),
 4196:              'weekday' => $wday,
 4197:              'dayyear' => $dt->day_of_year(),
 4198:              'dlsav'   => $dt->is_dst() );
 4199: }
 4200: 
 4201: sub utc_string {
 4202:     my ($date)=@_;
 4203:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4204: }
 4205: 
 4206: sub maketime {
 4207:     my %th=@_;
 4208:     my ($epoch_time,$timezone,$dt);
 4209:     $timezone = &Apache::lonlocal::gettimezone();
 4210:     eval {
 4211:         $dt = DateTime->new( year   => $th{'year'},
 4212:                              month  => $th{'month'},
 4213:                              day    => $th{'day'},
 4214:                              hour   => $th{'hour'},
 4215:                              minute => $th{'minute'},
 4216:                              second => $th{'second'},
 4217:                              time_zone => $timezone,
 4218:                          );
 4219:     };
 4220:     if (!$@) {
 4221:         $epoch_time = $dt->epoch;
 4222:         if ($epoch_time) {
 4223:             return $epoch_time;
 4224:         }
 4225:     }
 4226:     return POSIX::mktime(
 4227:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4228:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4229: }
 4230: 
 4231: #########################################
 4232: 
 4233: sub findallcourses {
 4234:     my ($roles,$uname,$udom) = @_;
 4235:     my %roles;
 4236:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4237:     my %courses;
 4238:     my $now=time;
 4239:     if (!defined($uname)) {
 4240:         $uname = $env{'user.name'};
 4241:     }
 4242:     if (!defined($udom)) {
 4243:         $udom = $env{'user.domain'};
 4244:     }
 4245:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4246:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4247:         if (!%roles) {
 4248:             %roles = (
 4249:                        cc => 1,
 4250:                        co => 1,
 4251:                        in => 1,
 4252:                        ep => 1,
 4253:                        ta => 1,
 4254:                        cr => 1,
 4255:                        st => 1,
 4256:              );
 4257:         }
 4258:         foreach my $entry (keys(%roleshash)) {
 4259:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4260:             if ($trole =~ /^cr/) { 
 4261:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4262:             } else {
 4263:                 next if (!exists($roles{$trole}));
 4264:             }
 4265:             if ($tend) {
 4266:                 next if ($tend < $now);
 4267:             }
 4268:             if ($tstart) {
 4269:                 next if ($tstart > $now);
 4270:             }
 4271:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4272:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4273:             my $value = $trole.'/'.$cdom.'/';
 4274:             if ($secpart eq '') {
 4275:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4276:                 $sec = 'none';
 4277:                 $value .= $cnum.'/';
 4278:             } else {
 4279:                 $cnum = $cnumpart;
 4280:                 ($sec,$role) = split(/_/,$secpart);
 4281:                 $value .= $cnum.'/'.$sec;
 4282:             }
 4283:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4284:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4285:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4286:                 }
 4287:             } else {
 4288:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4289:             }
 4290:         }
 4291:     } else {
 4292:         foreach my $key (keys(%env)) {
 4293: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4294:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4295: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4296: 	        next if ($role eq 'ca' || $role eq 'aa');
 4297: 	        next if (%roles && !exists($roles{$role}));
 4298: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4299:                 my $active=1;
 4300:                 if ($starttime) {
 4301: 		    if ($now<$starttime) { $active=0; }
 4302:                 }
 4303:                 if ($endtime) {
 4304:                     if ($now>$endtime) { $active=0; }
 4305:                 }
 4306:                 if ($active) {
 4307:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4308:                     if ($sec eq '') {
 4309:                         $sec = 'none';
 4310:                     } else {
 4311:                         $value .= $sec;
 4312:                     }
 4313:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4314:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4315:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4316:                         }
 4317:                     } else {
 4318:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4319:                     }
 4320:                 }
 4321:             }
 4322:         }
 4323:     }
 4324:     return %courses;
 4325: }
 4326: 
 4327: ###############################################
 4328: 
 4329: sub blockcheck {
 4330:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4331: 
 4332:     if (defined($udom) && defined($uname)) {
 4333:         # If uname and udom are for a course, check for blocks in the course.
 4334:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4335:             my ($startblock,$endblock,$triggerblock) =
 4336:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4337:             return ($startblock,$endblock,$triggerblock);
 4338:         }
 4339:     } else {
 4340:         $udom = $env{'user.domain'};
 4341:         $uname = $env{'user.name'};
 4342:     }
 4343: 
 4344:     my $startblock = 0;
 4345:     my $endblock = 0;
 4346:     my $triggerblock = '';
 4347:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4348: 
 4349:     # If uname is for a user, and activity is course-specific, i.e.,
 4350:     # boards, chat or groups, check for blocking in current course only.
 4351: 
 4352:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4353:          $activity eq 'groups' || $activity eq 'printout') &&
 4354:         ($env{'request.course.id'})) {
 4355:         foreach my $key (keys(%live_courses)) {
 4356:             if ($key ne $env{'request.course.id'}) {
 4357:                 delete($live_courses{$key});
 4358:             }
 4359:         }
 4360:     }
 4361: 
 4362:     my $otheruser = 0;
 4363:     my %own_courses;
 4364:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4365:         # Resource belongs to user other than current user.
 4366:         $otheruser = 1;
 4367:         # Gather courses for current user
 4368:         %own_courses = 
 4369:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4370:     }
 4371: 
 4372:     # Gather active course roles - course coordinator, instructor, 
 4373:     # exam proctor, ta, student, or custom role.
 4374: 
 4375:     foreach my $course (keys(%live_courses)) {
 4376:         my ($cdom,$cnum);
 4377:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4378:             $cdom = $env{'course.'.$course.'.domain'};
 4379:             $cnum = $env{'course.'.$course.'.num'};
 4380:         } else {
 4381:             ($cdom,$cnum) = split(/_/,$course); 
 4382:         }
 4383:         my $no_ownblock = 0;
 4384:         my $no_userblock = 0;
 4385:         if ($otheruser && $activity ne 'com') {
 4386:             # Check if current user has 'evb' priv for this
 4387:             if (defined($own_courses{$course})) {
 4388:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4389:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4390:                     if ($sec ne 'none') {
 4391:                         $checkrole .= '/'.$sec;
 4392:                     }
 4393:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4394:                         $no_ownblock = 1;
 4395:                         last;
 4396:                     }
 4397:                 }
 4398:             }
 4399:             # if they have 'evb' priv and are currently not playing student
 4400:             next if (($no_ownblock) &&
 4401:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4402:         }
 4403:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4404:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4405:             if ($sec ne 'none') {
 4406:                 $checkrole .= '/'.$sec;
 4407:             }
 4408:             if ($otheruser) {
 4409:                 # Resource belongs to user other than current user.
 4410:                 # Assemble privs for that user, and check for 'evb' priv.
 4411:                 my (%allroles,%userroles);
 4412:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4413:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4414:                         my ($trole,$tdom,$tnum,$tsec);
 4415:                         if ($entry =~ /^cr/) {
 4416:                             ($trole,$tdom,$tnum,$tsec) = 
 4417:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4418:                         } else {
 4419:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4420:                         }
 4421:                         my ($spec,$area,$trest);
 4422:                         $area = '/'.$tdom.'/'.$tnum;
 4423:                         $trest = $tnum;
 4424:                         if ($tsec ne '') {
 4425:                             $area .= '/'.$tsec;
 4426:                             $trest .= '/'.$tsec;
 4427:                         }
 4428:                         $spec = $trole.'.'.$area;
 4429:                         if ($trole =~ /^cr/) {
 4430:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4431:                                                               $tdom,$spec,$trest,$area);
 4432:                         } else {
 4433:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4434:                                                                 $tdom,$spec,$trest,$area);
 4435:                         }
 4436:                     }
 4437:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4438:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4439:                         if ($1) {
 4440:                             $no_userblock = 1;
 4441:                             last;
 4442:                         }
 4443:                     }
 4444:                 }
 4445:             } else {
 4446:                 # Resource belongs to current user
 4447:                 # Check for 'evb' priv via lonnet::allowed().
 4448:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4449:                     $no_ownblock = 1;
 4450:                     last;
 4451:                 }
 4452:             }
 4453:         }
 4454:         # if they have the evb priv and are currently not playing student
 4455:         next if (($no_ownblock) &&
 4456:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4457:         next if ($no_userblock);
 4458: 
 4459:         # Retrieve blocking times and identity of locker for course
 4460:         # of specified user, unless user has 'evb' privilege.
 4461:         
 4462:         my ($start,$end,$trigger) = 
 4463:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4464:         if (($start != 0) && 
 4465:             (($startblock == 0) || ($startblock > $start))) {
 4466:             $startblock = $start;
 4467:             if ($trigger ne '') {
 4468:                 $triggerblock = $trigger;
 4469:             }
 4470:         }
 4471:         if (($end != 0)  &&
 4472:             (($endblock == 0) || ($endblock < $end))) {
 4473:             $endblock = $end;
 4474:             if ($trigger ne '') {
 4475:                 $triggerblock = $trigger;
 4476:             }
 4477:         }
 4478:     }
 4479:     return ($startblock,$endblock,$triggerblock);
 4480: }
 4481: 
 4482: sub get_blocks {
 4483:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4484:     my $startblock = 0;
 4485:     my $endblock = 0;
 4486:     my $triggerblock = '';
 4487:     my $course = $cdom.'_'.$cnum;
 4488:     $setters->{$course} = {};
 4489:     $setters->{$course}{'staff'} = [];
 4490:     $setters->{$course}{'times'} = [];
 4491:     $setters->{$course}{'triggers'} = [];
 4492:     my (@blockers,%triggered);
 4493:     my $now = time;
 4494:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4495:     if ($activity eq 'docs') {
 4496:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4497:         foreach my $block (@blockers) {
 4498:             if ($block =~ /^firstaccess____(.+)$/) {
 4499:                 my $item = $1;
 4500:                 my $type = 'map';
 4501:                 my $timersymb = $item;
 4502:                 if ($item eq 'course') {
 4503:                     $type = 'course';
 4504:                 } elsif ($item =~ /___\d+___/) {
 4505:                     $type = 'resource';
 4506:                 } else {
 4507:                     $timersymb = &Apache::lonnet::symbread($item);
 4508:                 }
 4509:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4510:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4511:                 $triggered{$block} = {
 4512:                                        start => $start,
 4513:                                        end   => $end,
 4514:                                        type  => $type,
 4515:                                      };
 4516:             }
 4517:         }
 4518:     } else {
 4519:         foreach my $block (keys(%commblocks)) {
 4520:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4521:                 my ($start,$end) = ($1,$2);
 4522:                 if ($start <= time && $end >= time) {
 4523:                     if (ref($commblocks{$block}) eq 'HASH') {
 4524:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4525:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4526:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4527:                                     push(@blockers,$block);
 4528:                                 }
 4529:                             }
 4530:                         }
 4531:                     }
 4532:                 }
 4533:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4534:                 my $item = $1;
 4535:                 my $timersymb = $item; 
 4536:                 my $type = 'map';
 4537:                 if ($item eq 'course') {
 4538:                     $type = 'course';
 4539:                 } elsif ($item =~ /___\d+___/) {
 4540:                     $type = 'resource';
 4541:                 } else {
 4542:                     $timersymb = &Apache::lonnet::symbread($item);
 4543:                 }
 4544:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4545:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4546:                 if ($start && $end) {
 4547:                     if (($start <= time) && ($end >= time)) {
 4548:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4549:                             push(@blockers,$block);
 4550:                             $triggered{$block} = {
 4551:                                                    start => $start,
 4552:                                                    end   => $end,
 4553:                                                    type  => $type,
 4554:                                                  };
 4555:                         }
 4556:                     }
 4557:                 }
 4558:             }
 4559:         }
 4560:     }
 4561:     foreach my $blocker (@blockers) {
 4562:         my ($staff_name,$staff_dom,$title,$blocks) =
 4563:             &parse_block_record($commblocks{$blocker});
 4564:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4565:         my ($start,$end,$triggertype);
 4566:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4567:             ($start,$end) = ($1,$2);
 4568:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4569:             $start = $triggered{$blocker}{'start'};
 4570:             $end = $triggered{$blocker}{'end'};
 4571:             $triggertype = $triggered{$blocker}{'type'};
 4572:         }
 4573:         if ($start) {
 4574:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4575:             if ($triggertype) {
 4576:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4577:             } else {
 4578:                 push(@{$$setters{$course}{'triggers'}},0);
 4579:             }
 4580:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4581:                 $startblock = $start;
 4582:                 if ($triggertype) {
 4583:                     $triggerblock = $blocker;
 4584:                 }
 4585:             }
 4586:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4587:                $endblock = $end;
 4588:                if ($triggertype) {
 4589:                    $triggerblock = $blocker;
 4590:                }
 4591:             }
 4592:         }
 4593:     }
 4594:     return ($startblock,$endblock,$triggerblock);
 4595: }
 4596: 
 4597: sub parse_block_record {
 4598:     my ($record) = @_;
 4599:     my ($setuname,$setudom,$title,$blocks);
 4600:     if (ref($record) eq 'HASH') {
 4601:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4602:         $title = &unescape($record->{'event'});
 4603:         $blocks = $record->{'blocks'};
 4604:     } else {
 4605:         my @data = split(/:/,$record,3);
 4606:         if (scalar(@data) eq 2) {
 4607:             $title = $data[1];
 4608:             ($setuname,$setudom) = split(/@/,$data[0]);
 4609:         } else {
 4610:             ($setuname,$setudom,$title) = @data;
 4611:         }
 4612:         $blocks = { 'com' => 'on' };
 4613:     }
 4614:     return ($setuname,$setudom,$title,$blocks);
 4615: }
 4616: 
 4617: sub blocking_status {
 4618:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4619:     my %setters;
 4620: 
 4621: # check for active blocking
 4622:     my ($startblock,$endblock,$triggerblock) = 
 4623:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4624:     my $blocked = 0;
 4625:     if ($startblock && $endblock) {
 4626:         $blocked = 1;
 4627:     }
 4628: 
 4629: # caller just wants to know whether a block is active
 4630:     if (!wantarray) { return $blocked; }
 4631: 
 4632: # build a link to a popup window containing the details
 4633:     my $querystring  = "?activity=$activity";
 4634: # $uname and $udom decide whose portfolio the user is trying to look at
 4635:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4636:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 4637:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4638:     } elsif ($activity eq 'docs') {
 4639:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4640:     }
 4641: 
 4642:     my $output .= <<'END_MYBLOCK';
 4643: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4644:     var options = "width=" + w + ",height=" + h + ",";
 4645:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4646:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4647:     var newWin = window.open(url, wdwName, options);
 4648:     newWin.focus();
 4649: }
 4650: END_MYBLOCK
 4651: 
 4652:     $output = Apache::lonhtmlcommon::scripttag($output);
 4653:   
 4654:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4655:     my $text = &mt('Communication Blocked');
 4656:     my $class = 'LC_comblock';
 4657:     if ($activity eq 'docs') {
 4658:         $text = &mt('Content Access Blocked');
 4659:         $class = '';
 4660:     } elsif ($activity eq 'printout') {
 4661:         $text = &mt('Printing Blocked');
 4662:     } elsif ($activity eq 'passwd') {
 4663:         $text = &mt('Password Changing Blocked');
 4664:     }
 4665:     $output .= <<"END_BLOCK";
 4666: <div class='$class'>
 4667:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4668:   title='$text'>
 4669:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4670:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4671:   title='$text'>$text</a>
 4672: </div>
 4673: 
 4674: END_BLOCK
 4675: 
 4676:     return ($blocked, $output);
 4677: }
 4678: 
 4679: ###############################################
 4680: 
 4681: sub check_ip_acc {
 4682:     my ($acc)=@_;
 4683:     &Apache::lonxml::debug("acc is $acc");
 4684:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4685:         return 1;
 4686:     }
 4687:     my $allowed=0;
 4688:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4689: 
 4690:     my $name;
 4691:     foreach my $pattern (split(',',$acc)) {
 4692:         $pattern =~ s/^\s*//;
 4693:         $pattern =~ s/\s*$//;
 4694:         if ($pattern =~ /\*$/) {
 4695:             #35.8.*
 4696:             $pattern=~s/\*//;
 4697:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4698:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4699:             #35.8.3.[34-56]
 4700:             my $low=$2;
 4701:             my $high=$3;
 4702:             $pattern=$1;
 4703:             if ($ip =~ /^\Q$pattern\E/) {
 4704:                 my $last=(split(/\./,$ip))[3];
 4705:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4706:             }
 4707:         } elsif ($pattern =~ /^\*/) {
 4708:             #*.msu.edu
 4709:             $pattern=~s/\*//;
 4710:             if (!defined($name)) {
 4711:                 use Socket;
 4712:                 my $netaddr=inet_aton($ip);
 4713:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4714:             }
 4715:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4716:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4717:             #127.0.0.1
 4718:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4719:         } else {
 4720:             #some.name.com
 4721:             if (!defined($name)) {
 4722:                 use Socket;
 4723:                 my $netaddr=inet_aton($ip);
 4724:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4725:             }
 4726:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4727:         }
 4728:         if ($allowed) { last; }
 4729:     }
 4730:     return $allowed;
 4731: }
 4732: 
 4733: ###############################################
 4734: 
 4735: =pod
 4736: 
 4737: =head1 Domain Template Functions
 4738: 
 4739: =over 4
 4740: 
 4741: =item * &determinedomain()
 4742: 
 4743: Inputs: $domain (usually will be undef)
 4744: 
 4745: Returns: Determines which domain should be used for designs
 4746: 
 4747: =cut
 4748: 
 4749: ###############################################
 4750: sub determinedomain {
 4751:     my $domain=shift;
 4752:     if (! $domain) {
 4753:         # Determine domain if we have not been given one
 4754:         $domain = &Apache::lonnet::default_login_domain();
 4755:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4756:         if ($env{'request.role.domain'}) { 
 4757:             $domain=$env{'request.role.domain'}; 
 4758:         }
 4759:     }
 4760:     return $domain;
 4761: }
 4762: ###############################################
 4763: 
 4764: sub devalidate_domconfig_cache {
 4765:     my ($udom)=@_;
 4766:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4767: }
 4768: 
 4769: # ---------------------- Get domain configuration for a domain
 4770: sub get_domainconf {
 4771:     my ($udom) = @_;
 4772:     my $cachetime=1800;
 4773:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4774:     if (defined($cached)) { return %{$result}; }
 4775: 
 4776:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4777: 					     ['login','rolecolors','autoenroll'],$udom);
 4778:     my (%designhash,%legacy);
 4779:     if (keys(%domconfig) > 0) {
 4780:         if (ref($domconfig{'login'}) eq 'HASH') {
 4781:             if (keys(%{$domconfig{'login'}})) {
 4782:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4783:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4784:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 4785:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4786:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 4787:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 4788:                                         if ($key eq 'loginvia') {
 4789:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4790:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4791:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 4792:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4793:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4794:                                                 } else {
 4795:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4796:                                                 }
 4797:                                             }
 4798:                                         } elsif ($key eq 'headtag') {
 4799:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 4800:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 4801:                                             }
 4802:                                         }
 4803:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 4804:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 4805:                                         }
 4806:                                     }
 4807:                                 }
 4808:                             }
 4809:                         } else {
 4810:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4811:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4812:                                     $domconfig{'login'}{$key}{$img};
 4813:                             }
 4814:                         }
 4815:                     } else {
 4816:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4817:                     }
 4818:                 }
 4819:             } else {
 4820:                 $legacy{'login'} = 1;
 4821:             }
 4822:         } else {
 4823:             $legacy{'login'} = 1;
 4824:         }
 4825:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4826:             if (keys(%{$domconfig{'rolecolors'}})) {
 4827:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4828:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4829:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4830:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4831:                         }
 4832:                     }
 4833:                 }
 4834:             } else {
 4835:                 $legacy{'rolecolors'} = 1;
 4836:             }
 4837:         } else {
 4838:             $legacy{'rolecolors'} = 1;
 4839:         }
 4840:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4841:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4842:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4843:             }
 4844:         }
 4845:         if (keys(%legacy) > 0) {
 4846:             my %legacyhash = &get_legacy_domconf($udom);
 4847:             foreach my $item (keys(%legacyhash)) {
 4848:                 if ($item =~ /^\Q$udom\E\.login/) {
 4849:                     if ($legacy{'login'}) { 
 4850:                         $designhash{$item} = $legacyhash{$item};
 4851:                     }
 4852:                 } else {
 4853:                     if ($legacy{'rolecolors'}) {
 4854:                         $designhash{$item} = $legacyhash{$item};
 4855:                     }
 4856:                 }
 4857:             }
 4858:         }
 4859:     } else {
 4860:         %designhash = &get_legacy_domconf($udom); 
 4861:     }
 4862:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4863: 				  $cachetime);
 4864:     return %designhash;
 4865: }
 4866: 
 4867: sub get_legacy_domconf {
 4868:     my ($udom) = @_;
 4869:     my %legacyhash;
 4870:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4871:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4872:     if (-e $designfile) {
 4873:         if ( open (my $fh,"<$designfile") ) {
 4874:             while (my $line = <$fh>) {
 4875:                 next if ($line =~ /^\#/);
 4876:                 chomp($line);
 4877:                 my ($key,$val)=(split(/\=/,$line));
 4878:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4879:             }
 4880:             close($fh);
 4881:         }
 4882:     }
 4883:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4884:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4885:     }
 4886:     return %legacyhash;
 4887: }
 4888: 
 4889: =pod
 4890: 
 4891: =item * &domainlogo()
 4892: 
 4893: Inputs: $domain (usually will be undef)
 4894: 
 4895: Returns: A link to a domain logo, if the domain logo exists.
 4896: If the domain logo does not exist, a description of the domain.
 4897: 
 4898: =cut
 4899: 
 4900: ###############################################
 4901: sub domainlogo {
 4902:     my $domain = &determinedomain(shift);
 4903:     my %designhash = &get_domainconf($domain);    
 4904:     # See if there is a logo
 4905:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4906:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4907:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4908: 	    if ($imgsrc =~ m{^/res/}) {
 4909: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4910: 		&Apache::lonnet::repcopy($local_name);
 4911: 	    }
 4912: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4913:         } 
 4914:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4915:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4916:         return &Apache::lonnet::domain($domain,'description');
 4917:     } else {
 4918:         return '';
 4919:     }
 4920: }
 4921: ##############################################
 4922: 
 4923: =pod
 4924: 
 4925: =item * &designparm()
 4926: 
 4927: Inputs: $which parameter; $domain (usually will be undef)
 4928: 
 4929: Returns: value of designparamter $which
 4930: 
 4931: =cut
 4932: 
 4933: 
 4934: ##############################################
 4935: sub designparm {
 4936:     my ($which,$domain)=@_;
 4937:     if (exists($env{'environment.color.'.$which})) {
 4938:         return $env{'environment.color.'.$which};
 4939:     }
 4940:     $domain=&determinedomain($domain);
 4941:     my %domdesign;
 4942:     unless ($domain eq 'public') {
 4943:         %domdesign = &get_domainconf($domain);
 4944:     }
 4945:     my $output;
 4946:     if ($domdesign{$domain.'.'.$which} ne '') {
 4947:         $output = $domdesign{$domain.'.'.$which};
 4948:     } else {
 4949:         $output = $defaultdesign{$which};
 4950:     }
 4951:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4952:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4953:         if ($output =~ m{^/(adm|res)/}) {
 4954:             if ($output =~ m{^/res/}) {
 4955:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4956:                 &Apache::lonnet::repcopy($local_name);
 4957:             }
 4958:             $output = &lonhttpdurl($output);
 4959:         }
 4960:     }
 4961:     return $output;
 4962: }
 4963: 
 4964: ##############################################
 4965: =pod
 4966: 
 4967: =item * &authorspace()
 4968: 
 4969: Inputs: $url (usually will be undef).
 4970: 
 4971: Returns: Path to Authoring Space containing the resource or 
 4972:          directory being viewed (or for which action is being taken). 
 4973:          If $url is provided, and begins /priv/<domain>/<uname>
 4974:          the path will be that portion of the $context argument.
 4975:          Otherwise the path will be for the author space of the current
 4976:          user when the current role is author, or for that of the 
 4977:          co-author/assistant co-author space when the current role 
 4978:          is co-author or assistant co-author.
 4979: 
 4980: =cut
 4981: 
 4982: sub authorspace {
 4983:     my ($url) = @_;
 4984:     if ($url ne '') {
 4985:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4986:            return $1;
 4987:         }
 4988:     }
 4989:     my $caname = '';
 4990:     my $cadom = '';
 4991:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4992:         ($cadom,$caname) =
 4993:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4994:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4995:         $caname = $env{'user.name'};
 4996:         $cadom = $env{'user.domain'};
 4997:     }
 4998:     if (($caname ne '') && ($cadom ne '')) {
 4999:         return "/priv/$cadom/$caname/";
 5000:     }
 5001:     return;
 5002: }
 5003: 
 5004: ##############################################
 5005: =pod
 5006: 
 5007: =item * &head_subbox()
 5008: 
 5009: Inputs: $content (contains HTML code with page functions, etc.)
 5010: 
 5011: Returns: HTML div with $content
 5012:          To be included in page header
 5013: 
 5014: =cut
 5015: 
 5016: sub head_subbox {
 5017:     my ($content)=@_;
 5018:     my $output =
 5019:         '<div class="LC_head_subbox">'
 5020:        .$content
 5021:        .'</div>'
 5022: }
 5023: 
 5024: ##############################################
 5025: =pod
 5026: 
 5027: =item * &CSTR_pageheader()
 5028: 
 5029: Input: (optional) filename from which breadcrumb trail is built.
 5030:        In most cases no input as needed, as $env{'request.filename'}
 5031:        is appropriate for use in building the breadcrumb trail.
 5032: 
 5033: Returns: HTML div with CSTR path and recent box
 5034:          To be included on Authoring Space pages
 5035: 
 5036: =cut
 5037: 
 5038: sub CSTR_pageheader {
 5039:     my ($trailfile) = @_;
 5040:     if ($trailfile eq '') {
 5041:         $trailfile = $env{'request.filename'};
 5042:     }
 5043: 
 5044: # this is for resources; directories have customtitle, and crumbs
 5045: # and select recent are created in lonpubdir.pm
 5046: 
 5047:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5048:     my ($udom,$uname,$thisdisfn)=
 5049:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5050:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5051:     $formaction =~ s{/+}{/}g;
 5052: 
 5053:     my $parentpath = '';
 5054:     my $lastitem = '';
 5055:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5056:         $parentpath = $1;
 5057:         $lastitem = $2;
 5058:     } else {
 5059:         $lastitem = $thisdisfn;
 5060:     }
 5061: 
 5062:     my $output =
 5063:          '<div>'
 5064:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5065:         .'<b>'.&mt('Authoring Space:').'</b> '
 5066:         .'<form name="dirs" method="post" action="'.$formaction
 5067:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5068:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5069: 
 5070:     if ($lastitem) {
 5071:         $output .=
 5072:              '<span class="LC_filename">'
 5073:             .$lastitem
 5074:             .'</span>';
 5075:     }
 5076:     $output .=
 5077:          '<br />'
 5078:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5079:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5080:         .'</form>'
 5081:         .&Apache::lonmenu::constspaceform()
 5082:         .'</div>';
 5083: 
 5084:     return $output;
 5085: }
 5086: 
 5087: ###############################################
 5088: ###############################################
 5089: 
 5090: =pod
 5091: 
 5092: =back
 5093: 
 5094: =head1 HTML Helpers
 5095: 
 5096: =over 4
 5097: 
 5098: =item * &bodytag()
 5099: 
 5100: Returns a uniform header for LON-CAPA web pages.
 5101: 
 5102: Inputs: 
 5103: 
 5104: =over 4
 5105: 
 5106: =item * $title, A title to be displayed on the page.
 5107: 
 5108: =item * $function, the current role (can be undef).
 5109: 
 5110: =item * $addentries, extra parameters for the <body> tag.
 5111: 
 5112: =item * $bodyonly, if defined, only return the <body> tag.
 5113: 
 5114: =item * $domain, if defined, force a given domain.
 5115: 
 5116: =item * $forcereg, if page should register as content page (relevant for 
 5117:             text interface only)
 5118: 
 5119: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5120:                      navigational links
 5121: 
 5122: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5123: 
 5124: =item * $no_inline_link, if true and in remote mode, don't show the
 5125:          'Switch To Inline Menu' link
 5126: 
 5127: =item * $args, optional argument valid values are
 5128:             no_auto_mt_title -> prevents &mt()ing the title arg
 5129:             inherit_jsmath -> when creating popup window in a page,
 5130:                               should it have jsmath forced on by the
 5131:                               current page
 5132: 
 5133: =item * $advtoolsref, optional argument, ref to an array containing
 5134:             inlineremote items to be added in "Functions" menu below
 5135:             breadcrumbs.
 5136: 
 5137: =back
 5138: 
 5139: Returns: A uniform header for LON-CAPA web pages.  
 5140: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5141: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5142: other decorations will be returned.
 5143: 
 5144: =cut
 5145: 
 5146: sub bodytag {
 5147:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5148:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5149: 
 5150:     my $public;
 5151:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5152:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5153:         $public = 1;
 5154:     }
 5155:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5156:     my $httphost = $args->{'use_absolute'};
 5157: 
 5158:     $function = &get_users_function() if (!$function);
 5159:     my $img =    &designparm($function.'.img',$domain);
 5160:     my $font =   &designparm($function.'.font',$domain);
 5161:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5162: 
 5163:     my %design = ( 'style'   => 'margin-top: 0',
 5164: 		   'bgcolor' => $pgbg,
 5165: 		   'text'    => $font,
 5166:                    'alink'   => &designparm($function.'.alink',$domain),
 5167: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5168: 		   'link'    => &designparm($function.'.link',$domain),);
 5169:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5170: 
 5171:  # role and realm
 5172:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5173:     if ($realm) {
 5174:         $realm = '/'.$realm;
 5175:     }
 5176:     if ($role  eq 'ca') {
 5177:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5178:         $realm = &plainname($rname,$rdom);
 5179:     } 
 5180: # realm
 5181:     if ($env{'request.course.id'}) {
 5182:         if ($env{'request.role'} !~ /^cr/) {
 5183:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5184:         }
 5185:         if ($env{'request.course.sec'}) {
 5186:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5187:         }   
 5188: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5189:     } else {
 5190:         $role = &Apache::lonnet::plaintext($role);
 5191:     }
 5192: 
 5193:     if (!$realm) { $realm='&nbsp;'; }
 5194: 
 5195:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5196: 
 5197: # construct main body tag
 5198:     my $bodytag = "<body $extra_body_attr>".
 5199: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5200: 
 5201:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5202: 
 5203:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5204:         return $bodytag;
 5205:     }
 5206: 
 5207:     if ($public) {
 5208: 	undef($role);
 5209:     }
 5210:     
 5211:     my $titleinfo = '<h1>'.$title.'</h1>';
 5212:     #
 5213:     # Extra info if you are the DC
 5214:     my $dc_info = '';
 5215:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5216:                         $env{'course.'.$env{'request.course.id'}.
 5217:                                  '.domain'}.'/'})) {
 5218:         my $cid = $env{'request.course.id'};
 5219:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5220:         $dc_info =~ s/\s+$//;
 5221:     }
 5222: 
 5223:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5224: 
 5225:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5226: 
 5227: 
 5228: 
 5229:     my $funclist;
 5230:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5231:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5232:                     Apache::lonmenu::serverform();
 5233:         my $forbodytag;
 5234:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5235:                                             $forcereg,$args->{'group'},
 5236:                                             $args->{'bread_crumbs'},
 5237:                                             $advtoolsref,'',\$forbodytag);
 5238:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5239:             $funclist = $forbodytag;
 5240:         }
 5241:     } else {
 5242: 
 5243:         #    if ($env{'request.state'} eq 'construct') {
 5244:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5245:         #    }
 5246: 
 5247:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5248:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5249: 
 5250:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5251: 
 5252:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5253:             if ($dc_info) {
 5254:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5255:             }
 5256:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5257:                            <em>$realm</em> $dc_info</div>|;
 5258:             return $bodytag;
 5259:         }
 5260: 
 5261:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5262:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5263:         }
 5264: 
 5265:         $bodytag .= $right;
 5266: 
 5267:         if ($dc_info) {
 5268:             $dc_info = &dc_courseid_toggle($dc_info);
 5269:         }
 5270:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5271: 
 5272:         #if directed to not display the secondary menu, don't.
 5273:         if ($args->{'no_secondary_menu'}) {
 5274:             return $bodytag;
 5275:         }
 5276:         #don't show menus for public users
 5277:         if (!$public){
 5278:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5279:             $bodytag .= Apache::lonmenu::serverform();
 5280:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5281:             if ($env{'request.state'} eq 'construct') {
 5282:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5283:                                 $args->{'bread_crumbs'});
 5284:             } elsif ($forcereg) { 
 5285:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5286:                                                             $args->{'group'});
 5287:             } else {
 5288:                 my $forbodytag;
 5289:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5290:                                                     $forcereg,$args->{'group'},
 5291:                                                     $args->{'bread_crumbs'},
 5292:                                                     $advtoolsref,'',\$forbodytag);
 5293:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5294:                     $bodytag .= $forbodytag;
 5295:                 }
 5296:             }
 5297:         }else{
 5298:             # this is to seperate menu from content when there's no secondary
 5299:             # menu. Especially needed for public accessible ressources.
 5300:             $bodytag .= '<hr style="clear:both" />';
 5301:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5302:         }
 5303: 
 5304:         return $bodytag;
 5305:     }
 5306: 
 5307: #
 5308: # Top frame rendering, Remote is up
 5309: #
 5310: 
 5311:     my $imgsrc = $img;
 5312:     if ($img =~ /^\/adm/) {
 5313:         $imgsrc = &lonhttpdurl($img);
 5314:     }
 5315:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5316: 
 5317:     my $help=($no_inline_link?''
 5318:               :&Apache::loncommon::top_nav_help('Help'));
 5319: 
 5320:     # Explicit link to get inline menu
 5321:     my $menu= ($no_inline_link?''
 5322:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5323: 
 5324:     if ($dc_info) {
 5325:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5326:     }
 5327: 
 5328:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5329:     unless ($public) {
 5330:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5331:                                 undef,'LC_menubuttons_link');
 5332:     }
 5333: 
 5334:     unless ($env{'form.inhibitmenu'}) {
 5335:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5336:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5337:                        <li>$help</li>
 5338:                        <li>$menu</li>
 5339:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5340:     }
 5341:     if ($env{'request.state'} eq 'construct') {
 5342:         if (!$public){
 5343:             if ($env{'request.state'} eq 'construct') {
 5344:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5345:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5346:                             &Apache::lonhtmlcommon::scripttag('','end').
 5347:                             &Apache::lonmenu::innerregister($forcereg,
 5348:                                                             $args->{'bread_crumbs'});
 5349:             }
 5350:         }
 5351:     }
 5352:     return $bodytag."\n".$funclist;
 5353: }
 5354: 
 5355: sub dc_courseid_toggle {
 5356:     my ($dc_info) = @_;
 5357:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5358:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5359:            &mt('(More ...)').'</a></span>'.
 5360:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5361: }
 5362: 
 5363: sub make_attr_string {
 5364:     my ($register,$attr_ref) = @_;
 5365: 
 5366:     if ($attr_ref && !ref($attr_ref)) {
 5367: 	die("addentries Must be a hash ref ".
 5368: 	    join(':',caller(1))." ".
 5369: 	    join(':',caller(0))." ");
 5370:     }
 5371: 
 5372:     if ($register) {
 5373: 	my ($on_load,$on_unload);
 5374: 	foreach my $key (keys(%{$attr_ref})) {
 5375: 	    if      (lc($key) eq 'onload') {
 5376: 		$on_load.=$attr_ref->{$key}.';';
 5377: 		delete($attr_ref->{$key});
 5378: 
 5379: 	    } elsif (lc($key) eq 'onunload') {
 5380: 		$on_unload.=$attr_ref->{$key}.';';
 5381: 		delete($attr_ref->{$key});
 5382: 	    }
 5383: 	}
 5384:         if ($env{'environment.remote'} eq 'on') {
 5385:             $attr_ref->{'onload'}  =
 5386:                 &Apache::lonmenu::loadevents().  $on_load;
 5387:             $attr_ref->{'onunload'}=
 5388:                 &Apache::lonmenu::unloadevents().$on_unload;
 5389:         } else {  
 5390: 	    $attr_ref->{'onload'}  = $on_load;
 5391: 	    $attr_ref->{'onunload'}= $on_unload;
 5392:         }
 5393:     }
 5394: 
 5395:     my $attr_string;
 5396:     foreach my $attr (sort(keys(%$attr_ref))) {
 5397: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5398:     }
 5399:     return $attr_string;
 5400: }
 5401: 
 5402: 
 5403: ###############################################
 5404: ###############################################
 5405: 
 5406: =pod
 5407: 
 5408: =item * &endbodytag()
 5409: 
 5410: Returns a uniform footer for LON-CAPA web pages.
 5411: 
 5412: Inputs: 1 - optional reference to an args hash
 5413: If in the hash, key for noredirectlink has a value which evaluates to true,
 5414: a 'Continue' link is not displayed if the page contains an
 5415: internal redirect in the <head></head> section,
 5416: i.e., $env{'internal.head.redirect'} exists   
 5417: 
 5418: =cut
 5419: 
 5420: sub endbodytag {
 5421:     my ($args) = @_;
 5422:     my $endbodytag;
 5423:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5424:         $endbodytag='</body>';
 5425:     }
 5426:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5427:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5428:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5429: 	    $endbodytag=
 5430: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5431: 	        &mt('Continue').'</a>'.
 5432: 	        $endbodytag;
 5433:         }
 5434:     }
 5435:     return $endbodytag;
 5436: }
 5437: 
 5438: =pod
 5439: 
 5440: =item * &standard_css()
 5441: 
 5442: Returns a style sheet
 5443: 
 5444: Inputs: (all optional)
 5445:             domain         -> force to color decorate a page for a specific
 5446:                                domain
 5447:             function       -> force usage of a specific rolish color scheme
 5448:             bgcolor        -> override the default page bgcolor
 5449: 
 5450: =cut
 5451: 
 5452: sub standard_css {
 5453:     my ($function,$domain,$bgcolor) = @_;
 5454:     $function  = &get_users_function() if (!$function);
 5455:     my $img    = &designparm($function.'.img',   $domain);
 5456:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5457:     my $font   = &designparm($function.'.font',  $domain);
 5458:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5459: #second colour for later usage
 5460:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5461:     my $pgbg_or_bgcolor =
 5462: 	         $bgcolor ||
 5463: 	         &designparm($function.'.pgbg',  $domain);
 5464:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5465:     my $alink  = &designparm($function.'.alink', $domain);
 5466:     my $vlink  = &designparm($function.'.vlink', $domain);
 5467:     my $link   = &designparm($function.'.link',  $domain);
 5468: 
 5469:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5470:     my $mono                 = 'monospace';
 5471:     my $data_table_head      = $sidebg;
 5472:     my $data_table_light     = '#FAFAFA';
 5473:     my $data_table_dark      = '#E0E0E0';
 5474:     my $data_table_darker    = '#CCCCCC';
 5475:     my $data_table_highlight = '#FFFF00';
 5476:     my $mail_new             = '#FFBB77';
 5477:     my $mail_new_hover       = '#DD9955';
 5478:     my $mail_read            = '#BBBB77';
 5479:     my $mail_read_hover      = '#999944';
 5480:     my $mail_replied         = '#AAAA88';
 5481:     my $mail_replied_hover   = '#888855';
 5482:     my $mail_other           = '#99BBBB';
 5483:     my $mail_other_hover     = '#669999';
 5484:     my $table_header         = '#DDDDDD';
 5485:     my $feedback_link_bg     = '#BBBBBB';
 5486:     my $lg_border_color      = '#C8C8C8';
 5487:     my $button_hover         = '#BF2317';
 5488: 
 5489:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5490:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5491:                                              : '0 3px 0 4px';
 5492: 
 5493: 
 5494:     return <<END;
 5495: 
 5496: /* needed for iframe to allow 100% height in FF */
 5497: body, html { 
 5498:     margin: 0;
 5499:     padding: 0 0.5%;
 5500:     height: 99%; /* to avoid scrollbars */
 5501: }
 5502: 
 5503: body {
 5504:   font-family: $sans;
 5505:   line-height:130%;
 5506:   font-size:0.83em;
 5507:   color:$font;
 5508: }
 5509: 
 5510: a:focus,
 5511: a:focus img {
 5512:   color: red;
 5513: }
 5514: 
 5515: form, .inline {
 5516:   display: inline;
 5517: }
 5518: 
 5519: .LC_right {
 5520:   text-align:right;
 5521: }
 5522: 
 5523: .LC_middle {
 5524:   vertical-align:middle;
 5525: }
 5526: 
 5527: .LC_floatleft {
 5528:   float: left;
 5529: }
 5530: 
 5531: .LC_floatright {
 5532:   float: right;
 5533: }
 5534: 
 5535: .LC_400Box {
 5536:   width:400px;
 5537: }
 5538: 
 5539: .LC_iframecontainer {
 5540:     width: 98%;
 5541:     margin: 0;
 5542:     position: fixed;
 5543:     top: 8.5em;
 5544:     bottom: 0;
 5545: }
 5546: 
 5547: .LC_iframecontainer iframe{
 5548:     border: none;
 5549:     width: 100%;
 5550:     height: 100%;
 5551: }
 5552: 
 5553: .LC_filename {
 5554:   font-family: $mono;
 5555:   white-space:pre;
 5556:   font-size: 120%;
 5557: }
 5558: 
 5559: .LC_fileicon {
 5560:   border: none;
 5561:   height: 1.3em;
 5562:   vertical-align: text-bottom;
 5563:   margin-right: 0.3em;
 5564:   text-decoration:none;
 5565: }
 5566: 
 5567: .LC_setting {
 5568:   text-decoration:underline;
 5569: }
 5570: 
 5571: .LC_error {
 5572:   color: red;
 5573: }
 5574: 
 5575: .LC_warning {
 5576:   color: darkorange;
 5577: }
 5578: 
 5579: .LC_diff_removed {
 5580:   color: red;
 5581: }
 5582: 
 5583: .LC_info,
 5584: .LC_success,
 5585: .LC_diff_added {
 5586:   color: green;
 5587: }
 5588: 
 5589: div.LC_confirm_box {
 5590:   background-color: #FAFAFA;
 5591:   border: 1px solid $lg_border_color;
 5592:   margin-right: 0;
 5593:   padding: 5px;
 5594: }
 5595: 
 5596: div.LC_confirm_box .LC_error img,
 5597: div.LC_confirm_box .LC_success img {
 5598:   vertical-align: middle;
 5599: }
 5600: 
 5601: .LC_icon {
 5602:   border: none;
 5603:   vertical-align: middle;
 5604: }
 5605: 
 5606: .LC_docs_spacer {
 5607:   width: 25px;
 5608:   height: 1px;
 5609:   border: none;
 5610: }
 5611: 
 5612: .LC_internal_info {
 5613:   color: #999999;
 5614: }
 5615: 
 5616: .LC_discussion {
 5617:   background: $data_table_dark;
 5618:   border: 1px solid black;
 5619:   margin: 2px;
 5620: }
 5621: 
 5622: .LC_disc_action_left {
 5623:   background: $sidebg;
 5624:   text-align: left;
 5625:   padding: 4px;
 5626:   margin: 2px;
 5627: }
 5628: 
 5629: .LC_disc_action_right {
 5630:   background: $sidebg;
 5631:   text-align: right;
 5632:   padding: 4px;
 5633:   margin: 2px;
 5634: }
 5635: 
 5636: .LC_disc_new_item {
 5637:   background: white;
 5638:   border: 2px solid red;
 5639:   margin: 4px;
 5640:   padding: 4px;
 5641: }
 5642: 
 5643: .LC_disc_old_item {
 5644:   background: white;
 5645:   margin: 4px;
 5646:   padding: 4px;
 5647: }
 5648: 
 5649: table.LC_pastsubmission {
 5650:   border: 1px solid black;
 5651:   margin: 2px;
 5652: }
 5653: 
 5654: table#LC_menubuttons {
 5655:   width: 100%;
 5656:   background: $pgbg;
 5657:   border: 2px;
 5658:   border-collapse: separate;
 5659:   padding: 0;
 5660: }
 5661: 
 5662: table#LC_title_bar a {
 5663:   color: $fontmenu;
 5664: }
 5665: 
 5666: table#LC_title_bar {
 5667:   clear: both;
 5668:   display: none;
 5669: }
 5670: 
 5671: table#LC_title_bar,
 5672: table.LC_breadcrumbs, /* obsolete? */
 5673: table#LC_title_bar.LC_with_remote {
 5674:   width: 100%;
 5675:   border-color: $pgbg;
 5676:   border-style: solid;
 5677:   border-width: $border;
 5678:   background: $pgbg;
 5679:   color: $fontmenu;
 5680:   border-collapse: collapse;
 5681:   padding: 0;
 5682:   margin: 0;
 5683: }
 5684: 
 5685: ul.LC_breadcrumb_tools_outerlist {
 5686:     margin: 0;
 5687:     padding: 0;
 5688:     position: relative;
 5689:     list-style: none;
 5690: }
 5691: ul.LC_breadcrumb_tools_outerlist li {
 5692:     display: inline;
 5693: }
 5694: 
 5695: .LC_breadcrumb_tools_navigation {
 5696:     padding: 0;
 5697:     margin: 0;
 5698:     float: left;
 5699: }
 5700: .LC_breadcrumb_tools_tools {
 5701:     padding: 0;
 5702:     margin: 0;
 5703:     float: right;
 5704: }
 5705: 
 5706: table#LC_title_bar td {
 5707:   background: $tabbg;
 5708: }
 5709: 
 5710: table#LC_menubuttons img {
 5711:   border: none;
 5712: }
 5713: 
 5714: .LC_breadcrumbs_component {
 5715:   float: right;
 5716:   margin: 0 1em;
 5717: }
 5718: .LC_breadcrumbs_component img {
 5719:   vertical-align: middle;
 5720: }
 5721: 
 5722: td.LC_table_cell_checkbox {
 5723:   text-align: center;
 5724: }
 5725: 
 5726: .LC_fontsize_small {
 5727:   font-size: 70%;
 5728: }
 5729: 
 5730: #LC_breadcrumbs {
 5731:   clear:both;
 5732:   background: $sidebg;
 5733:   border-bottom: 1px solid $lg_border_color;
 5734:   line-height: 2.5em;
 5735:   overflow: hidden;
 5736:   margin: 0;
 5737:   padding: 0;
 5738:   text-align: left;
 5739: }
 5740: 
 5741: .LC_head_subbox, .LC_actionbox {
 5742:   clear:both;
 5743:   background: #F8F8F8; /* $sidebg; */
 5744:   border: 1px solid $sidebg;
 5745:   margin: 0 0 10px 0;
 5746:   padding: 3px;
 5747:   text-align: left;
 5748: }
 5749: 
 5750: .LC_fontsize_medium {
 5751:   font-size: 85%;
 5752: }
 5753: 
 5754: .LC_fontsize_large {
 5755:   font-size: 120%;
 5756: }
 5757: 
 5758: .LC_menubuttons_inline_text {
 5759:   color: $font;
 5760:   font-size: 90%;
 5761:   padding-left:3px;
 5762: }
 5763: 
 5764: .LC_menubuttons_inline_text img{
 5765:   vertical-align: middle;
 5766: }
 5767: 
 5768: li.LC_menubuttons_inline_text img {
 5769:   cursor:pointer;
 5770:   text-decoration: none;
 5771: }
 5772: 
 5773: .LC_menubuttons_link {
 5774:   text-decoration: none;
 5775: }
 5776: 
 5777: .LC_menubuttons_category {
 5778:   color: $font;
 5779:   background: $pgbg;
 5780:   font-size: larger;
 5781:   font-weight: bold;
 5782: }
 5783: 
 5784: td.LC_menubuttons_text {
 5785:   color: $font;
 5786: }
 5787: 
 5788: .LC_current_location {
 5789:   background: $tabbg;
 5790: }
 5791: 
 5792: table.LC_data_table {
 5793:   border: 1px solid #000000;
 5794:   border-collapse: separate;
 5795:   border-spacing: 1px;
 5796:   background: $pgbg;
 5797: }
 5798: 
 5799: .LC_data_table_dense {
 5800:   font-size: small;
 5801: }
 5802: 
 5803: table.LC_nested_outer {
 5804:   border: 1px solid #000000;
 5805:   border-collapse: collapse;
 5806:   border-spacing: 0;
 5807:   width: 100%;
 5808: }
 5809: 
 5810: table.LC_innerpickbox,
 5811: table.LC_nested {
 5812:   border: none;
 5813:   border-collapse: collapse;
 5814:   border-spacing: 0;
 5815:   width: 100%;
 5816: }
 5817: 
 5818: table.LC_data_table tr th,
 5819: table.LC_calendar tr th,
 5820: table.LC_prior_tries tr th,
 5821: table.LC_innerpickbox tr th {
 5822:   font-weight: bold;
 5823:   background-color: $data_table_head;
 5824:   color:$fontmenu;
 5825:   font-size:90%;
 5826: }
 5827: 
 5828: table.LC_innerpickbox tr th,
 5829: table.LC_innerpickbox tr td {
 5830:   vertical-align: top;
 5831: }
 5832: 
 5833: table.LC_data_table tr.LC_info_row > td {
 5834:   background-color: #CCCCCC;
 5835:   font-weight: bold;
 5836:   text-align: left;
 5837: }
 5838: 
 5839: table.LC_data_table tr.LC_odd_row > td {
 5840:   background-color: $data_table_light;
 5841:   padding: 2px;
 5842:   vertical-align: top;
 5843: }
 5844: 
 5845: table.LC_pick_box tr > td.LC_odd_row {
 5846:   background-color: $data_table_light;
 5847:   vertical-align: top;
 5848: }
 5849: 
 5850: table.LC_data_table tr.LC_even_row > td {
 5851:   background-color: $data_table_dark;
 5852:   padding: 2px;
 5853:   vertical-align: top;
 5854: }
 5855: 
 5856: table.LC_pick_box tr > td.LC_even_row {
 5857:   background-color: $data_table_dark;
 5858:   vertical-align: top;
 5859: }
 5860: 
 5861: table.LC_data_table tr.LC_data_table_highlight td {
 5862:   background-color: $data_table_darker;
 5863: }
 5864: 
 5865: table.LC_data_table tr td.LC_leftcol_header {
 5866:   background-color: $data_table_head;
 5867:   font-weight: bold;
 5868: }
 5869: 
 5870: table.LC_data_table tr.LC_empty_row td,
 5871: table.LC_nested tr.LC_empty_row td {
 5872:   font-weight: bold;
 5873:   font-style: italic;
 5874:   text-align: center;
 5875:   padding: 8px;
 5876: }
 5877: 
 5878: table.LC_data_table tr.LC_empty_row td,
 5879: table.LC_data_table tr.LC_footer_row td {
 5880:   background-color: $sidebg;
 5881: }
 5882: 
 5883: table.LC_nested tr.LC_empty_row td {
 5884:   background-color: #FFFFFF;
 5885: }
 5886: 
 5887: table.LC_caption {
 5888: }
 5889: 
 5890: table.LC_nested tr.LC_empty_row td {
 5891:   padding: 4ex
 5892: }
 5893: 
 5894: table.LC_nested_outer tr th {
 5895:   font-weight: bold;
 5896:   color:$fontmenu;
 5897:   background-color: $data_table_head;
 5898:   font-size: small;
 5899:   border-bottom: 1px solid #000000;
 5900: }
 5901: 
 5902: table.LC_nested_outer tr td.LC_subheader {
 5903:   background-color: $data_table_head;
 5904:   font-weight: bold;
 5905:   font-size: small;
 5906:   border-bottom: 1px solid #000000;
 5907:   text-align: right;
 5908: }
 5909: 
 5910: table.LC_nested tr.LC_info_row td {
 5911:   background-color: #CCCCCC;
 5912:   font-weight: bold;
 5913:   font-size: small;
 5914:   text-align: center;
 5915: }
 5916: 
 5917: table.LC_nested tr.LC_info_row td.LC_left_item,
 5918: table.LC_nested_outer tr th.LC_left_item {
 5919:   text-align: left;
 5920: }
 5921: 
 5922: table.LC_nested td {
 5923:   background-color: #FFFFFF;
 5924:   font-size: small;
 5925: }
 5926: 
 5927: table.LC_nested_outer tr th.LC_right_item,
 5928: table.LC_nested tr.LC_info_row td.LC_right_item,
 5929: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5930: table.LC_nested tr td.LC_right_item {
 5931:   text-align: right;
 5932: }
 5933: 
 5934: table.LC_nested tr.LC_odd_row td {
 5935:   background-color: #EEEEEE;
 5936: }
 5937: 
 5938: table.LC_createuser {
 5939: }
 5940: 
 5941: table.LC_createuser tr.LC_section_row td {
 5942:   font-size: small;
 5943: }
 5944: 
 5945: table.LC_createuser tr.LC_info_row td  {
 5946:   background-color: #CCCCCC;
 5947:   font-weight: bold;
 5948:   text-align: center;
 5949: }
 5950: 
 5951: table.LC_calendar {
 5952:   border: 1px solid #000000;
 5953:   border-collapse: collapse;
 5954:   width: 98%;
 5955: }
 5956: 
 5957: table.LC_calendar_pickdate {
 5958:   font-size: xx-small;
 5959: }
 5960: 
 5961: table.LC_calendar tr td {
 5962:   border: 1px solid #000000;
 5963:   vertical-align: top;
 5964:   width: 14%;
 5965: }
 5966: 
 5967: table.LC_calendar tr td.LC_calendar_day_empty {
 5968:   background-color: $data_table_dark;
 5969: }
 5970: 
 5971: table.LC_calendar tr td.LC_calendar_day_current {
 5972:   background-color: $data_table_highlight;
 5973: }
 5974: 
 5975: table.LC_data_table tr td.LC_mail_new {
 5976:   background-color: $mail_new;
 5977: }
 5978: 
 5979: table.LC_data_table tr.LC_mail_new:hover {
 5980:   background-color: $mail_new_hover;
 5981: }
 5982: 
 5983: table.LC_data_table tr td.LC_mail_read {
 5984:   background-color: $mail_read;
 5985: }
 5986: 
 5987: /*
 5988: table.LC_data_table tr.LC_mail_read:hover {
 5989:   background-color: $mail_read_hover;
 5990: }
 5991: */
 5992: 
 5993: table.LC_data_table tr td.LC_mail_replied {
 5994:   background-color: $mail_replied;
 5995: }
 5996: 
 5997: /*
 5998: table.LC_data_table tr.LC_mail_replied:hover {
 5999:   background-color: $mail_replied_hover;
 6000: }
 6001: */
 6002: 
 6003: table.LC_data_table tr td.LC_mail_other {
 6004:   background-color: $mail_other;
 6005: }
 6006: 
 6007: /*
 6008: table.LC_data_table tr.LC_mail_other:hover {
 6009:   background-color: $mail_other_hover;
 6010: }
 6011: */
 6012: 
 6013: table.LC_data_table tr > td.LC_browser_file,
 6014: table.LC_data_table tr > td.LC_browser_file_published {
 6015:   background: #AAEE77;
 6016: }
 6017: 
 6018: table.LC_data_table tr > td.LC_browser_file_locked,
 6019: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6020:   background: #FFAA99;
 6021: }
 6022: 
 6023: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6024:   background: #888888;
 6025: }
 6026: 
 6027: table.LC_data_table tr > td.LC_browser_file_modified,
 6028: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6029:   background: #F8F866;
 6030: }
 6031: 
 6032: table.LC_data_table tr.LC_browser_folder > td {
 6033:   background: #E0E8FF;
 6034: }
 6035: 
 6036: table.LC_data_table tr > td.LC_roles_is {
 6037:   /* background: #77FF77; */
 6038: }
 6039: 
 6040: table.LC_data_table tr > td.LC_roles_future {
 6041:   border-right: 8px solid #FFFF77;
 6042: }
 6043: 
 6044: table.LC_data_table tr > td.LC_roles_will {
 6045:   border-right: 8px solid #FFAA77;
 6046: }
 6047: 
 6048: table.LC_data_table tr > td.LC_roles_expired {
 6049:   border-right: 8px solid #FF7777;
 6050: }
 6051: 
 6052: table.LC_data_table tr > td.LC_roles_will_not {
 6053:   border-right: 8px solid #AAFF77;
 6054: }
 6055: 
 6056: table.LC_data_table tr > td.LC_roles_selected {
 6057:   border-right: 8px solid #11CC55;
 6058: }
 6059: 
 6060: span.LC_current_location {
 6061:   font-size:larger;
 6062:   background: $pgbg;
 6063: }
 6064: 
 6065: span.LC_current_nav_location {
 6066:   font-weight:bold;
 6067:   background: $sidebg;
 6068: }
 6069: 
 6070: span.LC_parm_menu_item {
 6071:   font-size: larger;
 6072: }
 6073: 
 6074: span.LC_parm_scope_all {
 6075:   color: red;
 6076: }
 6077: 
 6078: span.LC_parm_scope_folder {
 6079:   color: green;
 6080: }
 6081: 
 6082: span.LC_parm_scope_resource {
 6083:   color: orange;
 6084: }
 6085: 
 6086: span.LC_parm_part {
 6087:   color: blue;
 6088: }
 6089: 
 6090: span.LC_parm_folder,
 6091: span.LC_parm_symb {
 6092:   font-size: x-small;
 6093:   font-family: $mono;
 6094:   color: #AAAAAA;
 6095: }
 6096: 
 6097: ul.LC_parm_parmlist li {
 6098:   display: inline-block;
 6099:   padding: 0.3em 0.8em;
 6100:   vertical-align: top;
 6101:   width: 150px;
 6102:   border-top:1px solid $lg_border_color;
 6103: }
 6104: 
 6105: td.LC_parm_overview_level_menu,
 6106: td.LC_parm_overview_map_menu,
 6107: td.LC_parm_overview_parm_selectors,
 6108: td.LC_parm_overview_restrictions  {
 6109:   border: 1px solid black;
 6110:   border-collapse: collapse;
 6111: }
 6112: 
 6113: table.LC_parm_overview_restrictions td {
 6114:   border-width: 1px 4px 1px 4px;
 6115:   border-style: solid;
 6116:   border-color: $pgbg;
 6117:   text-align: center;
 6118: }
 6119: 
 6120: table.LC_parm_overview_restrictions th {
 6121:   background: $tabbg;
 6122:   border-width: 1px 4px 1px 4px;
 6123:   border-style: solid;
 6124:   border-color: $pgbg;
 6125: }
 6126: 
 6127: table#LC_helpmenu {
 6128:   border: none;
 6129:   height: 55px;
 6130:   border-spacing: 0;
 6131: }
 6132: 
 6133: table#LC_helpmenu fieldset legend {
 6134:   font-size: larger;
 6135: }
 6136: 
 6137: table#LC_helpmenu_links {
 6138:   width: 100%;
 6139:   border: 1px solid black;
 6140:   background: $pgbg;
 6141:   padding: 0;
 6142:   border-spacing: 1px;
 6143: }
 6144: 
 6145: table#LC_helpmenu_links tr td {
 6146:   padding: 1px;
 6147:   background: $tabbg;
 6148:   text-align: center;
 6149:   font-weight: bold;
 6150: }
 6151: 
 6152: table#LC_helpmenu_links a:link,
 6153: table#LC_helpmenu_links a:visited,
 6154: table#LC_helpmenu_links a:active {
 6155:   text-decoration: none;
 6156:   color: $font;
 6157: }
 6158: 
 6159: table#LC_helpmenu_links a:hover {
 6160:   text-decoration: underline;
 6161:   color: $vlink;
 6162: }
 6163: 
 6164: .LC_chrt_popup_exists {
 6165:   border: 1px solid #339933;
 6166:   margin: -1px;
 6167: }
 6168: 
 6169: .LC_chrt_popup_up {
 6170:   border: 1px solid yellow;
 6171:   margin: -1px;
 6172: }
 6173: 
 6174: .LC_chrt_popup {
 6175:   border: 1px solid #8888FF;
 6176:   background: #CCCCFF;
 6177: }
 6178: 
 6179: table.LC_pick_box {
 6180:   border-collapse: separate;
 6181:   background: white;
 6182:   border: 1px solid black;
 6183:   border-spacing: 1px;
 6184: }
 6185: 
 6186: table.LC_pick_box td.LC_pick_box_title {
 6187:   background: $sidebg;
 6188:   font-weight: bold;
 6189:   text-align: left;
 6190:   vertical-align: top;
 6191:   width: 184px;
 6192:   padding: 8px;
 6193: }
 6194: 
 6195: table.LC_pick_box td.LC_pick_box_value {
 6196:   text-align: left;
 6197:   padding: 8px;
 6198: }
 6199: 
 6200: table.LC_pick_box td.LC_pick_box_select {
 6201:   text-align: left;
 6202:   padding: 8px;
 6203: }
 6204: 
 6205: table.LC_pick_box td.LC_pick_box_separator {
 6206:   padding: 0;
 6207:   height: 1px;
 6208:   background: black;
 6209: }
 6210: 
 6211: table.LC_pick_box td.LC_pick_box_submit {
 6212:   text-align: right;
 6213: }
 6214: 
 6215: table.LC_pick_box td.LC_evenrow_value {
 6216:   text-align: left;
 6217:   padding: 8px;
 6218:   background-color: $data_table_light;
 6219: }
 6220: 
 6221: table.LC_pick_box td.LC_oddrow_value {
 6222:   text-align: left;
 6223:   padding: 8px;
 6224:   background-color: $data_table_light;
 6225: }
 6226: 
 6227: span.LC_helpform_receipt_cat {
 6228:   font-weight: bold;
 6229: }
 6230: 
 6231: table.LC_group_priv_box {
 6232:   background: white;
 6233:   border: 1px solid black;
 6234:   border-spacing: 1px;
 6235: }
 6236: 
 6237: table.LC_group_priv_box td.LC_pick_box_title {
 6238:   background: $tabbg;
 6239:   font-weight: bold;
 6240:   text-align: right;
 6241:   width: 184px;
 6242: }
 6243: 
 6244: table.LC_group_priv_box td.LC_groups_fixed {
 6245:   background: $data_table_light;
 6246:   text-align: center;
 6247: }
 6248: 
 6249: table.LC_group_priv_box td.LC_groups_optional {
 6250:   background: $data_table_dark;
 6251:   text-align: center;
 6252: }
 6253: 
 6254: table.LC_group_priv_box td.LC_groups_functionality {
 6255:   background: $data_table_darker;
 6256:   text-align: center;
 6257:   font-weight: bold;
 6258: }
 6259: 
 6260: table.LC_group_priv td {
 6261:   text-align: left;
 6262:   padding: 0;
 6263: }
 6264: 
 6265: .LC_navbuttons {
 6266:   margin: 2ex 0ex 2ex 0ex;
 6267: }
 6268: 
 6269: .LC_topic_bar {
 6270:   font-weight: bold;
 6271:   background: $tabbg;
 6272:   margin: 1em 0em 1em 2em;
 6273:   padding: 3px;
 6274:   font-size: 1.2em;
 6275: }
 6276: 
 6277: .LC_topic_bar span {
 6278:   left: 0.5em;
 6279:   position: absolute;
 6280:   vertical-align: middle;
 6281:   font-size: 1.2em;
 6282: }
 6283: 
 6284: table.LC_course_group_status {
 6285:   margin: 20px;
 6286: }
 6287: 
 6288: table.LC_status_selector td {
 6289:   vertical-align: top;
 6290:   text-align: center;
 6291:   padding: 4px;
 6292: }
 6293: 
 6294: div.LC_feedback_link {
 6295:   clear: both;
 6296:   background: $sidebg;
 6297:   width: 100%;
 6298:   padding-bottom: 10px;
 6299:   border: 1px $tabbg solid;
 6300:   height: 22px;
 6301:   line-height: 22px;
 6302:   padding-top: 5px;
 6303: }
 6304: 
 6305: div.LC_feedback_link img {
 6306:   height: 22px;
 6307:   vertical-align:middle;
 6308: }
 6309: 
 6310: div.LC_feedback_link a {
 6311:   text-decoration: none;
 6312: }
 6313: 
 6314: div.LC_comblock {
 6315:   display:inline;
 6316:   color:$font;
 6317:   font-size:90%;
 6318: }
 6319: 
 6320: div.LC_feedback_link div.LC_comblock {
 6321:   padding-left:5px;
 6322: }
 6323: 
 6324: div.LC_feedback_link div.LC_comblock a {
 6325:   color:$font;
 6326: }
 6327: 
 6328: span.LC_feedback_link {
 6329:   /* background: $feedback_link_bg; */
 6330:   font-size: larger;
 6331: }
 6332: 
 6333: span.LC_message_link {
 6334:   /* background: $feedback_link_bg; */
 6335:   font-size: larger;
 6336:   position: absolute;
 6337:   right: 1em;
 6338: }
 6339: 
 6340: table.LC_prior_tries {
 6341:   border: 1px solid #000000;
 6342:   border-collapse: separate;
 6343:   border-spacing: 1px;
 6344: }
 6345: 
 6346: table.LC_prior_tries td {
 6347:   padding: 2px;
 6348: }
 6349: 
 6350: .LC_answer_correct {
 6351:   background: lightgreen;
 6352:   color: darkgreen;
 6353:   padding: 6px;
 6354: }
 6355: 
 6356: .LC_answer_charged_try {
 6357:   background: #FFAAAA;
 6358:   color: darkred;
 6359:   padding: 6px;
 6360: }
 6361: 
 6362: .LC_answer_not_charged_try,
 6363: .LC_answer_no_grade,
 6364: .LC_answer_late {
 6365:   background: lightyellow;
 6366:   color: black;
 6367:   padding: 6px;
 6368: }
 6369: 
 6370: .LC_answer_previous {
 6371:   background: lightblue;
 6372:   color: darkblue;
 6373:   padding: 6px;
 6374: }
 6375: 
 6376: .LC_answer_no_message {
 6377:   background: #FFFFFF;
 6378:   color: black;
 6379:   padding: 6px;
 6380: }
 6381: 
 6382: .LC_answer_unknown {
 6383:   background: orange;
 6384:   color: black;
 6385:   padding: 6px;
 6386: }
 6387: 
 6388: span.LC_prior_numerical,
 6389: span.LC_prior_string,
 6390: span.LC_prior_custom,
 6391: span.LC_prior_reaction,
 6392: span.LC_prior_math {
 6393:   font-family: $mono;
 6394:   white-space: pre;
 6395: }
 6396: 
 6397: span.LC_prior_string {
 6398:   font-family: $mono;
 6399:   white-space: pre;
 6400: }
 6401: 
 6402: table.LC_prior_option {
 6403:   width: 100%;
 6404:   border-collapse: collapse;
 6405: }
 6406: 
 6407: table.LC_prior_rank,
 6408: table.LC_prior_match {
 6409:   border-collapse: collapse;
 6410: }
 6411: 
 6412: table.LC_prior_option tr td,
 6413: table.LC_prior_rank tr td,
 6414: table.LC_prior_match tr td {
 6415:   border: 1px solid #000000;
 6416: }
 6417: 
 6418: .LC_nobreak {
 6419:   white-space: nowrap;
 6420: }
 6421: 
 6422: span.LC_cusr_emph {
 6423:   font-style: italic;
 6424: }
 6425: 
 6426: span.LC_cusr_subheading {
 6427:   font-weight: normal;
 6428:   font-size: 85%;
 6429: }
 6430: 
 6431: div.LC_docs_entry_move {
 6432:   border: 1px solid #BBBBBB;
 6433:   background: #DDDDDD;
 6434:   width: 22px;
 6435:   padding: 1px;
 6436:   margin: 0;
 6437: }
 6438: 
 6439: table.LC_data_table tr > td.LC_docs_entry_commands,
 6440: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6441:   font-size: x-small;
 6442: }
 6443: 
 6444: .LC_docs_entry_parameter {
 6445:   white-space: nowrap;
 6446: }
 6447: 
 6448: .LC_docs_copy {
 6449:   color: #000099;
 6450: }
 6451: 
 6452: .LC_docs_cut {
 6453:   color: #550044;
 6454: }
 6455: 
 6456: .LC_docs_rename {
 6457:   color: #009900;
 6458: }
 6459: 
 6460: .LC_docs_remove {
 6461:   color: #990000;
 6462: }
 6463: 
 6464: .LC_docs_reinit_warn,
 6465: .LC_docs_ext_edit {
 6466:   font-size: x-small;
 6467: }
 6468: 
 6469: table.LC_docs_adddocs td,
 6470: table.LC_docs_adddocs th {
 6471:   border: 1px solid #BBBBBB;
 6472:   padding: 4px;
 6473:   background: #DDDDDD;
 6474: }
 6475: 
 6476: table.LC_sty_begin {
 6477:   background: #BBFFBB;
 6478: }
 6479: 
 6480: table.LC_sty_end {
 6481:   background: #FFBBBB;
 6482: }
 6483: 
 6484: table.LC_double_column {
 6485:   border-width: 0;
 6486:   border-collapse: collapse;
 6487:   width: 100%;
 6488:   padding: 2px;
 6489: }
 6490: 
 6491: table.LC_double_column tr td.LC_left_col {
 6492:   top: 2px;
 6493:   left: 2px;
 6494:   width: 47%;
 6495:   vertical-align: top;
 6496: }
 6497: 
 6498: table.LC_double_column tr td.LC_right_col {
 6499:   top: 2px;
 6500:   right: 2px;
 6501:   width: 47%;
 6502:   vertical-align: top;
 6503: }
 6504: 
 6505: div.LC_left_float {
 6506:   float: left;
 6507:   padding-right: 5%;
 6508:   padding-bottom: 4px;
 6509: }
 6510: 
 6511: div.LC_clear_float_header {
 6512:   padding-bottom: 2px;
 6513: }
 6514: 
 6515: div.LC_clear_float_footer {
 6516:   padding-top: 10px;
 6517:   clear: both;
 6518: }
 6519: 
 6520: div.LC_grade_show_user {
 6521: /*  border-left: 5px solid $sidebg; */
 6522:   border-top: 5px solid #000000;
 6523:   margin: 50px 0 0 0;
 6524:   padding: 15px 0 5px 10px;
 6525: }
 6526: 
 6527: div.LC_grade_show_user_odd_row {
 6528: /*  border-left: 5px solid #000000; */
 6529: }
 6530: 
 6531: div.LC_grade_show_user div.LC_Box {
 6532:   margin-right: 50px;
 6533: }
 6534: 
 6535: div.LC_grade_submissions,
 6536: div.LC_grade_message_center,
 6537: div.LC_grade_info_links {
 6538:   margin: 5px;
 6539:   width: 99%;
 6540:   background: #FFFFFF;
 6541: }
 6542: 
 6543: div.LC_grade_submissions_header,
 6544: div.LC_grade_message_center_header {
 6545:   font-weight: bold;
 6546:   font-size: large;
 6547: }
 6548: 
 6549: div.LC_grade_submissions_body,
 6550: div.LC_grade_message_center_body {
 6551:   border: 1px solid black;
 6552:   width: 99%;
 6553:   background: #FFFFFF;
 6554: }
 6555: 
 6556: table.LC_scantron_action {
 6557:   width: 100%;
 6558: }
 6559: 
 6560: table.LC_scantron_action tr th {
 6561:   font-weight:bold;
 6562:   font-style:normal;
 6563: }
 6564: 
 6565: .LC_edit_problem_header,
 6566: div.LC_edit_problem_footer {
 6567:   font-weight: normal;
 6568:   font-size:  medium;
 6569:   margin: 2px;
 6570:   background-color: $sidebg;
 6571: }
 6572: 
 6573: div.LC_edit_problem_header,
 6574: div.LC_edit_problem_header div,
 6575: div.LC_edit_problem_footer,
 6576: div.LC_edit_problem_footer div,
 6577: div.LC_edit_problem_editxml_header,
 6578: div.LC_edit_problem_editxml_header div {
 6579:   margin-top: 5px;
 6580: }
 6581: 
 6582: div.LC_edit_problem_header_title {
 6583:   font-weight: bold;
 6584:   font-size: larger;
 6585:   background: $tabbg;
 6586:   padding: 3px;
 6587:   margin: 0 0 5px 0;
 6588: }
 6589: 
 6590: table.LC_edit_problem_header_title {
 6591:   width: 100%;
 6592:   background: $tabbg;
 6593: }
 6594: 
 6595: div.LC_edit_problem_discards {
 6596:   float: left;
 6597:   padding-bottom: 5px;
 6598: }
 6599: 
 6600: div.LC_edit_problem_saves {
 6601:   float: right;
 6602:   padding-bottom: 5px;
 6603: }
 6604: 
 6605: .LC_edit_opt {
 6606:   padding-left: 1em;
 6607:   white-space: nowrap;
 6608: }
 6609: 
 6610: .LC_edit_problem_latexhelper{
 6611:     text-align: right;
 6612: }
 6613: 
 6614: #LC_edit_problem_colorful div{
 6615:     margin-left: 40px;
 6616: }
 6617: 
 6618: img.stift {
 6619:   border-width: 0;
 6620:   vertical-align: middle;
 6621: }
 6622: 
 6623: table td.LC_mainmenu_col_fieldset {
 6624:   vertical-align: top;
 6625: }
 6626: 
 6627: div.LC_createcourse {
 6628:   margin: 10px 10px 10px 10px;
 6629: }
 6630: 
 6631: .LC_dccid {
 6632:   float: right;
 6633:   margin: 0.2em 0 0 0;
 6634:   padding: 0;
 6635:   font-size: 90%;
 6636:   display:none;
 6637: }
 6638: 
 6639: ol.LC_primary_menu a:hover,
 6640: ol#LC_MenuBreadcrumbs a:hover,
 6641: ol#LC_PathBreadcrumbs a:hover,
 6642: ul#LC_secondary_menu a:hover,
 6643: .LC_FormSectionClearButton input:hover
 6644: ul.LC_TabContent   li:hover a {
 6645:   color:$button_hover;
 6646:   text-decoration:none;
 6647: }
 6648: 
 6649: h1 {
 6650:   padding: 0;
 6651:   line-height:130%;
 6652: }
 6653: 
 6654: h2,
 6655: h3,
 6656: h4,
 6657: h5,
 6658: h6 {
 6659:   margin: 5px 0 5px 0;
 6660:   padding: 0;
 6661:   line-height:130%;
 6662: }
 6663: 
 6664: .LC_hcell {
 6665:   padding:3px 15px 3px 15px;
 6666:   margin: 0;
 6667:   background-color:$tabbg;
 6668:   color:$fontmenu;
 6669:   border-bottom:solid 1px $lg_border_color;
 6670: }
 6671: 
 6672: .LC_Box > .LC_hcell {
 6673:   margin: 0 -10px 10px -10px;
 6674: }
 6675: 
 6676: .LC_noBorder {
 6677:   border: 0;
 6678: }
 6679: 
 6680: .LC_FormSectionClearButton input {
 6681:   background-color:transparent;
 6682:   border: none;
 6683:   cursor:pointer;
 6684:   text-decoration:underline;
 6685: }
 6686: 
 6687: .LC_help_open_topic {
 6688:   color: #FFFFFF;
 6689:   background-color: #EEEEFF;
 6690:   margin: 1px;
 6691:   padding: 4px;
 6692:   border: 1px solid #000033;
 6693:   white-space: nowrap;
 6694:   /* vertical-align: middle; */
 6695: }
 6696: 
 6697: dl,
 6698: ul,
 6699: div,
 6700: fieldset {
 6701:   margin: 10px 10px 10px 0;
 6702:   /* overflow: hidden; */
 6703: }
 6704: 
 6705: article.geogebraweb div {
 6706:     margin: 0;
 6707: }
 6708: 
 6709: fieldset > legend {
 6710:   font-weight: bold;
 6711:   padding: 0 5px 0 5px;
 6712: }
 6713: 
 6714: #LC_nav_bar {
 6715:   float: left;
 6716:   background-color: $pgbg_or_bgcolor;
 6717:   margin: 0 0 2px 0;
 6718: }
 6719: 
 6720: #LC_realm {
 6721:   margin: 0.2em 0 0 0;
 6722:   padding: 0;
 6723:   font-weight: bold;
 6724:   text-align: center;
 6725:   background-color: $pgbg_or_bgcolor;
 6726: }
 6727: 
 6728: #LC_nav_bar em {
 6729:   font-weight: bold;
 6730:   font-style: normal;
 6731: }
 6732: 
 6733: ol.LC_primary_menu {
 6734:   margin: 0;
 6735:   padding: 0;
 6736:   background-color: $pgbg_or_bgcolor;
 6737: }
 6738: 
 6739: ol#LC_PathBreadcrumbs {
 6740:   margin: 0;
 6741: }
 6742: 
 6743: ol.LC_primary_menu li {
 6744:   color: RGB(80, 80, 80);
 6745:   vertical-align: middle;
 6746:   text-align: left;
 6747:   list-style: none;
 6748:   float: left;
 6749: }
 6750: 
 6751: ol.LC_primary_menu li a {
 6752:   display: block;
 6753:   margin: 0;
 6754:   padding: 0 5px 0 10px;
 6755:   text-decoration: none;
 6756: }
 6757: 
 6758: ol.LC_primary_menu li ul {
 6759:   display: none;
 6760:   width: 10em;
 6761:   background-color: $data_table_light;
 6762: }
 6763: 
 6764: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6765:   display: block;
 6766:   position: absolute;
 6767:   margin: 0;
 6768:   padding: 0;
 6769:   z-index: 2;
 6770: }
 6771: 
 6772: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6773:   font-size: 90%;
 6774:   vertical-align: top;
 6775:   float: none;
 6776:   border-left: 1px solid black;
 6777:   border-right: 1px solid black;
 6778: }
 6779: 
 6780: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6781:   background-color:$data_table_light;
 6782: }
 6783: 
 6784: ol.LC_primary_menu li li a:hover {
 6785:    color:$button_hover;
 6786:    background-color:$data_table_dark;
 6787: }
 6788: 
 6789: ol.LC_primary_menu li img {
 6790:   vertical-align: bottom;
 6791:   height: 1.1em;
 6792:   margin: 0.2em 0 0 0;
 6793: }
 6794: 
 6795: ol.LC_primary_menu a {
 6796:   color: RGB(80, 80, 80);
 6797:   text-decoration: none;
 6798: }
 6799: 
 6800: ol.LC_primary_menu a.LC_new_message {
 6801:   font-weight:bold;
 6802:   color: darkred;
 6803: }
 6804: 
 6805: ol.LC_docs_parameters {
 6806:   margin-left: 0;
 6807:   padding: 0;
 6808:   list-style: none;
 6809: }
 6810: 
 6811: ol.LC_docs_parameters li {
 6812:   margin: 0;
 6813:   padding-right: 20px;
 6814:   display: inline;
 6815: }
 6816: 
 6817: ol.LC_docs_parameters li:before {
 6818:   content: "\\002022 \\0020";
 6819: }
 6820: 
 6821: li.LC_docs_parameters_title {
 6822:   font-weight: bold;
 6823: }
 6824: 
 6825: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6826:   content: "";
 6827: }
 6828: 
 6829: ul#LC_secondary_menu {
 6830:   clear: right;
 6831:   color: $fontmenu;
 6832:   background: $tabbg;
 6833:   list-style: none;
 6834:   padding: 0;
 6835:   margin: 0;
 6836:   width: 100%;
 6837:   text-align: left;
 6838:   float: left;
 6839: }
 6840: 
 6841: ul#LC_secondary_menu li {
 6842:   font-weight: bold;
 6843:   line-height: 1.8em;
 6844:   border-right: 1px solid black;
 6845:   vertical-align: middle;
 6846:   float: left;
 6847: }
 6848: 
 6849: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6850:   background-color: $data_table_light;
 6851: }
 6852: 
 6853: ul#LC_secondary_menu li a {
 6854:   padding: 0 0.8em;
 6855: }
 6856: 
 6857: ul#LC_secondary_menu li ul {
 6858:   display: none;
 6859: }
 6860: 
 6861: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6862:   display: block;
 6863:   position: absolute;
 6864:   margin: 0;
 6865:   padding: 0;
 6866:   list-style:none;
 6867:   float: none;
 6868:   background-color: $data_table_light;
 6869:   z-index: 2;
 6870:   margin-left: -1px;
 6871: }
 6872: 
 6873: ul#LC_secondary_menu li ul li {
 6874:   font-size: 90%;
 6875:   vertical-align: top;
 6876:   border-left: 1px solid black;
 6877:   border-right: 1px solid black;
 6878:   background-color: $data_table_light;
 6879:   list-style:none;
 6880:   float: none;
 6881: }
 6882: 
 6883: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6884:   background-color: $data_table_dark;
 6885: }
 6886: 
 6887: ul.LC_TabContent {
 6888:   display:block;
 6889:   background: $sidebg;
 6890:   border-bottom: solid 1px $lg_border_color;
 6891:   list-style:none;
 6892:   margin: -1px -10px 0 -10px;
 6893:   padding: 0;
 6894: }
 6895: 
 6896: ul.LC_TabContent li,
 6897: ul.LC_TabContentBigger li {
 6898:   float:left;
 6899: }
 6900: 
 6901: ul#LC_secondary_menu li a {
 6902:   color: $fontmenu;
 6903:   text-decoration: none;
 6904: }
 6905: 
 6906: ul.LC_TabContent {
 6907:   min-height:20px;
 6908: }
 6909: 
 6910: ul.LC_TabContent li {
 6911:   vertical-align:middle;
 6912:   padding: 0 16px 0 10px;
 6913:   background-color:$tabbg;
 6914:   border-bottom:solid 1px $lg_border_color;
 6915:   border-left: solid 1px $font;
 6916: }
 6917: 
 6918: ul.LC_TabContent .right {
 6919:   float:right;
 6920: }
 6921: 
 6922: ul.LC_TabContent li a,
 6923: ul.LC_TabContent li {
 6924:   color:rgb(47,47,47);
 6925:   text-decoration:none;
 6926:   font-size:95%;
 6927:   font-weight:bold;
 6928:   min-height:20px;
 6929: }
 6930: 
 6931: ul.LC_TabContent li a:hover,
 6932: ul.LC_TabContent li a:focus {
 6933:   color: $button_hover;
 6934:   background:none;
 6935:   outline:none;
 6936: }
 6937: 
 6938: ul.LC_TabContent li:hover {
 6939:   color: $button_hover;
 6940:   cursor:pointer;
 6941: }
 6942: 
 6943: ul.LC_TabContent li.active {
 6944:   color: $font;
 6945:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6946:   border-bottom:solid 1px #FFFFFF;
 6947:   cursor: default;
 6948: }
 6949: 
 6950: ul.LC_TabContent li.active a {
 6951:   color:$font;
 6952:   background:#FFFFFF;
 6953:   outline: none;
 6954: }
 6955: 
 6956: ul.LC_TabContent li.goback {
 6957:   float: left;
 6958:   border-left: none;
 6959: }
 6960: 
 6961: #maincoursedoc {
 6962:   clear:both;
 6963: }
 6964: 
 6965: ul.LC_TabContentBigger {
 6966:   display:block;
 6967:   list-style:none;
 6968:   padding: 0;
 6969: }
 6970: 
 6971: ul.LC_TabContentBigger li {
 6972:   vertical-align:bottom;
 6973:   height: 30px;
 6974:   font-size:110%;
 6975:   font-weight:bold;
 6976:   color: #737373;
 6977: }
 6978: 
 6979: ul.LC_TabContentBigger li.active {
 6980:   position: relative;
 6981:   top: 1px;
 6982: }
 6983: 
 6984: ul.LC_TabContentBigger li a {
 6985:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6986:   height: 30px;
 6987:   line-height: 30px;
 6988:   text-align: center;
 6989:   display: block;
 6990:   text-decoration: none;
 6991:   outline: none;  
 6992: }
 6993: 
 6994: ul.LC_TabContentBigger li.active a {
 6995:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6996:   color:$font;
 6997: }
 6998: 
 6999: ul.LC_TabContentBigger li b {
 7000:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7001:   display: block;
 7002:   float: left;
 7003:   padding: 0 30px;
 7004:   border-bottom: 1px solid $lg_border_color;
 7005: }
 7006: 
 7007: ul.LC_TabContentBigger li:hover b {
 7008:   color:$button_hover;
 7009: }
 7010: 
 7011: ul.LC_TabContentBigger li.active b {
 7012:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7013:   color:$font;
 7014:   border: 0;
 7015: }
 7016: 
 7017: 
 7018: ul.LC_CourseBreadcrumbs {
 7019:   background: $sidebg;
 7020:   height: 2em;
 7021:   padding-left: 10px;
 7022:   margin: 0;
 7023:   list-style-position: inside;
 7024: }
 7025: 
 7026: ol#LC_MenuBreadcrumbs,
 7027: ol#LC_PathBreadcrumbs {
 7028:   padding-left: 10px;
 7029:   margin: 0;
 7030:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7031: }
 7032: 
 7033: ol#LC_MenuBreadcrumbs li,
 7034: ol#LC_PathBreadcrumbs li,
 7035: ul.LC_CourseBreadcrumbs li {
 7036:   display: inline;
 7037:   white-space: normal;  
 7038: }
 7039: 
 7040: ol#LC_MenuBreadcrumbs li a,
 7041: ul.LC_CourseBreadcrumbs li a {
 7042:   text-decoration: none;
 7043:   font-size:90%;
 7044: }
 7045: 
 7046: ol#LC_MenuBreadcrumbs h1 {
 7047:   display: inline;
 7048:   font-size: 90%;
 7049:   line-height: 2.5em;
 7050:   margin: 0;
 7051:   padding: 0;
 7052: }
 7053: 
 7054: ol#LC_PathBreadcrumbs li a {
 7055:   text-decoration:none;
 7056:   font-size:100%;
 7057:   font-weight:bold;
 7058: }
 7059: 
 7060: .LC_Box {
 7061:   border: solid 1px $lg_border_color;
 7062:   padding: 0 10px 10px 10px;
 7063: }
 7064: 
 7065: .LC_DocsBox {
 7066:   border: solid 1px $lg_border_color;
 7067:   padding: 0 0 10px 10px;
 7068: }
 7069: 
 7070: .LC_AboutMe_Image {
 7071:   float:left;
 7072:   margin-right:10px;
 7073: }
 7074: 
 7075: .LC_Clear_AboutMe_Image {
 7076:   clear:left;
 7077: }
 7078: 
 7079: dl.LC_ListStyleClean dt {
 7080:   padding-right: 5px;
 7081:   display: table-header-group;
 7082: }
 7083: 
 7084: dl.LC_ListStyleClean dd {
 7085:   display: table-row;
 7086: }
 7087: 
 7088: .LC_ListStyleClean,
 7089: .LC_ListStyleSimple,
 7090: .LC_ListStyleNormal,
 7091: .LC_ListStyleSpecial {
 7092:   /* display:block; */
 7093:   list-style-position: inside;
 7094:   list-style-type: none;
 7095:   overflow: hidden;
 7096:   padding: 0;
 7097: }
 7098: 
 7099: .LC_ListStyleSimple li,
 7100: .LC_ListStyleSimple dd,
 7101: .LC_ListStyleNormal li,
 7102: .LC_ListStyleNormal dd,
 7103: .LC_ListStyleSpecial li,
 7104: .LC_ListStyleSpecial dd {
 7105:   margin: 0;
 7106:   padding: 5px 5px 5px 10px;
 7107:   clear: both;
 7108: }
 7109: 
 7110: .LC_ListStyleClean li,
 7111: .LC_ListStyleClean dd {
 7112:   padding-top: 0;
 7113:   padding-bottom: 0;
 7114: }
 7115: 
 7116: .LC_ListStyleSimple dd,
 7117: .LC_ListStyleSimple li {
 7118:   border-bottom: solid 1px $lg_border_color;
 7119: }
 7120: 
 7121: .LC_ListStyleSpecial li,
 7122: .LC_ListStyleSpecial dd {
 7123:   list-style-type: none;
 7124:   background-color: RGB(220, 220, 220);
 7125:   margin-bottom: 4px;
 7126: }
 7127: 
 7128: table.LC_SimpleTable {
 7129:   margin:5px;
 7130:   border:solid 1px $lg_border_color;
 7131: }
 7132: 
 7133: table.LC_SimpleTable tr {
 7134:   padding: 0;
 7135:   border:solid 1px $lg_border_color;
 7136: }
 7137: 
 7138: table.LC_SimpleTable thead {
 7139:   background:rgb(220,220,220);
 7140: }
 7141: 
 7142: div.LC_columnSection {
 7143:   display: block;
 7144:   clear: both;
 7145:   overflow: hidden;
 7146:   margin: 0;
 7147: }
 7148: 
 7149: div.LC_columnSection>* {
 7150:   float: left;
 7151:   margin: 10px 20px 10px 0;
 7152:   overflow:hidden;
 7153: }
 7154: 
 7155: table em {
 7156:   font-weight: bold;
 7157:   font-style: normal;
 7158: }
 7159: 
 7160: table.LC_tableBrowseRes,
 7161: table.LC_tableOfContent {
 7162:   border:none;
 7163:   border-spacing: 1px;
 7164:   padding: 3px;
 7165:   background-color: #FFFFFF;
 7166:   font-size: 90%;
 7167: }
 7168: 
 7169: table.LC_tableOfContent {
 7170:   border-collapse: collapse;
 7171: }
 7172: 
 7173: table.LC_tableBrowseRes a,
 7174: table.LC_tableOfContent a {
 7175:   background-color: transparent;
 7176:   text-decoration: none;
 7177: }
 7178: 
 7179: table.LC_tableOfContent img {
 7180:   border: none;
 7181:   height: 1.3em;
 7182:   vertical-align: text-bottom;
 7183:   margin-right: 0.3em;
 7184: }
 7185: 
 7186: a#LC_content_toolbar_firsthomework {
 7187:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7188: }
 7189: 
 7190: a#LC_content_toolbar_everything {
 7191:   background-image:url(/res/adm/pages/show-all.gif);
 7192: }
 7193: 
 7194: a#LC_content_toolbar_uncompleted {
 7195:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7196: }
 7197: 
 7198: #LC_content_toolbar_clearbubbles {
 7199:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7200: }
 7201: 
 7202: a#LC_content_toolbar_changefolder {
 7203:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7204: }
 7205: 
 7206: a#LC_content_toolbar_changefolder_toggled {
 7207:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7208: }
 7209: 
 7210: a#LC_content_toolbar_edittoplevel {
 7211:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7212: }
 7213: 
 7214: ul#LC_toolbar li a:hover {
 7215:   background-position: bottom center;
 7216: }
 7217: 
 7218: ul#LC_toolbar {
 7219:   padding: 0;
 7220:   margin: 2px;
 7221:   list-style:none;
 7222:   position:relative;
 7223:   background-color:white;
 7224:   overflow: auto;
 7225: }
 7226: 
 7227: ul#LC_toolbar li {
 7228:   border:1px solid white;
 7229:   padding: 0;
 7230:   margin: 0;
 7231:   float: left;
 7232:   display:inline;
 7233:   vertical-align:middle;
 7234:   white-space: nowrap;
 7235: }
 7236: 
 7237: 
 7238: a.LC_toolbarItem {
 7239:   display:block;
 7240:   padding: 0;
 7241:   margin: 0;
 7242:   height: 32px;
 7243:   width: 32px;
 7244:   color:white;
 7245:   border: none;
 7246:   background-repeat:no-repeat;
 7247:   background-color:transparent;
 7248: }
 7249: 
 7250: ul.LC_funclist {
 7251:     margin: 0;
 7252:     padding: 0.5em 1em 0.5em 0;
 7253: }
 7254: 
 7255: ul.LC_funclist > li:first-child {
 7256:     font-weight:bold; 
 7257:     margin-left:0.8em;
 7258: }
 7259: 
 7260: ul.LC_funclist + ul.LC_funclist {
 7261:     /* 
 7262:        left border as a seperator if we have more than
 7263:        one list 
 7264:     */
 7265:     border-left: 1px solid $sidebg;
 7266:     /* 
 7267:        this hides the left border behind the border of the 
 7268:        outer box if element is wrapped to the next 'line' 
 7269:     */
 7270:     margin-left: -1px;
 7271: }
 7272: 
 7273: ul.LC_funclist li {
 7274:   display: inline;
 7275:   white-space: nowrap;
 7276:   margin: 0 0 0 25px;
 7277:   line-height: 150%;
 7278: }
 7279: 
 7280: .LC_hidden {
 7281:   display: none;
 7282: }
 7283: 
 7284: .LCmodal-overlay {
 7285: 		position:fixed;
 7286: 		top:0;
 7287: 		right:0;
 7288: 		bottom:0;
 7289: 		left:0;
 7290: 		height:100%;
 7291: 		width:100%;
 7292: 		margin:0;
 7293: 		padding:0;
 7294: 		background:#999;
 7295: 		opacity:.75;
 7296: 		filter: alpha(opacity=75);
 7297: 		-moz-opacity: 0.75;
 7298: 		z-index:101;
 7299: }
 7300: 
 7301: * html .LCmodal-overlay {   
 7302: 		position: absolute;
 7303: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7304: }
 7305: 
 7306: .LCmodal-window {
 7307: 		position:fixed;
 7308: 		top:50%;
 7309: 		left:50%;
 7310: 		margin:0;
 7311: 		padding:0;
 7312: 		z-index:102;
 7313: 	}
 7314: 
 7315: * html .LCmodal-window {
 7316: 		position:absolute;
 7317: }
 7318: 
 7319: .LCclose-window {
 7320: 		position:absolute;
 7321: 		width:32px;
 7322: 		height:32px;
 7323: 		right:8px;
 7324: 		top:8px;
 7325: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7326: 		text-indent:-99999px;
 7327: 		overflow:hidden;
 7328: 		cursor:pointer;
 7329: }
 7330: 
 7331: /*
 7332:   styles used by TTH when "Default set of options to pass to tth/m
 7333:   when converting TeX" in course settings has been set
 7334: 
 7335:   option passed: -t
 7336: 
 7337: */
 7338: 
 7339: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7340: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7341: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7342: td div.norm {line-height:normal;}
 7343: 
 7344: /*
 7345:   option passed -y3
 7346: */
 7347: 
 7348: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7349: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7350: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7351: 
 7352: END
 7353: }
 7354: 
 7355: =pod
 7356: 
 7357: =item * &headtag()
 7358: 
 7359: Returns a uniform footer for LON-CAPA web pages.
 7360: 
 7361: Inputs: $title - optional title for the head
 7362:         $head_extra - optional extra HTML to put inside the <head>
 7363:         $args - optional arguments
 7364:             force_register - if is true call registerurl so the remote is 
 7365:                              informed
 7366:             redirect       -> array ref of
 7367:                                    1- seconds before redirect occurs
 7368:                                    2- url to redirect to
 7369:                                    3- whether the side effect should occur
 7370:                            (side effect of setting 
 7371:                                $env{'internal.head.redirect'} to the url 
 7372:                                redirected too)
 7373:             domain         -> force to color decorate a page for a specific
 7374:                                domain
 7375:             function       -> force usage of a specific rolish color scheme
 7376:             bgcolor        -> override the default page bgcolor
 7377:             no_auto_mt_title
 7378:                            -> prevent &mt()ing the title arg
 7379: 
 7380: =cut
 7381: 
 7382: sub headtag {
 7383:     my ($title,$head_extra,$args) = @_;
 7384:     
 7385:     my $function = $args->{'function'} || &get_users_function();
 7386:     my $domain   = $args->{'domain'}   || &determinedomain();
 7387:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7388:     my $httphost = $args->{'use_absolute'};
 7389:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7390: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7391: 		   #time(),
 7392: 		   $env{'environment.color.timestamp'},
 7393: 		   $function,$domain,$bgcolor);
 7394: 
 7395:     $url = '/adm/css/'.&escape($url).'.css';
 7396: 
 7397:     my $result =
 7398: 	'<head>'.
 7399: 	&font_settings($args);
 7400: 
 7401:     my $inhibitprint;
 7402:     if ($args->{'print_suppress'}) {
 7403:         $inhibitprint = &print_suppression();
 7404:     }
 7405: 
 7406:     if (!$args->{'frameset'}) {
 7407: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7408:     }
 7409:     if ($args->{'force_register'}) {
 7410:         $result .= &Apache::lonmenu::registerurl(1);
 7411:     }
 7412:     if (!$args->{'no_nav_bar'} 
 7413: 	&& !$args->{'only_body'}
 7414: 	&& !$args->{'frameset'}) {
 7415: 	$result .= &help_menu_js($httphost);
 7416:         $result.=&modal_window();
 7417:         $result.=&togglebox_script();
 7418:         $result.=&wishlist_window();
 7419:         $result.=&LCprogressbarUpdate_script();
 7420:     } else {
 7421:         if ($args->{'add_modal'}) {
 7422:            $result.=&modal_window();
 7423:         }
 7424:         if ($args->{'add_wishlist'}) {
 7425:            $result.=&wishlist_window();
 7426:         }
 7427:         if ($args->{'add_togglebox'}) {
 7428:            $result.=&togglebox_script();
 7429:         }
 7430:         if ($args->{'add_progressbar'}) {
 7431:            $result.=&LCprogressbarUpdate_script();
 7432:         }
 7433:     }
 7434:     if (ref($args->{'redirect'})) {
 7435: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7436: 	$url = &Apache::lonenc::check_encrypt($url);
 7437: 	if (!$inhibit_continue) {
 7438: 	    $env{'internal.head.redirect'} = $url;
 7439: 	}
 7440: 	$result.=<<ADDMETA
 7441: <meta http-equiv="pragma" content="no-cache" />
 7442: <meta http-equiv="Refresh" content="$time; url=$url" />
 7443: ADDMETA
 7444:     } else {
 7445:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7446:             my $requrl = $env{'request.uri'};
 7447:             if ($requrl eq '') {
 7448:                 $requrl = $ENV{'REQUEST_URI'};
 7449:                 $requrl =~ s/\?.+$//;
 7450:             }
 7451:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7452:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7453:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7454:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7455:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7456:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7457:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7458:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7459:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7460:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7461:                             if (($newserver) && ($newserver ne $lonhost)) {
 7462:                                 my $numsec = 5;
 7463:                                 my $timeout = $numsec * 1000;
 7464:                                 my ($newurl,$locknum,%locks,$msg);
 7465:                                 if ($env{'request.role.adv'}) {
 7466:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7467:                                 }
 7468:                                 my $disable_submit = 0;
 7469:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7470:                                     $disable_submit = 1;
 7471:                                 }
 7472:                                 if ($locknum) {
 7473:                                     my @lockinfo = sort(values(%locks));
 7474:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7475:                                            join(", ",sort(values(%locks)))."\\n".
 7476:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7477:                                 } else {
 7478:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7479:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7480:                                     }
 7481:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7482:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7483:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7484:                                         $newurl .= '&role='.$env{'request.role'};
 7485:                                     }
 7486:                                     if ($env{'request.symb'}) {
 7487:                                         $newurl .= '&symb='.$env{'request.symb'};
 7488:                                     } else {
 7489:                                         $newurl .= '&origurl='.$requrl;
 7490:                                     }
 7491:                                 }
 7492:                                 &js_escape(\$msg);
 7493:                                 $result.=<<OFFLOAD
 7494: <meta http-equiv="pragma" content="no-cache" />
 7495: <script type="text/javascript">
 7496: // <![CDATA[
 7497: function LC_Offload_Now() {
 7498:     var dest = "$newurl";
 7499:     if (dest != '') {
 7500:         window.location.href="$newurl";
 7501:     }
 7502: }
 7503: \$(document).ready(function () {
 7504:     window.alert('$msg');
 7505:     if ($disable_submit) {
 7506:         \$(".LC_hwk_submit").prop("disabled", true);
 7507:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7508:     }
 7509:     setTimeout('LC_Offload_Now()', $timeout);
 7510: });
 7511: // ]]>
 7512: </script>
 7513: OFFLOAD
 7514:                             }
 7515:                         }
 7516:                     }
 7517:                 }
 7518:             }
 7519:         }
 7520:     }
 7521:     if (!defined($title)) {
 7522: 	$title = 'The LearningOnline Network with CAPA';
 7523:     }
 7524:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7525:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7526: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7527:     if (!$args->{'frameset'}) {
 7528:         $result .= ' /';
 7529:     }
 7530:     $result .= '>'
 7531:         .$inhibitprint
 7532: 	.$head_extra;
 7533:     if ($env{'browser.mobile'}) {
 7534:         $result .= '
 7535: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7536: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7537:     }
 7538:     return $result.'</head>';
 7539: }
 7540: 
 7541: =pod
 7542: 
 7543: =item * &font_settings()
 7544: 
 7545: Returns neccessary <meta> to set the proper encoding
 7546: 
 7547: Inputs: optional reference to HASH -- $args passed to &headtag()
 7548: 
 7549: =cut
 7550: 
 7551: sub font_settings {
 7552:     my ($args) = @_;
 7553:     my $headerstring='';
 7554:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7555:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7556: 	$headerstring.=
 7557: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7558:         if (!$args->{'frameset'}) {
 7559:             $headerstring.= ' /';
 7560:         }
 7561:         $headerstring .= '>'."\n";
 7562:     }
 7563:     return $headerstring;
 7564: }
 7565: 
 7566: =pod
 7567: 
 7568: =item * &print_suppression()
 7569: 
 7570: In course context returns css which causes the body to be blank when media="print",
 7571: if printout generation is unavailable for the current resource.
 7572: 
 7573: This could be because:
 7574: 
 7575: (a) printstartdate is in the future
 7576: 
 7577: (b) printenddate is in the past
 7578: 
 7579: (c) there is an active exam block with "printout"
 7580: functionality blocked
 7581: 
 7582: Users with pav, pfo or evb privileges are exempt.
 7583: 
 7584: Inputs: none
 7585: 
 7586: =cut
 7587: 
 7588: 
 7589: sub print_suppression {
 7590:     my $noprint;
 7591:     if ($env{'request.course.id'}) {
 7592:         my $scope = $env{'request.course.id'};
 7593:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7594:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7595:             return;
 7596:         }
 7597:         if ($env{'request.course.sec'} ne '') {
 7598:             $scope .= "/$env{'request.course.sec'}";
 7599:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7600:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7601:                 return;
 7602:             }
 7603:         }
 7604:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7605:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7606:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 7607:         if ($blocked) {
 7608:             my $checkrole = "cm./$cdom/$cnum";
 7609:             if ($env{'request.course.sec'} ne '') {
 7610:                 $checkrole .= "/$env{'request.course.sec'}";
 7611:             }
 7612:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7613:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7614:                 $noprint = 1;
 7615:             }
 7616:         }
 7617:         unless ($noprint) {
 7618:             my $symb = &Apache::lonnet::symbread();
 7619:             if ($symb ne '') {
 7620:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7621:                 if (ref($navmap)) {
 7622:                     my $res = $navmap->getBySymb($symb);
 7623:                     if (ref($res)) {
 7624:                         if (!$res->resprintable()) {
 7625:                             $noprint = 1;
 7626:                         }
 7627:                     }
 7628:                 }
 7629:             }
 7630:         }
 7631:         if ($noprint) {
 7632:             return <<"ENDSTYLE";
 7633: <style type="text/css" media="print">
 7634:     body { display:none }
 7635: </style>
 7636: ENDSTYLE
 7637:         }
 7638:     }
 7639:     return;
 7640: }
 7641: 
 7642: =pod
 7643: 
 7644: =item * &xml_begin()
 7645: 
 7646: Returns the needed doctype and <html>
 7647: 
 7648: Inputs: none
 7649: 
 7650: =cut
 7651: 
 7652: sub xml_begin {
 7653:     my ($is_frameset) = @_;
 7654:     my $output='';
 7655: 
 7656:     if ($env{'browser.mathml'}) {
 7657: 	$output='<?xml version="1.0"?>'
 7658:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7659: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7660:             
 7661: #	    .'<!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">] >'
 7662: 	    .'<!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">'
 7663:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7664: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7665:     } elsif ($is_frameset) {
 7666:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 7667:                 '<html>'."\n";
 7668:     } else {
 7669: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 7670:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7671:     }
 7672:     return $output;
 7673: }
 7674: 
 7675: =pod
 7676: 
 7677: =item * &start_page()
 7678: 
 7679: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7680: 
 7681: Inputs:
 7682: 
 7683: =over 4
 7684: 
 7685: $title - optional title for the page
 7686: 
 7687: $head_extra - optional extra HTML to incude inside the <head>
 7688: 
 7689: $args - additional optional args supported are:
 7690: 
 7691: =over 8
 7692: 
 7693:              only_body      -> is true will set &bodytag() onlybodytag
 7694:                                     arg on
 7695:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7696:              add_entries    -> additional attributes to add to the  <body>
 7697:              domain         -> force to color decorate a page for a 
 7698:                                     specific domain
 7699:              function       -> force usage of a specific rolish color
 7700:                                     scheme
 7701:              redirect       -> see &headtag()
 7702:              bgcolor        -> override the default page bg color
 7703:              js_ready       -> return a string ready for being used in 
 7704:                                     a javascript writeln
 7705:              html_encode    -> return a string ready for being used in 
 7706:                                     a html attribute
 7707:              force_register -> if is true will turn on the &bodytag()
 7708:                                     $forcereg arg
 7709:              frameset       -> if true will start with a <frameset>
 7710:                                     rather than <body>
 7711:              skip_phases    -> hash ref of 
 7712:                                     head -> skip the <html><head> generation
 7713:                                     body -> skip all <body> generation
 7714:              no_inline_link -> if true and in remote mode, don't show the
 7715:                                     'Switch To Inline Menu' link
 7716:              no_auto_mt_title -> prevent &mt()ing the title arg
 7717:              inherit_jsmath -> when creating popup window in a page,
 7718:                                     should it have jsmath forced on by the
 7719:                                     current page
 7720:              bread_crumbs ->             Array containing breadcrumbs
 7721:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7722:              group          -> includes the current group, if page is for a
 7723:                                specific group
 7724: 
 7725: =back
 7726: 
 7727: =back
 7728: 
 7729: =cut
 7730: 
 7731: sub start_page {
 7732:     my ($title,$head_extra,$args) = @_;
 7733:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7734: 
 7735:     $env{'internal.start_page'}++;
 7736:     my ($result,@advtools);
 7737: 
 7738:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7739:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 7740:     }
 7741:     
 7742:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7743: 	if ($args->{'frameset'}) {
 7744: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7745: 						$args->{'add_entries'});
 7746: 	    $result .= "\n<frameset $attr_string>\n";
 7747:         } else {
 7748:             $result .=
 7749:                 &bodytag($title, 
 7750:                          $args->{'function'},       $args->{'add_entries'},
 7751:                          $args->{'only_body'},      $args->{'domain'},
 7752:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7753:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7754:                          $args,                     \@advtools);
 7755:         }
 7756:     }
 7757: 
 7758:     if ($args->{'js_ready'}) {
 7759: 		$result = &js_ready($result);
 7760:     }
 7761:     if ($args->{'html_encode'}) {
 7762: 		$result = &html_encode($result);
 7763:     }
 7764: 
 7765:     # Preparation for new and consistent functionlist at top of screen
 7766:     # if ($args->{'functionlist'}) {
 7767:     #            $result .= &build_functionlist();
 7768:     #}
 7769: 
 7770:     # Don't add anything more if only_body wanted or in const space
 7771:     return $result if    $args->{'only_body'} 
 7772:                       || $env{'request.state'} eq 'construct';
 7773: 
 7774:     #Breadcrumbs
 7775:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7776: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7777: 		#if any br links exists, add them to the breadcrumbs
 7778: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7779: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7780: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7781: 			}
 7782: 		}
 7783:                 # if @advtools array contains items add then to the breadcrumbs
 7784:                 if (@advtools > 0) {
 7785:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7786:                 }
 7787: 
 7788: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7789: 		if(exists($args->{'bread_crumbs_component'})){
 7790: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7791: 		}else{
 7792: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7793: 		}
 7794:     } elsif (($env{'environment.remote'} eq 'on') &&
 7795:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7796:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7797:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7798:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7799:     }
 7800:     return $result;
 7801: }
 7802: 
 7803: sub end_page {
 7804:     my ($args) = @_;
 7805:     $env{'internal.end_page'}++;
 7806:     my $result;
 7807:     if ($args->{'discussion'}) {
 7808: 	my ($target,$parser);
 7809: 	if (ref($args->{'discussion'})) {
 7810: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7811: 				$args->{'discussion'}{'parser'});
 7812: 	}
 7813: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7814:     }
 7815:     if ($args->{'frameset'}) {
 7816: 	$result .= '</frameset>';
 7817:     } else {
 7818: 	$result .= &endbodytag($args);
 7819:     }
 7820:     unless ($args->{'notbody'}) {
 7821:         $result .= "\n</html>";
 7822:     }
 7823: 
 7824:     if ($args->{'js_ready'}) {
 7825: 	$result = &js_ready($result);
 7826:     }
 7827: 
 7828:     if ($args->{'html_encode'}) {
 7829: 	$result = &html_encode($result);
 7830:     }
 7831: 
 7832:     return $result;
 7833: }
 7834: 
 7835: sub wishlist_window {
 7836:     return(<<'ENDWISHLIST');
 7837: <script type="text/javascript">
 7838: // <![CDATA[
 7839: // <!-- BEGIN LON-CAPA Internal
 7840: function set_wishlistlink(title, path) {
 7841:     if (!title) {
 7842:         title = document.title;
 7843:         title = title.replace(/^LON-CAPA /,'');
 7844:     }
 7845:     title = encodeURIComponent(title);
 7846:     title = title.replace("'","\\\'");
 7847:     if (!path) {
 7848:         path = location.pathname;
 7849:     }
 7850:     path = encodeURIComponent(path);
 7851:     path = path.replace("'","\\\'");
 7852:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7853:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7854: }
 7855: // END LON-CAPA Internal -->
 7856: // ]]>
 7857: </script>
 7858: ENDWISHLIST
 7859: }
 7860: 
 7861: sub modal_window {
 7862:     return(<<'ENDMODAL');
 7863: <script type="text/javascript">
 7864: // <![CDATA[
 7865: // <!-- BEGIN LON-CAPA Internal
 7866: var modalWindow = {
 7867: 	parent:"body",
 7868: 	windowId:null,
 7869: 	content:null,
 7870: 	width:null,
 7871: 	height:null,
 7872: 	close:function()
 7873: 	{
 7874: 	        $(".LCmodal-window").remove();
 7875: 	        $(".LCmodal-overlay").remove();
 7876: 	},
 7877: 	open:function()
 7878: 	{
 7879: 		var modal = "";
 7880: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7881: 		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;\">";
 7882: 		modal += this.content;
 7883: 		modal += "</div>";	
 7884: 
 7885: 		$(this.parent).append(modal);
 7886: 
 7887: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7888: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7889: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7890: 	}
 7891: };
 7892: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7893: 	{
 7894:                 source = source.replace("'","&#39;");
 7895: 		modalWindow.windowId = "myModal";
 7896: 		modalWindow.width = width;
 7897: 		modalWindow.height = height;
 7898: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 7899: 		modalWindow.open();
 7900: 	};
 7901: // END LON-CAPA Internal -->
 7902: // ]]>
 7903: </script>
 7904: ENDMODAL
 7905: }
 7906: 
 7907: sub modal_link {
 7908:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7909:     unless ($width) { $width=480; }
 7910:     unless ($height) { $height=400; }
 7911:     unless ($scrolling) { $scrolling='yes'; }
 7912:     unless ($transparency) { $transparency='true'; }
 7913: 
 7914:     my $target_attr;
 7915:     if (defined($target)) {
 7916:         $target_attr = 'target="'.$target.'"';
 7917:     }
 7918:     return <<"ENDLINK";
 7919: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7920:            $linktext</a>
 7921: ENDLINK
 7922: }
 7923: 
 7924: sub modal_adhoc_script {
 7925:     my ($funcname,$width,$height,$content)=@_;
 7926:     return (<<ENDADHOC);
 7927: <script type="text/javascript">
 7928: // <![CDATA[
 7929:         var $funcname = function()
 7930:         {
 7931:                 modalWindow.windowId = "myModal";
 7932:                 modalWindow.width = $width;
 7933:                 modalWindow.height = $height;
 7934:                 modalWindow.content = '$content';
 7935:                 modalWindow.open();
 7936:         };  
 7937: // ]]>
 7938: </script>
 7939: ENDADHOC
 7940: }
 7941: 
 7942: sub modal_adhoc_inner {
 7943:     my ($funcname,$width,$height,$content)=@_;
 7944:     my $innerwidth=$width-20;
 7945:     $content=&js_ready(
 7946:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7947:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7948:                  $content.
 7949:                  &end_scrollbox().
 7950:                  &end_page()
 7951:              );
 7952:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7953: }
 7954: 
 7955: sub modal_adhoc_window {
 7956:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7957:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7958:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7959: }
 7960: 
 7961: sub modal_adhoc_launch {
 7962:     my ($funcname,$width,$height,$content)=@_;
 7963:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7964: <script type="text/javascript">
 7965: // <![CDATA[
 7966: $funcname();
 7967: // ]]>
 7968: </script>
 7969: ENDLAUNCH
 7970: }
 7971: 
 7972: sub modal_adhoc_close {
 7973:     return (<<ENDCLOSE);
 7974: <script type="text/javascript">
 7975: // <![CDATA[
 7976: modalWindow.close();
 7977: // ]]>
 7978: </script>
 7979: ENDCLOSE
 7980: }
 7981: 
 7982: sub togglebox_script {
 7983:    return(<<ENDTOGGLE);
 7984: <script type="text/javascript"> 
 7985: // <![CDATA[
 7986: function LCtoggleDisplay(id,hidetext,showtext) {
 7987:    link = document.getElementById(id + "link").childNodes[0];
 7988:    with (document.getElementById(id).style) {
 7989:       if (display == "none" ) {
 7990:           display = "inline";
 7991:           link.nodeValue = hidetext;
 7992:         } else {
 7993:           display = "none";
 7994:           link.nodeValue = showtext;
 7995:        }
 7996:    }
 7997: }
 7998: // ]]>
 7999: </script>
 8000: ENDTOGGLE
 8001: }
 8002: 
 8003: sub start_togglebox {
 8004:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8005:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8006:     unless ($showtext) { $showtext=&mt('show'); }
 8007:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8008:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8009:     return &start_data_table().
 8010:            &start_data_table_header_row().
 8011:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8012:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8013:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8014:            &end_data_table_header_row().
 8015:            '<tr id="'.$id.'" style="display:none""><td>';
 8016: }
 8017: 
 8018: sub end_togglebox {
 8019:     return '</td></tr>'.&end_data_table();
 8020: }
 8021: 
 8022: sub LCprogressbar_script {
 8023:    my ($id)=@_;
 8024:    return(<<ENDPROGRESS);
 8025: <script type="text/javascript">
 8026: // <![CDATA[
 8027: \$('#progressbar$id').progressbar({
 8028:   value: 0,
 8029:   change: function(event, ui) {
 8030:     var newVal = \$(this).progressbar('option', 'value');
 8031:     \$('.pblabel', this).text(LCprogressTxt);
 8032:   }
 8033: });
 8034: // ]]>
 8035: </script>
 8036: ENDPROGRESS
 8037: }
 8038: 
 8039: sub LCprogressbarUpdate_script {
 8040:    return(<<ENDPROGRESSUPDATE);
 8041: <style type="text/css">
 8042: .ui-progressbar { position:relative; }
 8043: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8044: </style>
 8045: <script type="text/javascript">
 8046: // <![CDATA[
 8047: var LCprogressTxt='---';
 8048: 
 8049: function LCupdateProgress(percent,progresstext,id) {
 8050:    LCprogressTxt=progresstext;
 8051:    \$('#progressbar'+id).progressbar('value',percent);
 8052: }
 8053: // ]]>
 8054: </script>
 8055: ENDPROGRESSUPDATE
 8056: }
 8057: 
 8058: my $LClastpercent;
 8059: my $LCidcnt;
 8060: my $LCcurrentid;
 8061: 
 8062: sub LCprogressbar {
 8063:     my ($r)=(@_);
 8064:     $LClastpercent=0;
 8065:     $LCidcnt++;
 8066:     $LCcurrentid=$$.'_'.$LCidcnt;
 8067:     my $starting=&mt('Starting');
 8068:     my $content=(<<ENDPROGBAR);
 8069:   <div id="progressbar$LCcurrentid">
 8070:     <span class="pblabel">$starting</span>
 8071:   </div>
 8072: ENDPROGBAR
 8073:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8074: }
 8075: 
 8076: sub LCprogressbarUpdate {
 8077:     my ($r,$val,$text)=@_;
 8078:     unless ($val) { 
 8079:        if ($LClastpercent) {
 8080:            $val=$LClastpercent;
 8081:        } else {
 8082:            $val=0;
 8083:        }
 8084:     }
 8085:     if ($val<0) { $val=0; }
 8086:     if ($val>100) { $val=0; }
 8087:     $LClastpercent=$val;
 8088:     unless ($text) { $text=$val.'%'; }
 8089:     $text=&js_ready($text);
 8090:     &r_print($r,<<ENDUPDATE);
 8091: <script type="text/javascript">
 8092: // <![CDATA[
 8093: LCupdateProgress($val,'$text','$LCcurrentid');
 8094: // ]]>
 8095: </script>
 8096: ENDUPDATE
 8097: }
 8098: 
 8099: sub LCprogressbarClose {
 8100:     my ($r)=@_;
 8101:     $LClastpercent=0;
 8102:     &r_print($r,<<ENDCLOSE);
 8103: <script type="text/javascript">
 8104: // <![CDATA[
 8105: \$("#progressbar$LCcurrentid").hide('slow'); 
 8106: // ]]>
 8107: </script>
 8108: ENDCLOSE
 8109: }
 8110: 
 8111: sub r_print {
 8112:     my ($r,$to_print)=@_;
 8113:     if ($r) {
 8114:       $r->print($to_print);
 8115:       $r->rflush();
 8116:     } else {
 8117:       print($to_print);
 8118:     }
 8119: }
 8120: 
 8121: sub html_encode {
 8122:     my ($result) = @_;
 8123: 
 8124:     $result = &HTML::Entities::encode($result,'<>&"');
 8125:     
 8126:     return $result;
 8127: }
 8128: 
 8129: sub js_ready {
 8130:     my ($result) = @_;
 8131: 
 8132:     $result =~ s/[\n\r]/ /xmsg;
 8133:     $result =~ s/\\/\\\\/xmsg;
 8134:     $result =~ s/'/\\'/xmsg;
 8135:     $result =~ s{</}{<\\/}xmsg;
 8136:     
 8137:     return $result;
 8138: }
 8139: 
 8140: sub validate_page {
 8141:     if (  exists($env{'internal.start_page'})
 8142: 	  &&     $env{'internal.start_page'} > 1) {
 8143: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8144: 				 $env{'internal.start_page'}.' '.
 8145: 				 $ENV{'request.filename'});
 8146:     }
 8147:     if (  exists($env{'internal.end_page'})
 8148: 	  &&     $env{'internal.end_page'} > 1) {
 8149: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8150: 				 $env{'internal.end_page'}.' '.
 8151: 				 $env{'request.filename'});
 8152:     }
 8153:     if (     exists($env{'internal.start_page'})
 8154: 	&& ! exists($env{'internal.end_page'})) {
 8155: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8156: 				 $env{'request.filename'});
 8157:     }
 8158:     if (   ! exists($env{'internal.start_page'})
 8159: 	&&   exists($env{'internal.end_page'})) {
 8160: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8161: 				 $env{'request.filename'});
 8162:     }
 8163: }
 8164: 
 8165: 
 8166: sub start_scrollbox {
 8167:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8168:     unless ($outerwidth) { $outerwidth='520px'; }
 8169:     unless ($width) { $width='500px'; }
 8170:     unless ($height) { $height='200px'; }
 8171:     my ($table_id,$div_id,$tdcol);
 8172:     if ($id ne '') {
 8173:         $table_id = ' id="table_'.$id.'"';
 8174:         $div_id = ' id="div_'.$id.'"';
 8175:     }
 8176:     if ($bgcolor ne '') {
 8177:         $tdcol = "background-color: $bgcolor;";
 8178:     }
 8179:     my $nicescroll_js;
 8180:     if ($env{'browser.mobile'}) {
 8181:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8182:     }
 8183:     return <<"END";
 8184: $nicescroll_js
 8185: 
 8186: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8187: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8188: END
 8189: }
 8190: 
 8191: sub end_scrollbox {
 8192:     return '</div></td></tr></table>';
 8193: }
 8194: 
 8195: sub nicescroll_javascript {
 8196:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8197:     my %options;
 8198:     if (ref($cursor) eq 'HASH') {
 8199:         %options = %{$cursor};
 8200:     }
 8201:     unless ($options{'railalign'} =~ /^left|right$/) {
 8202:         $options{'railalign'} = 'left';
 8203:     }
 8204:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8205:         my $function  = &get_users_function();
 8206:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8207:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8208:             $options{'cursorcolor'} = '#00F';
 8209:         }
 8210:     }
 8211:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8212:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8213:             $options{'cursoropacity'}='1.0';
 8214:         }
 8215:     } else {
 8216:         $options{'cursoropacity'}='1.0';
 8217:     }
 8218:     if ($options{'cursorfixedheight'} eq 'none') {
 8219:         delete($options{'cursorfixedheight'});
 8220:     } else {
 8221:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8222:     }
 8223:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8224:         delete($options{'railoffset'});
 8225:     }
 8226:     my @niceoptions;
 8227:     while (my($key,$value) = each(%options)) {
 8228:         if ($value =~ /^\{.+\}$/) {
 8229:             push(@niceoptions,$key.':'.$value);
 8230:         } else {
 8231:             push(@niceoptions,$key.':"'.$value.'"');
 8232:         }
 8233:     }
 8234:     my $nicescroll_js = '
 8235: $(document).ready(
 8236:       function() {
 8237:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8238:       }
 8239: );
 8240: ';
 8241:     if ($framecheck) {
 8242:         $nicescroll_js .= '
 8243: function expand_div(caller) {
 8244:     if (top === self) {
 8245:         document.getElementById("'.$id.'").style.width = "auto";
 8246:         document.getElementById("'.$id.'").style.height = "auto";
 8247:     } else {
 8248:         try {
 8249:             if (parent.frames) {
 8250:                 if (parent.frames.length > 1) {
 8251:                     var framesrc = parent.frames[1].location.href;
 8252:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8253:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8254:                         document.getElementById("'.$id.'").style.width = "auto";
 8255:                         document.getElementById("'.$id.'").style.height = "auto";
 8256:                     }
 8257:                 }
 8258:             }
 8259:         } catch (e) {
 8260:             return;
 8261:         }
 8262:     }
 8263:     return;
 8264: }
 8265: ';
 8266:     }
 8267:     if ($needjsready) {
 8268:         $nicescroll_js = '
 8269: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8270:     } else {
 8271:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8272:     }
 8273:     return $nicescroll_js;
 8274: }
 8275: 
 8276: sub simple_error_page {
 8277:     my ($r,$title,$msg,$args) = @_;
 8278:     if (ref($args) eq 'HASH') {
 8279:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8280:     } else {
 8281:         $msg = &mt($msg);
 8282:     }
 8283: 
 8284:     my $page =
 8285: 	&Apache::loncommon::start_page($title).
 8286: 	'<p class="LC_error">'.$msg.'</p>'.
 8287: 	&Apache::loncommon::end_page();
 8288:     if (ref($r)) {
 8289: 	$r->print($page);
 8290: 	return;
 8291:     }
 8292:     return $page;
 8293: }
 8294: 
 8295: {
 8296:     my @row_count;
 8297: 
 8298:     sub start_data_table_count {
 8299:         unshift(@row_count, 0);
 8300:         return;
 8301:     }
 8302: 
 8303:     sub end_data_table_count {
 8304:         shift(@row_count);
 8305:         return;
 8306:     }
 8307: 
 8308:     sub start_data_table {
 8309: 	my ($add_class,$id) = @_;
 8310: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8311:         my $table_id;
 8312:         if (defined($id)) {
 8313:             $table_id = ' id="'.$id.'"';
 8314:         }
 8315: 	&start_data_table_count();
 8316: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8317:     }
 8318: 
 8319:     sub end_data_table {
 8320: 	&end_data_table_count();
 8321: 	return '</table>'."\n";;
 8322:     }
 8323: 
 8324:     sub start_data_table_row {
 8325: 	my ($add_class, $id) = @_;
 8326: 	$row_count[0]++;
 8327: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8328: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8329:         $id = (' id="'.$id.'"') unless ($id eq '');
 8330:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8331:     }
 8332:     
 8333:     sub continue_data_table_row {
 8334: 	my ($add_class, $id) = @_;
 8335: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8336: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8337:         $id = (' id="'.$id.'"') unless ($id eq '');
 8338:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8339:     }
 8340: 
 8341:     sub end_data_table_row {
 8342: 	return '</tr>'."\n";;
 8343:     }
 8344: 
 8345:     sub start_data_table_empty_row {
 8346: #	$row_count[0]++;
 8347: 	return  '<tr class="LC_empty_row" >'."\n";;
 8348:     }
 8349: 
 8350:     sub end_data_table_empty_row {
 8351: 	return '</tr>'."\n";;
 8352:     }
 8353: 
 8354:     sub start_data_table_header_row {
 8355: 	return  '<tr class="LC_header_row">'."\n";;
 8356:     }
 8357: 
 8358:     sub end_data_table_header_row {
 8359: 	return '</tr>'."\n";;
 8360:     }
 8361: 
 8362:     sub data_table_caption {
 8363:         my $caption = shift;
 8364:         return "<caption class=\"LC_caption\">$caption</caption>";
 8365:     }
 8366: }
 8367: 
 8368: =pod
 8369: 
 8370: =item * &inhibit_menu_check($arg)
 8371: 
 8372: Checks for a inhibitmenu state and generates output to preserve it
 8373: 
 8374: Inputs:         $arg - can be any of
 8375:                      - undef - in which case the return value is a string 
 8376:                                to add  into arguments list of a uri
 8377:                      - 'input' - in which case the return value is a HTML
 8378:                                  <form> <input> field of type hidden to
 8379:                                  preserve the value
 8380:                      - a url - in which case the return value is the url with
 8381:                                the neccesary cgi args added to preserve the
 8382:                                inhibitmenu state
 8383:                      - a ref to a url - no return value, but the string is
 8384:                                         updated to include the neccessary cgi
 8385:                                         args to preserve the inhibitmenu state
 8386: 
 8387: =cut
 8388: 
 8389: sub inhibit_menu_check {
 8390:     my ($arg) = @_;
 8391:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8392:     if ($arg eq 'input') {
 8393: 	if ($env{'form.inhibitmenu'}) {
 8394: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8395: 	} else {
 8396: 	    return
 8397: 	}
 8398:     }
 8399:     if ($env{'form.inhibitmenu'}) {
 8400: 	if (ref($arg)) {
 8401: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8402: 	} elsif ($arg eq '') {
 8403: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8404: 	} else {
 8405: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8406: 	}
 8407:     }
 8408:     if (!ref($arg)) {
 8409: 	return $arg;
 8410:     }
 8411: }
 8412: 
 8413: ###############################################
 8414: 
 8415: =pod
 8416: 
 8417: =back
 8418: 
 8419: =head1 User Information Routines
 8420: 
 8421: =over 4
 8422: 
 8423: =item * &get_users_function()
 8424: 
 8425: Used by &bodytag to determine the current users primary role.
 8426: Returns either 'student','coordinator','admin', or 'author'.
 8427: 
 8428: =cut
 8429: 
 8430: ###############################################
 8431: sub get_users_function {
 8432:     my $function = 'norole';
 8433:     if ($env{'request.role'}=~/^(st)/) {
 8434:         $function='student';
 8435:     }
 8436:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8437:         $function='coordinator';
 8438:     }
 8439:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8440:         $function='admin';
 8441:     }
 8442:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8443:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8444:         $function='author';
 8445:     }
 8446:     return $function;
 8447: }
 8448: 
 8449: ###############################################
 8450: 
 8451: =pod
 8452: 
 8453: =item * &show_course()
 8454: 
 8455: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8456: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8457: 
 8458: Inputs:
 8459: None
 8460: 
 8461: Outputs:
 8462: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8463: 
 8464: =cut
 8465: 
 8466: ###############################################
 8467: sub show_course {
 8468:     my $course = !$env{'user.adv'};
 8469:     if (!$env{'user.adv'}) {
 8470:         foreach my $env (keys(%env)) {
 8471:             next if ($env !~ m/^user\.priv\./);
 8472:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8473:                 $course = 0;
 8474:                 last;
 8475:             }
 8476:         }
 8477:     }
 8478:     return $course;
 8479: }
 8480: 
 8481: ###############################################
 8482: 
 8483: =pod
 8484: 
 8485: =item * &check_user_status()
 8486: 
 8487: Determines current status of supplied role for a
 8488: specific user. Roles can be active, previous or future.
 8489: 
 8490: Inputs: 
 8491: user's domain, user's username, course's domain,
 8492: course's number, optional section ID.
 8493: 
 8494: Outputs:
 8495: role status: active, previous or future. 
 8496: 
 8497: =cut
 8498: 
 8499: sub check_user_status {
 8500:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8501:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8502:     my @uroles = keys(%userinfo);
 8503:     my $srchstr;
 8504:     my $active_chk = 'none';
 8505:     my $now = time;
 8506:     if (@uroles > 0) {
 8507:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8508:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8509:         } else {
 8510:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8511:         }
 8512:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8513:             my $role_end = 0;
 8514:             my $role_start = 0;
 8515:             $active_chk = 'active';
 8516:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8517:                 $role_end = $1;
 8518:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8519:                     $role_start = $1;
 8520:                 }
 8521:             }
 8522:             if ($role_start > 0) {
 8523:                 if ($now < $role_start) {
 8524:                     $active_chk = 'future';
 8525:                 }
 8526:             }
 8527:             if ($role_end > 0) {
 8528:                 if ($now > $role_end) {
 8529:                     $active_chk = 'previous';
 8530:                 }
 8531:             }
 8532:         }
 8533:     }
 8534:     return $active_chk;
 8535: }
 8536: 
 8537: ###############################################
 8538: 
 8539: =pod
 8540: 
 8541: =item * &get_sections()
 8542: 
 8543: Determines all the sections for a course including
 8544: sections with students and sections containing other roles.
 8545: Incoming parameters: 
 8546: 
 8547: 1. domain
 8548: 2. course number 
 8549: 3. reference to array containing roles for which sections should 
 8550: be gathered (optional).
 8551: 4. reference to array containing status types for which sections 
 8552: should be gathered (optional).
 8553: 
 8554: If the third argument is undefined, sections are gathered for any role. 
 8555: If the fourth argument is undefined, sections are gathered for any status.
 8556: Permissible values are 'active' or 'future' or 'previous'.
 8557:  
 8558: Returns section hash (keys are section IDs, values are
 8559: number of users in each section), subject to the
 8560: optional roles filter, optional status filter 
 8561: 
 8562: =cut
 8563: 
 8564: ###############################################
 8565: sub get_sections {
 8566:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8567:     if (!defined($cdom) || !defined($cnum)) {
 8568:         my $cid =  $env{'request.course.id'};
 8569: 
 8570: 	return if (!defined($cid));
 8571: 
 8572:         $cdom = $env{'course.'.$cid.'.domain'};
 8573:         $cnum = $env{'course.'.$cid.'.num'};
 8574:     }
 8575: 
 8576:     my %sectioncount;
 8577:     my $now = time;
 8578: 
 8579:     my $check_students = 1;
 8580:     my $only_students = 0;
 8581:     if (ref($possible_roles) eq 'ARRAY') {
 8582:         if (grep(/^st$/,@{$possible_roles})) {
 8583:             if (@{$possible_roles} == 1) {
 8584:                 $only_students = 1;
 8585:             }
 8586:         } else {
 8587:             $check_students = 0;
 8588:         }
 8589:     }
 8590: 
 8591:     if ($check_students) {
 8592: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8593: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8594: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8595:         my $start_index = &Apache::loncoursedata::CL_START();
 8596:         my $end_index = &Apache::loncoursedata::CL_END();
 8597:         my $status;
 8598: 	while (my ($student,$data) = each(%$classlist)) {
 8599: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8600: 				                     $data->[$status_index],
 8601:                                                      $data->[$start_index],
 8602:                                                      $data->[$end_index]);
 8603:             if ($stu_status eq 'Active') {
 8604:                 $status = 'active';
 8605:             } elsif ($end < $now) {
 8606:                 $status = 'previous';
 8607:             } elsif ($start > $now) {
 8608:                 $status = 'future';
 8609:             } 
 8610: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8611:                 if ((!defined($possible_status)) || (($status ne '') && 
 8612:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8613: 		    $sectioncount{$section}++;
 8614:                 }
 8615: 	    }
 8616: 	}
 8617:     }
 8618:     if ($only_students) {
 8619:         return %sectioncount;
 8620:     }
 8621:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8622:     foreach my $user (sort(keys(%courseroles))) {
 8623: 	if ($user !~ /^(\w{2})/) { next; }
 8624: 	my ($role) = ($user =~ /^(\w{2})/);
 8625: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8626: 	my ($section,$status);
 8627: 	if ($role eq 'cr' &&
 8628: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8629: 	    $section=$1;
 8630: 	}
 8631: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8632: 	if (!defined($section) || $section eq '-1') { next; }
 8633:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8634:         if ($end == -1 && $start == -1) {
 8635:             next; #deleted role
 8636:         }
 8637:         if (!defined($possible_status)) { 
 8638:             $sectioncount{$section}++;
 8639:         } else {
 8640:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8641:                 $status = 'active';
 8642:             } elsif ($end < $now) {
 8643:                 $status = 'future';
 8644:             } elsif ($start > $now) {
 8645:                 $status = 'previous';
 8646:             }
 8647:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8648:                 $sectioncount{$section}++;
 8649:             }
 8650:         }
 8651:     }
 8652:     return %sectioncount;
 8653: }
 8654: 
 8655: ###############################################
 8656: 
 8657: =pod
 8658: 
 8659: =item * &get_course_users()
 8660: 
 8661: Retrieves usernames:domains for users in the specified course
 8662: with specific role(s), and access status. 
 8663: 
 8664: Incoming parameters:
 8665: 1. course domain
 8666: 2. course number
 8667: 3. access status: users must have - either active, 
 8668: previous, future, or all.
 8669: 4. reference to array of permissible roles
 8670: 5. reference to array of section restrictions (optional)
 8671: 6. reference to results object (hash of hashes).
 8672: 7. reference to optional userdata hash
 8673: 8. reference to optional statushash
 8674: 9. flag if privileged users (except those set to unhide in
 8675:    course settings) should be excluded    
 8676: Keys of top level results hash are roles.
 8677: Keys of inner hashes are username:domain, with 
 8678: values set to access type.
 8679: Optional userdata hash returns an array with arguments in the 
 8680: same order as loncoursedata::get_classlist() for student data.
 8681: 
 8682: Optional statushash returns
 8683: 
 8684: Entries for end, start, section and status are blank because
 8685: of the possibility of multiple values for non-student roles.
 8686: 
 8687: =cut
 8688: 
 8689: ###############################################
 8690: 
 8691: sub get_course_users {
 8692:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8693:     my %idx = ();
 8694:     my %seclists;
 8695: 
 8696:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8697:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8698:     $idx{end} = &Apache::loncoursedata::CL_END();
 8699:     $idx{start} = &Apache::loncoursedata::CL_START();
 8700:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8701:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8702:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8703:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8704: 
 8705:     if (grep(/^st$/,@{$roles})) {
 8706:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8707:         my $now = time;
 8708:         foreach my $student (keys(%{$classlist})) {
 8709:             my $match = 0;
 8710:             my $secmatch = 0;
 8711:             my $section = $$classlist{$student}[$idx{section}];
 8712:             my $status = $$classlist{$student}[$idx{status}];
 8713:             if ($section eq '') {
 8714:                 $section = 'none';
 8715:             }
 8716:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8717:                 if (grep(/^all$/,@{$sections})) {
 8718:                     $secmatch = 1;
 8719:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8720:                     if (grep(/^none$/,@{$sections})) {
 8721:                         $secmatch = 1;
 8722:                     }
 8723:                 } else {  
 8724: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8725: 		        $secmatch = 1;
 8726:                     }
 8727: 		}
 8728:                 if (!$secmatch) {
 8729:                     next;
 8730:                 }
 8731:             }
 8732:             if (defined($$types{'active'})) {
 8733:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8734:                     push(@{$$users{st}{$student}},'active');
 8735:                     $match = 1;
 8736:                 }
 8737:             }
 8738:             if (defined($$types{'previous'})) {
 8739:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8740:                     push(@{$$users{st}{$student}},'previous');
 8741:                     $match = 1;
 8742:                 }
 8743:             }
 8744:             if (defined($$types{'future'})) {
 8745:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8746:                     push(@{$$users{st}{$student}},'future');
 8747:                     $match = 1;
 8748:                 }
 8749:             }
 8750:             if ($match) {
 8751:                 push(@{$seclists{$student}},$section);
 8752:                 if (ref($userdata) eq 'HASH') {
 8753:                     $$userdata{$student} = $$classlist{$student};
 8754:                 }
 8755:                 if (ref($statushash) eq 'HASH') {
 8756:                     $statushash->{$student}{'st'}{$section} = $status;
 8757:                 }
 8758:             }
 8759:         }
 8760:     }
 8761:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8762:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8763:         my $now = time;
 8764:         my %displaystatus = ( previous => 'Expired',
 8765:                               active   => 'Active',
 8766:                               future   => 'Future',
 8767:                             );
 8768:         my (%nothide,@possdoms);
 8769:         if ($hidepriv) {
 8770:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8771:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8772:                 if ($user !~ /:/) {
 8773:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8774:                 } else {
 8775:                     $nothide{$user} = 1;
 8776:                 }
 8777:             }
 8778:             my @possdoms = ($cdom);
 8779:             if ($coursehash{'checkforpriv'}) {
 8780:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8781:             }
 8782:         }
 8783:         foreach my $person (sort(keys(%coursepersonnel))) {
 8784:             my $match = 0;
 8785:             my $secmatch = 0;
 8786:             my $status;
 8787:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8788:             $user =~ s/:$//;
 8789:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8790:             if ($end == -1 || $start == -1) {
 8791:                 next;
 8792:             }
 8793:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8794:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8795:                 my ($uname,$udom) = split(/:/,$user);
 8796:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8797:                     if (grep(/^all$/,@{$sections})) {
 8798:                         $secmatch = 1;
 8799:                     } elsif ($usec eq '') {
 8800:                         if (grep(/^none$/,@{$sections})) {
 8801:                             $secmatch = 1;
 8802:                         }
 8803:                     } else {
 8804:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8805:                             $secmatch = 1;
 8806:                         }
 8807:                     }
 8808:                     if (!$secmatch) {
 8809:                         next;
 8810:                     }
 8811:                 }
 8812:                 if ($usec eq '') {
 8813:                     $usec = 'none';
 8814:                 }
 8815:                 if ($uname ne '' && $udom ne '') {
 8816:                     if ($hidepriv) {
 8817:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8818:                             (!$nothide{$uname.':'.$udom})) {
 8819:                             next;
 8820:                         }
 8821:                     }
 8822:                     if ($end > 0 && $end < $now) {
 8823:                         $status = 'previous';
 8824:                     } elsif ($start > $now) {
 8825:                         $status = 'future';
 8826:                     } else {
 8827:                         $status = 'active';
 8828:                     }
 8829:                     foreach my $type (keys(%{$types})) { 
 8830:                         if ($status eq $type) {
 8831:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8832:                                 push(@{$$users{$role}{$user}},$type);
 8833:                             }
 8834:                             $match = 1;
 8835:                         }
 8836:                     }
 8837:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8838:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8839: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8840:                         }
 8841:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8842:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8843:                         }
 8844:                         if (ref($statushash) eq 'HASH') {
 8845:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8846:                         }
 8847:                     }
 8848:                 }
 8849:             }
 8850:         }
 8851:         if (grep(/^ow$/,@{$roles})) {
 8852:             if ((defined($cdom)) && (defined($cnum))) {
 8853:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8854:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8855:                     my $owner = $csettings{'internal.courseowner'};
 8856:                     next if ($owner eq '');
 8857:                     my ($ownername,$ownerdom);
 8858:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8859:                         $ownername = $1;
 8860:                         $ownerdom = $2;
 8861:                     } else {
 8862:                         $ownername = $owner;
 8863:                         $ownerdom = $cdom;
 8864:                         $owner = $ownername.':'.$ownerdom;
 8865:                     }
 8866:                     @{$$users{'ow'}{$owner}} = 'any';
 8867:                     if (defined($userdata) && 
 8868: 			!exists($$userdata{$owner})) {
 8869: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8870:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8871:                             push(@{$seclists{$owner}},'none');
 8872:                         }
 8873:                         if (ref($statushash) eq 'HASH') {
 8874:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8875:                         }
 8876: 		    }
 8877:                 }
 8878:             }
 8879:         }
 8880:         foreach my $user (keys(%seclists)) {
 8881:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8882:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8883:         }
 8884:     }
 8885:     return;
 8886: }
 8887: 
 8888: sub get_user_info {
 8889:     my ($udom,$uname,$idx,$userdata) = @_;
 8890:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8891: 	&plainname($uname,$udom,'lastname');
 8892:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8893:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8894:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8895:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8896:     return;
 8897: }
 8898: 
 8899: ###############################################
 8900: 
 8901: =pod
 8902: 
 8903: =item * &get_user_quota()
 8904: 
 8905: Retrieves quota assigned for storage of user files.
 8906: Default is to report quota for portfolio files.
 8907: 
 8908: Incoming parameters:
 8909: 1. user's username
 8910: 2. user's domain
 8911: 3. quota name - portfolio, author, or course
 8912:    (if no quota name provided, defaults to portfolio).
 8913: 4. crstype - official, unofficial, textbook or community, if quota name is
 8914:    course
 8915: 
 8916: Returns:
 8917: 1. Disk quota (in MB) assigned to student.
 8918: 2. (Optional) Type of setting: custom or default
 8919:    (individually assigned or default for user's 
 8920:    institutional status).
 8921: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8922:    or student - types as defined in localenroll::inst_usertypes 
 8923:    for user's domain, which determines default quota for user.
 8924: 4. (Optional) - Default quota which would apply to the user.
 8925: 
 8926: If a value has been stored in the user's environment, 
 8927: it will return that, otherwise it returns the maximal default
 8928: defined for the user's institutional status(es) in the domain.
 8929: 
 8930: =cut
 8931: 
 8932: ###############################################
 8933: 
 8934: 
 8935: sub get_user_quota {
 8936:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8937:     my ($quota,$quotatype,$settingstatus,$defquota);
 8938:     if (!defined($udom)) {
 8939:         $udom = $env{'user.domain'};
 8940:     }
 8941:     if (!defined($uname)) {
 8942:         $uname = $env{'user.name'};
 8943:     }
 8944:     if (($udom eq '' || $uname eq '') ||
 8945:         ($udom eq 'public') && ($uname eq 'public')) {
 8946:         $quota = 0;
 8947:         $quotatype = 'default';
 8948:         $defquota = 0; 
 8949:     } else {
 8950:         my $inststatus;
 8951:         if ($quotaname eq 'course') {
 8952:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8953:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8954:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8955:             } else {
 8956:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8957:                 $quota = $cenv{'internal.uploadquota'};
 8958:             }
 8959:         } else {
 8960:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8961:                 if ($quotaname eq 'author') {
 8962:                     $quota = $env{'environment.authorquota'};
 8963:                 } else {
 8964:                     $quota = $env{'environment.portfolioquota'};
 8965:                 }
 8966:                 $inststatus = $env{'environment.inststatus'};
 8967:             } else {
 8968:                 my %userenv = 
 8969:                     &Apache::lonnet::get('environment',['portfolioquota',
 8970:                                          'authorquota','inststatus'],$udom,$uname);
 8971:                 my ($tmp) = keys(%userenv);
 8972:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8973:                     if ($quotaname eq 'author') {
 8974:                         $quota = $userenv{'authorquota'};
 8975:                     } else {
 8976:                         $quota = $userenv{'portfolioquota'};
 8977:                     }
 8978:                     $inststatus = $userenv{'inststatus'};
 8979:                 } else {
 8980:                     undef(%userenv);
 8981:                 }
 8982:             }
 8983:         }
 8984:         if ($quota eq '' || wantarray) {
 8985:             if ($quotaname eq 'course') {
 8986:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8987:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 8988:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 8989:                     $defquota = $domdefs{$crstype.'quota'};
 8990:                 }
 8991:                 if ($defquota eq '') {
 8992:                     $defquota = 500;
 8993:                 }
 8994:             } else {
 8995:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8996:             }
 8997:             if ($quota eq '') {
 8998:                 $quota = $defquota;
 8999:                 $quotatype = 'default';
 9000:             } else {
 9001:                 $quotatype = 'custom';
 9002:             }
 9003:         }
 9004:     }
 9005:     if (wantarray) {
 9006:         return ($quota,$quotatype,$settingstatus,$defquota);
 9007:     } else {
 9008:         return $quota;
 9009:     }
 9010: }
 9011: 
 9012: ###############################################
 9013: 
 9014: =pod
 9015: 
 9016: =item * &default_quota()
 9017: 
 9018: Retrieves default quota assigned for storage of user portfolio files,
 9019: given an (optional) user's institutional status.
 9020: 
 9021: Incoming parameters:
 9022: 
 9023: 1. domain
 9024: 2. (Optional) institutional status(es).  This is a : separated list of 
 9025:    status types (e.g., faculty, staff, student etc.)
 9026:    which apply to the user for whom the default is being retrieved.
 9027:    If the institutional status string in undefined, the domain
 9028:    default quota will be returned.
 9029: 3.  quota name - portfolio, author, or course
 9030:    (if no quota name provided, defaults to portfolio).
 9031: 
 9032: Returns:
 9033: 
 9034: 1. Default disk quota (in MB) for user portfolios in the domain.
 9035: 2. (Optional) institutional type which determined the value of the
 9036:    default quota.
 9037: 
 9038: If a value has been stored in the domain's configuration db,
 9039: it will return that, otherwise it returns 20 (for backwards 
 9040: compatibility with domains which have not set up a configuration
 9041: db file; the original statically defined portfolio quota was 20 MB). 
 9042: 
 9043: If the user's status includes multiple types (e.g., staff and student),
 9044: the largest default quota which applies to the user determines the
 9045: default quota returned.
 9046: 
 9047: =cut
 9048: 
 9049: ###############################################
 9050: 
 9051: 
 9052: sub default_quota {
 9053:     my ($udom,$inststatus,$quotaname) = @_;
 9054:     my ($defquota,$settingstatus);
 9055:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9056:                                             ['quotas'],$udom);
 9057:     my $key = 'defaultquota';
 9058:     if ($quotaname eq 'author') {
 9059:         $key = 'authorquota';
 9060:     }
 9061:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9062:         if ($inststatus ne '') {
 9063:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9064:             foreach my $item (@statuses) {
 9065:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9066:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9067:                         if ($defquota eq '') {
 9068:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9069:                             $settingstatus = $item;
 9070:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9071:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9072:                             $settingstatus = $item;
 9073:                         }
 9074:                     }
 9075:                 } elsif ($key eq 'defaultquota') {
 9076:                     if ($quotahash{'quotas'}{$item} ne '') {
 9077:                         if ($defquota eq '') {
 9078:                             $defquota = $quotahash{'quotas'}{$item};
 9079:                             $settingstatus = $item;
 9080:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9081:                             $defquota = $quotahash{'quotas'}{$item};
 9082:                             $settingstatus = $item;
 9083:                         }
 9084:                     }
 9085:                 }
 9086:             }
 9087:         }
 9088:         if ($defquota eq '') {
 9089:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9090:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9091:             } elsif ($key eq 'defaultquota') {
 9092:                 $defquota = $quotahash{'quotas'}{'default'};
 9093:             }
 9094:             $settingstatus = 'default';
 9095:             if ($defquota eq '') {
 9096:                 if ($quotaname eq 'author') {
 9097:                     $defquota = 500;
 9098:                 }
 9099:             }
 9100:         }
 9101:     } else {
 9102:         $settingstatus = 'default';
 9103:         if ($quotaname eq 'author') {
 9104:             $defquota = 500;
 9105:         } else {
 9106:             $defquota = 20;
 9107:         }
 9108:     }
 9109:     if (wantarray) {
 9110:         return ($defquota,$settingstatus);
 9111:     } else {
 9112:         return $defquota;
 9113:     }
 9114: }
 9115: 
 9116: ###############################################
 9117: 
 9118: =pod
 9119: 
 9120: =item * &excess_filesize_warning()
 9121: 
 9122: Returns warning message if upload of file to authoring space, or copying
 9123: of existing file within authoring space will cause quota for the authoring
 9124: space to be exceeded.
 9125: 
 9126: Same, if upload of a file directly to a course/community via Course Editor
 9127: will cause quota for uploaded content for the course to be exceeded.
 9128: 
 9129: Inputs: 7 
 9130: 1. username or coursenum
 9131: 2. domain
 9132: 3. context ('author' or 'course')
 9133: 4. filename of file for which action is being requested
 9134: 5. filesize (kB) of file
 9135: 6. action being taken: copy or upload.
 9136: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9137: 
 9138: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9139:          otherwise return null.
 9140: 
 9141: =back
 9142: 
 9143: =cut
 9144: 
 9145: sub excess_filesize_warning {
 9146:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9147:     my $current_disk_usage = 0;
 9148:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9149:     if ($context eq 'author') {
 9150:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9151:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9152:     } else {
 9153:         foreach my $subdir ('docs','supplemental') {
 9154:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9155:         }
 9156:     }
 9157:     $disk_quota = int($disk_quota * 1000);
 9158:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9159:         return '<p class="LC_warning">'.
 9160:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9161:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9162:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9163:                             $disk_quota,$current_disk_usage).
 9164:                '</p>';
 9165:     }
 9166:     return;
 9167: }
 9168: 
 9169: ###############################################
 9170: 
 9171: 
 9172: sub get_secgrprole_info {
 9173:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9174:     my %sections_count = &get_sections($cdom,$cnum);
 9175:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9176:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9177:     my @groups = sort(keys(%curr_groups));
 9178:     my $allroles = [];
 9179:     my $rolehash;
 9180:     my $accesshash = {
 9181:                      active => 'Currently has access',
 9182:                      future => 'Will have future access',
 9183:                      previous => 'Previously had access',
 9184:                   };
 9185:     if ($needroles) {
 9186:         $rolehash = {'all' => 'all'};
 9187:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9188: 	if (&Apache::lonnet::error(%user_roles)) {
 9189: 	    undef(%user_roles);
 9190: 	}
 9191:         foreach my $item (keys(%user_roles)) {
 9192:             my ($role)=split(/\:/,$item,2);
 9193:             if ($role eq 'cr') { next; }
 9194:             if ($role =~ /^cr/) {
 9195:                 $$rolehash{$role} = (split('/',$role))[3];
 9196:             } else {
 9197:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9198:             }
 9199:         }
 9200:         foreach my $key (sort(keys(%{$rolehash}))) {
 9201:             push(@{$allroles},$key);
 9202:         }
 9203:         push (@{$allroles},'st');
 9204:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9205:     }
 9206:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9207: }
 9208: 
 9209: sub user_picker {
 9210:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9211:     my $currdom = $dom;
 9212:     my %curr_selected = (
 9213:                         srchin => 'dom',
 9214:                         srchby => 'lastname',
 9215:                       );
 9216:     my $srchterm;
 9217:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9218:         if ($srch->{'srchby'} ne '') {
 9219:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9220:         }
 9221:         if ($srch->{'srchin'} ne '') {
 9222:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9223:         }
 9224:         if ($srch->{'srchtype'} ne '') {
 9225:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9226:         }
 9227:         if ($srch->{'srchdomain'} ne '') {
 9228:             $currdom = $srch->{'srchdomain'};
 9229:         }
 9230:         $srchterm = $srch->{'srchterm'};
 9231:     }
 9232:     my %html_lt=&Apache::lonlocal::texthash(
 9233:                     'usr'       => 'Search criteria',
 9234:                     'doma'      => 'Domain/institution to search',
 9235:                     'uname'     => 'username',
 9236:                     'lastname'  => 'last name',
 9237:                     'lastfirst' => 'last name, first name',
 9238:                     'crs'       => 'in this course',
 9239:                     'dom'       => 'in selected LON-CAPA domain', 
 9240:                     'alc'       => 'all LON-CAPA',
 9241:                     'instd'     => 'in institutional directory for selected domain',
 9242:                     'exact'     => 'is',
 9243:                     'contains'  => 'contains',
 9244:                     'begins'    => 'begins with',
 9245:                                        );
 9246:     my %js_lt=&Apache::lonlocal::texthash(
 9247:                     'youm'      => "You must include some text to search for.",
 9248:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9249:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9250:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9251:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9252:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9253:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9254:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9255:                                        );
 9256:     &html_escape(\%html_lt);
 9257:     &js_escape(\%js_lt);
 9258:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9259:     my $srchinsel = ' <select name="srchin">';
 9260: 
 9261:     my @srchins = ('crs','dom','alc','instd');
 9262: 
 9263:     foreach my $option (@srchins) {
 9264:         # FIXME 'alc' option unavailable until 
 9265:         #       loncreateuser::print_user_query_page()
 9266:         #       has been completed.
 9267:         next if ($option eq 'alc');
 9268:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9269:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9270:         if ($curr_selected{'srchin'} eq $option) {
 9271:             $srchinsel .= ' 
 9272:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9273:         } else {
 9274:             $srchinsel .= '
 9275:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9276:         }
 9277:     }
 9278:     $srchinsel .= "\n  </select>\n";
 9279: 
 9280:     my $srchbysel =  ' <select name="srchby">';
 9281:     foreach my $option ('lastname','lastfirst','uname') {
 9282:         if ($curr_selected{'srchby'} eq $option) {
 9283:             $srchbysel .= '
 9284:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9285:         } else {
 9286:             $srchbysel .= '
 9287:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9288:          }
 9289:     }
 9290:     $srchbysel .= "\n  </select>\n";
 9291: 
 9292:     my $srchtypesel = ' <select name="srchtype">';
 9293:     foreach my $option ('begins','contains','exact') {
 9294:         if ($curr_selected{'srchtype'} eq $option) {
 9295:             $srchtypesel .= '
 9296:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9297:         } else {
 9298:             $srchtypesel .= '
 9299:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9300:         }
 9301:     }
 9302:     $srchtypesel .= "\n  </select>\n";
 9303: 
 9304:     my ($newuserscript,$new_user_create);
 9305:     my $context_dom = $env{'request.role.domain'};
 9306:     if ($context eq 'requestcrs') {
 9307:         if ($env{'form.coursedom'} ne '') { 
 9308:             $context_dom = $env{'form.coursedom'};
 9309:         }
 9310:     }
 9311:     if ($forcenewuser) {
 9312:         if (ref($srch) eq 'HASH') {
 9313:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9314:                 if ($cancreate) {
 9315:                     $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>';
 9316:                 } else {
 9317:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9318:                     my %usertypetext = (
 9319:                         official   => 'institutional',
 9320:                         unofficial => 'non-institutional',
 9321:                     );
 9322:                     $new_user_create = '<p class="LC_warning">'
 9323:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9324:                                       .' '
 9325:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9326:                                           ,'<a href="'.$helplink.'">','</a>')
 9327:                                       .'</p><br />';
 9328:                 }
 9329:             }
 9330:         }
 9331: 
 9332:         $newuserscript = <<"ENDSCRIPT";
 9333: 
 9334: function setSearch(createnew,callingForm) {
 9335:     if (createnew == 1) {
 9336:         for (var i=0; i<callingForm.srchby.length; i++) {
 9337:             if (callingForm.srchby.options[i].value == 'uname') {
 9338:                 callingForm.srchby.selectedIndex = i;
 9339:             }
 9340:         }
 9341:         for (var i=0; i<callingForm.srchin.length; i++) {
 9342:             if ( callingForm.srchin.options[i].value == 'dom') {
 9343: 		callingForm.srchin.selectedIndex = i;
 9344:             }
 9345:         }
 9346:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9347:             if (callingForm.srchtype.options[i].value == 'exact') {
 9348:                 callingForm.srchtype.selectedIndex = i;
 9349:             }
 9350:         }
 9351:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9352:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9353:                 callingForm.srchdomain.selectedIndex = i;
 9354:             }
 9355:         }
 9356:     }
 9357: }
 9358: ENDSCRIPT
 9359: 
 9360:     }
 9361: 
 9362:     my $output = <<"END_BLOCK";
 9363: <script type="text/javascript">
 9364: // <![CDATA[
 9365: function validateEntry(callingForm) {
 9366: 
 9367:     var checkok = 1;
 9368:     var srchin;
 9369:     for (var i=0; i<callingForm.srchin.length; i++) {
 9370: 	if ( callingForm.srchin[i].checked ) {
 9371: 	    srchin = callingForm.srchin[i].value;
 9372: 	}
 9373:     }
 9374: 
 9375:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9376:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9377:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9378:     var srchterm =  callingForm.srchterm.value;
 9379:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9380:     var msg = "";
 9381: 
 9382:     if (srchterm == "") {
 9383:         checkok = 0;
 9384:         msg += "$js_lt{'youm'}\\n";
 9385:     }
 9386: 
 9387:     if (srchtype== 'begins') {
 9388:         if (srchterm.length < 2) {
 9389:             checkok = 0;
 9390:             msg += "$js_lt{'thte'}\\n";
 9391:         }
 9392:     }
 9393: 
 9394:     if (srchtype== 'contains') {
 9395:         if (srchterm.length < 3) {
 9396:             checkok = 0;
 9397:             msg += "$js_lt{'thet'}\\n";
 9398:         }
 9399:     }
 9400:     if (srchin == 'instd') {
 9401:         if (srchdomain == '') {
 9402:             checkok = 0;
 9403:             msg += "$js_lt{'yomc'}\\n";
 9404:         }
 9405:     }
 9406:     if (srchin == 'dom') {
 9407:         if (srchdomain == '') {
 9408:             checkok = 0;
 9409:             msg += "$js_lt{'ymcd'}\\n";
 9410:         }
 9411:     }
 9412:     if (srchby == 'lastfirst') {
 9413:         if (srchterm.indexOf(",") == -1) {
 9414:             checkok = 0;
 9415:             msg += "$js_lt{'whus'}\\n";
 9416:         }
 9417:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9418:             checkok = 0;
 9419:             msg += "$js_lt{'whse'}\\n";
 9420:         }
 9421:     }
 9422:     if (checkok == 0) {
 9423:         alert("$js_lt{'thfo'}\\n"+msg);
 9424:         return;
 9425:     }
 9426:     if (checkok == 1) {
 9427:         callingForm.submit();
 9428:     }
 9429: }
 9430: 
 9431: $newuserscript
 9432: 
 9433: // ]]>
 9434: </script>
 9435: 
 9436: $new_user_create
 9437: 
 9438: END_BLOCK
 9439: 
 9440:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9441:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9442:                $domform.
 9443:                &Apache::lonhtmlcommon::row_closure().
 9444:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9445:                $srchbysel.
 9446:                $srchtypesel. 
 9447:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9448:                $srchinsel.
 9449:                &Apache::lonhtmlcommon::row_closure(1). 
 9450:                &Apache::lonhtmlcommon::end_pick_box().
 9451:                '<br />';
 9452:     return $output;
 9453: }
 9454: 
 9455: sub user_rule_check {
 9456:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9457:     my ($response,%inst_response);
 9458:     if (ref($usershash) eq 'HASH') {
 9459:         if (keys(%{$usershash}) > 1) {
 9460:             my (%by_username,%by_id,%userdoms);
 9461:             my $checkid;
 9462:             if (ref($checks) eq 'HASH') {
 9463:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9464:                     $checkid = 1;
 9465:                 }
 9466:             }
 9467:             foreach my $user (keys(%{$usershash})) {
 9468:                 my ($uname,$udom) = split(/:/,$user);
 9469:                 if ($checkid) {
 9470:                     if (ref($usershash->{$user}) eq 'HASH') {
 9471:                         if ($usershash->{$user}->{'id'} ne '') {
 9472:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
 9473:                             $userdoms{$udom} = 1;
 9474:                             if (ref($inst_results) eq 'HASH') {
 9475:                                 $inst_results->{$uname.':'.$udom} = {};
 9476:                             }
 9477:                         }
 9478:                     }
 9479:                 } else {
 9480:                     $by_username{$udom}{$uname} = 1;
 9481:                     $userdoms{$udom} = 1;
 9482:                     if (ref($inst_results) eq 'HASH') {
 9483:                         $inst_results->{$uname.':'.$udom} = {};
 9484:                     }
 9485:                 }
 9486:             }
 9487:             foreach my $udom (keys(%userdoms)) {
 9488:                 if (!$got_rules->{$udom}) {
 9489:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9490:                                                              ['usercreation'],$udom);
 9491:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9492:                         foreach my $item ('username','id') {
 9493:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9494:                                 $$curr_rules{$udom}{$item} =
 9495:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9496:                             }
 9497:                         }
 9498:                     }
 9499:                     $got_rules->{$udom} = 1;
 9500:                 }
 9501:             }
 9502:             if ($checkid) {
 9503:                 foreach my $udom (keys(%by_id)) {
 9504:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9505:                     if ($outcome eq 'ok') {
 9506:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9507:                             my $uname = $by_id{$udom}{$id};
 9508:                             $inst_response{$uname.':'.$udom} = $outcome;
 9509:                         }
 9510:                         if (ref($results) eq 'HASH') {
 9511:                             foreach my $uname (keys(%{$results})) {
 9512:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9513:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9514:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9515:                                 }
 9516:                             }
 9517:                         }
 9518:                     }
 9519:                 }
 9520:             } else {
 9521:                 foreach my $udom (keys(%by_username)) {
 9522:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
 9523:                     if ($outcome eq 'ok') {
 9524:                         foreach my $uname (keys(%{$by_username{$udom}})) {
 9525:                             $inst_response{$uname.':'.$udom} = $outcome;
 9526:                         }
 9527:                         if (ref($results) eq 'HASH') {
 9528:                             foreach my $uname (keys(%{$results})) {
 9529:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9530:                             }
 9531:                         }
 9532:                     }
 9533:                 }
 9534:             }
 9535:         } elsif (keys(%{$usershash}) == 1) {
 9536:             my $user = (keys(%{$usershash}))[0];
 9537:             my ($uname,$udom) = split(/:/,$user);
 9538:             if (($udom ne '') && ($uname ne '')) {
 9539:                 if (ref($usershash->{$user}) eq 'HASH') {
 9540:                     if (ref($checks) eq 'HASH') {
 9541:                         if (defined($checks->{'username'})) {
 9542:                             ($inst_response{$user},%{$inst_results->{$user}}) =
 9543:                                 &Apache::lonnet::get_instuser($udom,$uname);
 9544:                         } elsif (defined($checks->{'id'})) {
 9545:                             if ($usershash->{$user}->{'id'} ne '') {
 9546:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9547:                                     &Apache::lonnet::get_instuser($udom,undef,
 9548:                                                                   $usershash->{$user}->{'id'});
 9549:                             } else {
 9550:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9551:                                     &Apache::lonnet::get_instuser($udom,$uname);
 9552:                             }
 9553:                         }
 9554:                     } else {
 9555:                        ($inst_response{$user},%{$inst_results->{$user}}) =
 9556:                             &Apache::lonnet::get_instuser($udom,$uname);
 9557:                        return;
 9558:                     }
 9559:                     if (!$got_rules->{$udom}) {
 9560:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
 9561:                                                                  ['usercreation'],$udom);
 9562:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9563:                             foreach my $item ('username','id') {
 9564:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9565:                                    $$curr_rules{$udom}{$item} =
 9566:                                        $domconfig{'usercreation'}{$item.'_rule'};
 9567:                                 }
 9568:                             }
 9569:                         }
 9570:                         $got_rules->{$udom} = 1;
 9571:                     }
 9572:                 }
 9573:             } else {
 9574:                 return;
 9575:             }
 9576:         } else {
 9577:             return;
 9578:         }
 9579:         foreach my $user (keys(%{$usershash})) {
 9580:             my ($uname,$udom) = split(/:/,$user);
 9581:             next if (($udom eq '') || ($uname eq ''));
 9582:             my $id;
 9583:             if (ref($inst_results) eq 'HASH') {
 9584:                 if (ref($inst_results->{$user}) eq 'HASH') {
 9585:                     $id = $inst_results->{$user}->{'id'};
 9586:                 }
 9587:             }
 9588:             if ($id eq '') {
 9589:                 if (ref($usershash->{$user})) {
 9590:                     $id = $usershash->{$user}->{'id'};
 9591:                 }
 9592:             }
 9593:             foreach my $item (keys(%{$checks})) {
 9594:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9595:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9596:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9597:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
 9598:                                                                              $$curr_rules{$udom}{$item});
 9599:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9600:                                 if ($rule_check{$rule}) {
 9601:                                     $$rulematch{$user}{$item} = $rule;
 9602:                                     if ($inst_response{$user} eq 'ok') {
 9603:                                         if (ref($inst_results) eq 'HASH') {
 9604:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9605:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9606:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9607:                                                 } elsif ($item eq 'id') {
 9608:                                                     if ($inst_results->{$user}->{'id'} eq '') {
 9609:                                                         $$alerts{$item}{$udom}{$uname} = 1;
 9610:                                                     }
 9611:                                                 }
 9612:                                             }
 9613:                                         }
 9614:                                     }
 9615:                                     last;
 9616:                                 }
 9617:                             }
 9618:                         }
 9619:                     }
 9620:                 }
 9621:             }
 9622:         }
 9623:     }
 9624:     return;
 9625: }
 9626: 
 9627: sub user_rule_formats {
 9628:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9629:     my %text = ( 
 9630:                  'username' => 'Usernames',
 9631:                  'id'       => 'IDs',
 9632:                );
 9633:     my $output;
 9634:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9635:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9636:         if (@{$ruleorder} > 0) {
 9637:             $output = '<br />'.
 9638:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9639:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9640:                       ' <ul>';
 9641:             foreach my $rule (@{$ruleorder}) {
 9642:                 if (ref($curr_rules) eq 'ARRAY') {
 9643:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9644:                         if (ref($rules->{$rule}) eq 'HASH') {
 9645:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9646:                                         $rules->{$rule}{'desc'}.'</li>';
 9647:                         }
 9648:                     }
 9649:                 }
 9650:             }
 9651:             $output .= '</ul>';
 9652:         }
 9653:     }
 9654:     return $output;
 9655: }
 9656: 
 9657: sub instrule_disallow_msg {
 9658:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9659:     my $response;
 9660:     my %text = (
 9661:                   item   => 'username',
 9662:                   items  => 'usernames',
 9663:                   match  => 'matches',
 9664:                   do     => 'does',
 9665:                   action => 'a username',
 9666:                   one    => 'one',
 9667:                );
 9668:     if ($count > 1) {
 9669:         $text{'item'} = 'usernames';
 9670:         $text{'match'} ='match';
 9671:         $text{'do'} = 'do';
 9672:         $text{'action'} = 'usernames',
 9673:         $text{'one'} = 'ones';
 9674:     }
 9675:     if ($checkitem eq 'id') {
 9676:         $text{'items'} = 'IDs';
 9677:         $text{'item'} = 'ID';
 9678:         $text{'action'} = 'an ID';
 9679:         if ($count > 1) {
 9680:             $text{'item'} = 'IDs';
 9681:             $text{'action'} = 'IDs';
 9682:         }
 9683:     }
 9684:     $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 />';
 9685:     if ($mode eq 'upload') {
 9686:         if ($checkitem eq 'username') {
 9687:             $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'}.");
 9688:         } elsif ($checkitem eq 'id') {
 9689:             $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.");
 9690:         }
 9691:     } elsif ($mode eq 'selfcreate') {
 9692:         if ($checkitem eq 'id') {
 9693:             $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.");
 9694:         }
 9695:     } else {
 9696:         if ($checkitem eq 'username') {
 9697:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9698:         } elsif ($checkitem eq 'id') {
 9699:             $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.");
 9700:         }
 9701:     }
 9702:     return $response;
 9703: }
 9704: 
 9705: sub personal_data_fieldtitles {
 9706:     my %fieldtitles = &Apache::lonlocal::texthash (
 9707:                         id => 'Student/Employee ID',
 9708:                         permanentemail => 'E-mail address',
 9709:                         lastname => 'Last Name',
 9710:                         firstname => 'First Name',
 9711:                         middlename => 'Middle Name',
 9712:                         generation => 'Generation',
 9713:                         gen => 'Generation',
 9714:                         inststatus => 'Affiliation',
 9715:                    );
 9716:     return %fieldtitles;
 9717: }
 9718: 
 9719: sub sorted_inst_types {
 9720:     my ($dom) = @_;
 9721:     my ($usertypes,$order);
 9722:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9723:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
 9724:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
 9725:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
 9726:     } else {
 9727:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9728:     }
 9729:     my $othertitle = &mt('All users');
 9730:     if ($env{'request.course.id'}) {
 9731:         $othertitle  = &mt('Any users');
 9732:     }
 9733:     my @types;
 9734:     if (ref($order) eq 'ARRAY') {
 9735:         @types = @{$order};
 9736:     }
 9737:     if (@types == 0) {
 9738:         if (ref($usertypes) eq 'HASH') {
 9739:             @types = sort(keys(%{$usertypes}));
 9740:         }
 9741:     }
 9742:     if (keys(%{$usertypes}) > 0) {
 9743:         $othertitle = &mt('Other users');
 9744:     }
 9745:     return ($othertitle,$usertypes,\@types);
 9746: }
 9747: 
 9748: sub get_institutional_codes {
 9749:     my ($settings,$allcourses,$LC_code) = @_;
 9750: # Get complete list of course sections to update
 9751:     my @currsections = ();
 9752:     my @currxlists = ();
 9753:     my $coursecode = $$settings{'internal.coursecode'};
 9754: 
 9755:     if ($$settings{'internal.sectionnums'} ne '') {
 9756:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9757:     }
 9758: 
 9759:     if ($$settings{'internal.crosslistings'} ne '') {
 9760:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9761:     }
 9762: 
 9763:     if (@currxlists > 0) {
 9764:         foreach (@currxlists) {
 9765:             if (m/^([^:]+):(\w*)$/) {
 9766:                 unless (grep/^$1$/,@{$allcourses}) {
 9767:                     push @{$allcourses},$1;
 9768:                     $$LC_code{$1} = $2;
 9769:                 }
 9770:             }
 9771:         }
 9772:     }
 9773:  
 9774:     if (@currsections > 0) {
 9775:         foreach (@currsections) {
 9776:             if (m/^(\w+):(\w*)$/) {
 9777:                 my $sec = $coursecode.$1;
 9778:                 my $lc_sec = $2;
 9779:                 unless (grep/^$sec$/,@{$allcourses}) {
 9780:                     push @{$allcourses},$sec;
 9781:                     $$LC_code{$sec} = $lc_sec;
 9782:                 }
 9783:             }
 9784:         }
 9785:     }
 9786:     return;
 9787: }
 9788: 
 9789: sub get_standard_codeitems {
 9790:     return ('Year','Semester','Department','Number','Section');
 9791: }
 9792: 
 9793: =pod
 9794: 
 9795: =head1 Slot Helpers
 9796: 
 9797: =over 4
 9798: 
 9799: =item * sorted_slots()
 9800: 
 9801: Sorts an array of slot names in order of an optional sort key,
 9802: default sort is by slot start time (earliest first). 
 9803: 
 9804: Inputs:
 9805: 
 9806: =over 4
 9807: 
 9808: slotsarr  - Reference to array of unsorted slot names.
 9809: 
 9810: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9811: 
 9812: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9813: 
 9814: =back
 9815: 
 9816: Returns:
 9817: 
 9818: =over 4
 9819: 
 9820: sorted   - An array of slot names sorted by a specified sort key 
 9821:            (default sort key is start time of the slot).
 9822: 
 9823: =back
 9824: 
 9825: =cut
 9826: 
 9827: 
 9828: sub sorted_slots {
 9829:     my ($slotsarr,$slots,$sortkey) = @_;
 9830:     if ($sortkey eq '') {
 9831:         $sortkey = 'starttime';
 9832:     }
 9833:     my @sorted;
 9834:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9835:         @sorted =
 9836:             sort {
 9837:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9838:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9839:                      }
 9840:                      if (ref($slots->{$a})) { return -1;}
 9841:                      if (ref($slots->{$b})) { return 1;}
 9842:                      return 0;
 9843:                  } @{$slotsarr};
 9844:     }
 9845:     return @sorted;
 9846: }
 9847: 
 9848: =pod
 9849: 
 9850: =item * get_future_slots()
 9851: 
 9852: Inputs:
 9853: 
 9854: =over 4
 9855: 
 9856: cnum - course number
 9857: 
 9858: cdom - course domain
 9859: 
 9860: now - current UNIX time
 9861: 
 9862: symb - optional symb
 9863: 
 9864: =back
 9865: 
 9866: Returns:
 9867: 
 9868: =over 4
 9869: 
 9870: sorted_reservable - ref to array of student_schedulable slots currently 
 9871:                     reservable, ordered by end date of reservation period.
 9872: 
 9873: reservable_now - ref to hash of student_schedulable slots currently
 9874:                  reservable.
 9875: 
 9876:     Keys in inner hash are:
 9877:     (a) symb: either blank or symb to which slot use is restricted.
 9878:     (b) endreserve: end date of reservation period. 
 9879: 
 9880: sorted_future - ref to array of student_schedulable slots reservable in
 9881:                 the future, ordered by start date of reservation period.
 9882: 
 9883: future_reservable - ref to hash of student_schedulable slots reservable
 9884:                     in the future.
 9885: 
 9886:     Keys in inner hash are:
 9887:     (a) symb: either blank or symb to which slot use is restricted.
 9888:     (b) startreserve:  start date of reservation period.
 9889: 
 9890: =back
 9891: 
 9892: =cut
 9893: 
 9894: sub get_future_slots {
 9895:     my ($cnum,$cdom,$now,$symb) = @_;
 9896:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9897:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9898:     foreach my $slot (keys(%slots)) {
 9899:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9900:         if ($symb) {
 9901:             next if (($slots{$slot}->{'symb'} ne '') && 
 9902:                      ($slots{$slot}->{'symb'} ne $symb));
 9903:         }
 9904:         if (($slots{$slot}->{'starttime'} > $now) &&
 9905:             ($slots{$slot}->{'endtime'} > $now)) {
 9906:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9907:                 my $userallowed = 0;
 9908:                 if ($slots{$slot}->{'allowedsections'}) {
 9909:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9910:                     if (!defined($env{'request.role.sec'})
 9911:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9912:                         $userallowed=1;
 9913:                     } else {
 9914:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9915:                             $userallowed=1;
 9916:                         }
 9917:                     }
 9918:                     unless ($userallowed) {
 9919:                         if (defined($env{'request.course.groups'})) {
 9920:                             my @groups = split(/:/,$env{'request.course.groups'});
 9921:                             foreach my $group (@groups) {
 9922:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9923:                                     $userallowed=1;
 9924:                                     last;
 9925:                                 }
 9926:                             }
 9927:                         }
 9928:                     }
 9929:                 }
 9930:                 if ($slots{$slot}->{'allowedusers'}) {
 9931:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9932:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9933:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9934:                         $userallowed = 1;
 9935:                     }
 9936:                 }
 9937:                 next unless($userallowed);
 9938:             }
 9939:             my $startreserve = $slots{$slot}->{'startreserve'};
 9940:             my $endreserve = $slots{$slot}->{'endreserve'};
 9941:             my $symb = $slots{$slot}->{'symb'};
 9942:             if (($startreserve < $now) &&
 9943:                 (!$endreserve || $endreserve > $now)) {
 9944:                 my $lastres = $endreserve;
 9945:                 if (!$lastres) {
 9946:                     $lastres = $slots{$slot}->{'starttime'};
 9947:                 }
 9948:                 $reservable_now{$slot} = {
 9949:                                            symb       => $symb,
 9950:                                            endreserve => $lastres
 9951:                                          };
 9952:             } elsif (($startreserve > $now) &&
 9953:                      (!$endreserve || $endreserve > $startreserve)) {
 9954:                 $future_reservable{$slot} = {
 9955:                                               symb         => $symb,
 9956:                                               startreserve => $startreserve
 9957:                                             };
 9958:             }
 9959:         }
 9960:     }
 9961:     my @unsorted_reservable = keys(%reservable_now);
 9962:     if (@unsorted_reservable > 0) {
 9963:         @sorted_reservable = 
 9964:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9965:     }
 9966:     my @unsorted_future = keys(%future_reservable);
 9967:     if (@unsorted_future > 0) {
 9968:         @sorted_future =
 9969:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9970:     }
 9971:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9972: }
 9973: 
 9974: =pod
 9975: 
 9976: =back
 9977: 
 9978: =head1 HTTP Helpers
 9979: 
 9980: =over 4
 9981: 
 9982: =item * &get_unprocessed_cgi($query,$possible_names)
 9983: 
 9984: Modify the %env hash to contain unprocessed CGI form parameters held in
 9985: $query.  The parameters listed in $possible_names (an array reference),
 9986: will be set in $env{'form.name'} if they do not already exist.
 9987: 
 9988: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9989: $possible_names is an ref to an array of form element names.  As an example:
 9990: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9991: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9992: 
 9993: =cut
 9994: 
 9995: sub get_unprocessed_cgi {
 9996:   my ($query,$possible_names)= @_;
 9997:   # $Apache::lonxml::debug=1;
 9998:   foreach my $pair (split(/&/,$query)) {
 9999:     my ($name, $value) = split(/=/,$pair);
10000:     $name = &unescape($name);
10001:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10002:       $value =~ tr/+/ /;
10003:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10004:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10005:     }
10006:   }
10007: }
10008: 
10009: =pod
10010: 
10011: =item * &cacheheader() 
10012: 
10013: returns cache-controlling header code
10014: 
10015: =cut
10016: 
10017: sub cacheheader {
10018:     unless ($env{'request.method'} eq 'GET') { return ''; }
10019:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10020:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10021:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10022:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10023:     return $output;
10024: }
10025: 
10026: =pod
10027: 
10028: =item * &no_cache($r) 
10029: 
10030: specifies header code to not have cache
10031: 
10032: =cut
10033: 
10034: sub no_cache {
10035:     my ($r) = @_;
10036:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10037: 	$env{'request.method'} ne 'GET') { return ''; }
10038:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10039:     $r->no_cache(1);
10040:     $r->header_out("Expires" => $date);
10041:     $r->header_out("Pragma" => "no-cache");
10042: }
10043: 
10044: sub content_type {
10045:     my ($r,$type,$charset) = @_;
10046:     if ($r) {
10047: 	#  Note that printout.pl calls this with undef for $r.
10048: 	&no_cache($r);
10049:     }
10050:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10051:     unless ($charset) {
10052: 	$charset=&Apache::lonlocal::current_encoding;
10053:     }
10054:     if ($charset) { $type.='; charset='.$charset; }
10055:     if ($r) {
10056: 	$r->content_type($type);
10057:     } else {
10058: 	print("Content-type: $type\n\n");
10059:     }
10060: }
10061: 
10062: =pod
10063: 
10064: =item * &add_to_env($name,$value) 
10065: 
10066: adds $name to the %env hash with value
10067: $value, if $name already exists, the entry is converted to an array
10068: reference and $value is added to the array.
10069: 
10070: =cut
10071: 
10072: sub add_to_env {
10073:   my ($name,$value)=@_;
10074:   if (defined($env{$name})) {
10075:     if (ref($env{$name})) {
10076:       #already have multiple values
10077:       push(@{ $env{$name} },$value);
10078:     } else {
10079:       #first time seeing multiple values, convert hash entry to an arrayref
10080:       my $first=$env{$name};
10081:       undef($env{$name});
10082:       push(@{ $env{$name} },$first,$value);
10083:     }
10084:   } else {
10085:     $env{$name}=$value;
10086:   }
10087: }
10088: 
10089: =pod
10090: 
10091: =item * &get_env_multiple($name) 
10092: 
10093: gets $name from the %env hash, it seemlessly handles the cases where multiple
10094: values may be defined and end up as an array ref.
10095: 
10096: returns an array of values
10097: 
10098: =cut
10099: 
10100: sub get_env_multiple {
10101:     my ($name) = @_;
10102:     my @values;
10103:     if (defined($env{$name})) {
10104:         # exists is it an array
10105:         if (ref($env{$name})) {
10106:             @values=@{ $env{$name} };
10107:         } else {
10108:             $values[0]=$env{$name};
10109:         }
10110:     }
10111:     return(@values);
10112: }
10113: 
10114: sub ask_for_embedded_content {
10115:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10116:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10117:         %currsubfile,%unused,$rem);
10118:     my $counter = 0;
10119:     my $numnew = 0;
10120:     my $numremref = 0;
10121:     my $numinvalid = 0;
10122:     my $numpathchg = 0;
10123:     my $numexisting = 0;
10124:     my $numunused = 0;
10125:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10126:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10127:     my $heading = &mt('Upload embedded files');
10128:     my $buttontext = &mt('Upload');
10129: 
10130:     if ($env{'request.course.id'}) {
10131:         if ($actionurl eq '/adm/dependencies') {
10132:             $navmap = Apache::lonnavmaps::navmap->new();
10133:         }
10134:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10135:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10136:     }
10137:     if (($actionurl eq '/adm/portfolio') ||
10138:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10139:         my $current_path='/';
10140:         if ($env{'form.currentpath'}) {
10141:             $current_path = $env{'form.currentpath'};
10142:         }
10143:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10144:             $udom = $cdom;
10145:             $uname = $cnum;
10146:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10147:         } else {
10148:             $udom = $env{'user.domain'};
10149:             $uname = $env{'user.name'};
10150:             $url = '/userfiles/portfolio';
10151:         }
10152:         $toplevel = $url.'/';
10153:         $url .= $current_path;
10154:         $getpropath = 1;
10155:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10156:              ($actionurl eq '/adm/imsimport')) { 
10157:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10158:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10159:         $toplevel = $url;
10160:         if ($rest ne '') {
10161:             $url .= $rest;
10162:         }
10163:     } elsif ($actionurl eq '/adm/coursedocs') {
10164:         if (ref($args) eq 'HASH') {
10165:             $url = $args->{'docs_url'};
10166:             $toplevel = $url;
10167:             if ($args->{'context'} eq 'paste') {
10168:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10169:                 ($path) =
10170:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10171:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10172:                 $fileloc =~ s{^/}{};
10173:             }
10174:         }
10175:     } elsif ($actionurl eq '/adm/dependencies') {
10176:         if ($env{'request.course.id'} ne '') {
10177:             if (ref($args) eq 'HASH') {
10178:                 $url = $args->{'docs_url'};
10179:                 $title = $args->{'docs_title'};
10180:                 $toplevel = $url;
10181:                 unless ($toplevel =~ m{^/}) {
10182:                     $toplevel = "/$url";
10183:                 }
10184:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10185:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10186:                     $path = $1;
10187:                 } else {
10188:                     ($path) =
10189:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10190:                 }
10191:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10192:                     $fileloc = $toplevel;
10193:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10194:                     my ($udom,$uname,$fname) =
10195:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10196:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10197:                 } else {
10198:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10199:                 }
10200:                 $fileloc =~ s{^/}{};
10201:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10202:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10203:             }
10204:         }
10205:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10206:         $udom = $cdom;
10207:         $uname = $cnum;
10208:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10209:         $toplevel = $url;
10210:         $path = $url;
10211:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10212:         $fileloc =~ s{^/}{};
10213:     }
10214:     foreach my $file (keys(%{$allfiles})) {
10215:         my $embed_file;
10216:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10217:             $embed_file = $1;
10218:         } else {
10219:             $embed_file = $file;
10220:         }
10221:         my ($absolutepath,$cleaned_file);
10222:         if ($embed_file =~ m{^\w+://}) {
10223:             $cleaned_file = $embed_file;
10224:             $newfiles{$cleaned_file} = 1;
10225:             $mapping{$cleaned_file} = $embed_file;
10226:         } else {
10227:             $cleaned_file = &clean_path($embed_file);
10228:             if ($embed_file =~ m{^/}) {
10229:                 $absolutepath = $embed_file;
10230:             }
10231:             if ($cleaned_file =~ m{/}) {
10232:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10233:                 $path = &check_for_traversal($path,$url,$toplevel);
10234:                 my $item = $fname;
10235:                 if ($path ne '') {
10236:                     $item = $path.'/'.$fname;
10237:                     $subdependencies{$path}{$fname} = 1;
10238:                 } else {
10239:                     $dependencies{$item} = 1;
10240:                 }
10241:                 if ($absolutepath) {
10242:                     $mapping{$item} = $absolutepath;
10243:                 } else {
10244:                     $mapping{$item} = $embed_file;
10245:                 }
10246:             } else {
10247:                 $dependencies{$embed_file} = 1;
10248:                 if ($absolutepath) {
10249:                     $mapping{$cleaned_file} = $absolutepath;
10250:                 } else {
10251:                     $mapping{$cleaned_file} = $embed_file;
10252:                 }
10253:             }
10254:         }
10255:     }
10256:     my $dirptr = 16384;
10257:     foreach my $path (keys(%subdependencies)) {
10258:         $currsubfile{$path} = {};
10259:         if (($actionurl eq '/adm/portfolio') ||
10260:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10261:             my ($sublistref,$listerror) =
10262:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10263:             if (ref($sublistref) eq 'ARRAY') {
10264:                 foreach my $line (@{$sublistref}) {
10265:                     my ($file_name,$rest) = split(/\&/,$line,2);
10266:                     $currsubfile{$path}{$file_name} = 1;
10267:                 }
10268:             }
10269:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10270:             if (opendir(my $dir,$url.'/'.$path)) {
10271:                 my @subdir_list = grep(!/^\./,readdir($dir));
10272:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10273:             }
10274:         } elsif (($actionurl eq '/adm/dependencies') ||
10275:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10276:                   ($args->{'context'} eq 'paste')) ||
10277:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10278:             if ($env{'request.course.id'} ne '') {
10279:                 my $dir;
10280:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10281:                     $dir = $fileloc;
10282:                 } else {
10283:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10284:                 }
10285:                 if ($dir ne '') {
10286:                     my ($sublistref,$listerror) =
10287:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10288:                     if (ref($sublistref) eq 'ARRAY') {
10289:                         foreach my $line (@{$sublistref}) {
10290:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10291:                                 undef,$mtime)=split(/\&/,$line,12);
10292:                             unless (($testdir&$dirptr) ||
10293:                                     ($file_name =~ /^\.\.?$/)) {
10294:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10295:                             }
10296:                         }
10297:                     }
10298:                 }
10299:             }
10300:         }
10301:         foreach my $file (keys(%{$subdependencies{$path}})) {
10302:             if (exists($currsubfile{$path}{$file})) {
10303:                 my $item = $path.'/'.$file;
10304:                 unless ($mapping{$item} eq $item) {
10305:                     $pathchanges{$item} = 1;
10306:                 }
10307:                 $existing{$item} = 1;
10308:                 $numexisting ++;
10309:             } else {
10310:                 $newfiles{$path.'/'.$file} = 1;
10311:             }
10312:         }
10313:         if ($actionurl eq '/adm/dependencies') {
10314:             foreach my $path (keys(%currsubfile)) {
10315:                 if (ref($currsubfile{$path}) eq 'HASH') {
10316:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10317:                          unless ($subdependencies{$path}{$file}) {
10318:                              next if (($rem ne '') &&
10319:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10320:                                        (ref($navmap) &&
10321:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10322:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10323:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10324:                              $unused{$path.'/'.$file} = 1; 
10325:                          }
10326:                     }
10327:                 }
10328:             }
10329:         }
10330:     }
10331:     my %currfile;
10332:     if (($actionurl eq '/adm/portfolio') ||
10333:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10334:         my ($dirlistref,$listerror) =
10335:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10336:         if (ref($dirlistref) eq 'ARRAY') {
10337:             foreach my $line (@{$dirlistref}) {
10338:                 my ($file_name,$rest) = split(/\&/,$line,2);
10339:                 $currfile{$file_name} = 1;
10340:             }
10341:         }
10342:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10343:         if (opendir(my $dir,$url)) {
10344:             my @dir_list = grep(!/^\./,readdir($dir));
10345:             map {$currfile{$_} = 1;} @dir_list;
10346:         }
10347:     } elsif (($actionurl eq '/adm/dependencies') ||
10348:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10349:               ($args->{'context'} eq 'paste')) ||
10350:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10351:         if ($env{'request.course.id'} ne '') {
10352:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10353:             if ($dir ne '') {
10354:                 my ($dirlistref,$listerror) =
10355:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10356:                 if (ref($dirlistref) eq 'ARRAY') {
10357:                     foreach my $line (@{$dirlistref}) {
10358:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10359:                             $size,undef,$mtime)=split(/\&/,$line,12);
10360:                         unless (($testdir&$dirptr) ||
10361:                                 ($file_name =~ /^\.\.?$/)) {
10362:                             $currfile{$file_name} = [$size,$mtime];
10363:                         }
10364:                     }
10365:                 }
10366:             }
10367:         }
10368:     }
10369:     foreach my $file (keys(%dependencies)) {
10370:         if (exists($currfile{$file})) {
10371:             unless ($mapping{$file} eq $file) {
10372:                 $pathchanges{$file} = 1;
10373:             }
10374:             $existing{$file} = 1;
10375:             $numexisting ++;
10376:         } else {
10377:             $newfiles{$file} = 1;
10378:         }
10379:     }
10380:     foreach my $file (keys(%currfile)) {
10381:         unless (($file eq $filename) ||
10382:                 ($file eq $filename.'.bak') ||
10383:                 ($dependencies{$file})) {
10384:             if ($actionurl eq '/adm/dependencies') {
10385:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10386:                     next if (($rem ne '') &&
10387:                              (($env{"httpref.$rem".$file} ne '') ||
10388:                               (ref($navmap) &&
10389:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10390:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10391:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10392:                 }
10393:             }
10394:             $unused{$file} = 1;
10395:         }
10396:     }
10397:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10398:         ($args->{'context'} eq 'paste')) {
10399:         $counter = scalar(keys(%existing));
10400:         $numpathchg = scalar(keys(%pathchanges));
10401:         return ($output,$counter,$numpathchg,\%existing);
10402:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10403:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10404:         $counter = scalar(keys(%existing));
10405:         $numpathchg = scalar(keys(%pathchanges));
10406:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10407:     }
10408:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10409:         if ($actionurl eq '/adm/dependencies') {
10410:             next if ($embed_file =~ m{^\w+://});
10411:         }
10412:         $upload_output .= &start_data_table_row().
10413:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10414:                           '<span class="LC_filename">'.$embed_file.'</span>';
10415:         unless ($mapping{$embed_file} eq $embed_file) {
10416:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10417:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10418:         }
10419:         $upload_output .= '</td>';
10420:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10421:             $upload_output.='<td align="right">'.
10422:                             '<span class="LC_info LC_fontsize_medium">'.
10423:                             &mt("URL points to web address").'</span>';
10424:             $numremref++;
10425:         } elsif ($args->{'error_on_invalid_names'}
10426:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10427:             $upload_output.='<td align="right"><span class="LC_warning">'.
10428:                             &mt('Invalid characters').'</span>';
10429:             $numinvalid++;
10430:         } else {
10431:             $upload_output .= '<td>'.
10432:                               &embedded_file_element('upload_embedded',$counter,
10433:                                                      $embed_file,\%mapping,
10434:                                                      $allfiles,$codebase,'upload');
10435:             $counter ++;
10436:             $numnew ++;
10437:         }
10438:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10439:     }
10440:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10441:         if ($actionurl eq '/adm/dependencies') {
10442:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10443:             $modify_output .= &start_data_table_row().
10444:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10445:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10446:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10447:                               '<td>'.$size.'</td>'.
10448:                               '<td>'.$mtime.'</td>'.
10449:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10450:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10451:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10452:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10453:                               &embedded_file_element('upload_embedded',$counter,
10454:                                                      $embed_file,\%mapping,
10455:                                                      $allfiles,$codebase,'modify').
10456:                               '</div></td>'.
10457:                               &end_data_table_row()."\n";
10458:             $counter ++;
10459:         } else {
10460:             $upload_output .= &start_data_table_row().
10461:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10462:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10463:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10464:                               &Apache::loncommon::end_data_table_row()."\n";
10465:         }
10466:     }
10467:     my $delidx = $counter;
10468:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10469:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10470:         $delete_output .= &start_data_table_row().
10471:                           '<td><img src="'.&icon($oldfile).'" />'.
10472:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10473:                           '<td>'.$size.'</td>'.
10474:                           '<td>'.$mtime.'</td>'.
10475:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10476:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10477:                           &embedded_file_element('upload_embedded',$delidx,
10478:                                                  $oldfile,\%mapping,$allfiles,
10479:                                                  $codebase,'delete').'</td>'.
10480:                           &end_data_table_row()."\n"; 
10481:         $numunused ++;
10482:         $delidx ++;
10483:     }
10484:     if ($upload_output) {
10485:         $upload_output = &start_data_table().
10486:                          $upload_output.
10487:                          &end_data_table()."\n";
10488:     }
10489:     if ($modify_output) {
10490:         $modify_output = &start_data_table().
10491:                          &start_data_table_header_row().
10492:                          '<th>'.&mt('File').'</th>'.
10493:                          '<th>'.&mt('Size (KB)').'</th>'.
10494:                          '<th>'.&mt('Modified').'</th>'.
10495:                          '<th>'.&mt('Upload replacement?').'</th>'.
10496:                          &end_data_table_header_row().
10497:                          $modify_output.
10498:                          &end_data_table()."\n";
10499:     }
10500:     if ($delete_output) {
10501:         $delete_output = &start_data_table().
10502:                          &start_data_table_header_row().
10503:                          '<th>'.&mt('File').'</th>'.
10504:                          '<th>'.&mt('Size (KB)').'</th>'.
10505:                          '<th>'.&mt('Modified').'</th>'.
10506:                          '<th>'.&mt('Delete?').'</th>'.
10507:                          &end_data_table_header_row().
10508:                          $delete_output.
10509:                          &end_data_table()."\n";
10510:     }
10511:     my $applies = 0;
10512:     if ($numremref) {
10513:         $applies ++;
10514:     }
10515:     if ($numinvalid) {
10516:         $applies ++;
10517:     }
10518:     if ($numexisting) {
10519:         $applies ++;
10520:     }
10521:     if ($counter || $numunused) {
10522:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10523:                   ' method="post" enctype="multipart/form-data">'."\n".
10524:                   $state.'<h3>'.$heading.'</h3>'; 
10525:         if ($actionurl eq '/adm/dependencies') {
10526:             if ($numnew) {
10527:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10528:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10529:                            $upload_output.'<br />'."\n";
10530:             }
10531:             if ($numexisting) {
10532:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10533:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10534:                            $modify_output.'<br />'."\n";
10535:                            $buttontext = &mt('Save changes');
10536:             }
10537:             if ($numunused) {
10538:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10539:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10540:                            $delete_output.'<br />'."\n";
10541:                            $buttontext = &mt('Save changes');
10542:             }
10543:         } else {
10544:             $output .= $upload_output.'<br />'."\n";
10545:         }
10546:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10547:                    $counter.'" />'."\n";
10548:         if ($actionurl eq '/adm/dependencies') { 
10549:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10550:                        $numnew.'" />'."\n";
10551:         } elsif ($actionurl eq '') {
10552:             $output .=  '<input type="hidden" name="phase" value="three" />';
10553:         }
10554:     } elsif ($applies) {
10555:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10556:         if ($applies > 1) {
10557:             $output .=  
10558:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10559:             if ($numremref) {
10560:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10561:             }
10562:             if ($numinvalid) {
10563:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10564:             }
10565:             if ($numexisting) {
10566:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10567:             }
10568:             $output .= '</ul><br />';
10569:         } elsif ($numremref) {
10570:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10571:         } elsif ($numinvalid) {
10572:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10573:         } elsif ($numexisting) {
10574:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10575:         }
10576:         $output .= $upload_output.'<br />';
10577:     }
10578:     my ($pathchange_output,$chgcount);
10579:     $chgcount = $counter;
10580:     if (keys(%pathchanges) > 0) {
10581:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10582:             if ($counter) {
10583:                 $output .= &embedded_file_element('pathchange',$chgcount,
10584:                                                   $embed_file,\%mapping,
10585:                                                   $allfiles,$codebase,'change');
10586:             } else {
10587:                 $pathchange_output .= 
10588:                     &start_data_table_row().
10589:                     '<td><input type ="checkbox" name="namechange" value="'.
10590:                     $chgcount.'" checked="checked" /></td>'.
10591:                     '<td>'.$mapping{$embed_file}.'</td>'.
10592:                     '<td>'.$embed_file.
10593:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10594:                                            \%mapping,$allfiles,$codebase,'change').
10595:                     '</td>'.&end_data_table_row();
10596:             }
10597:             $numpathchg ++;
10598:             $chgcount ++;
10599:         }
10600:     }
10601:     if (($counter) || ($numunused)) {
10602:         if ($numpathchg) {
10603:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10604:                        $numpathchg.'" />'."\n";
10605:         }
10606:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10607:             ($actionurl eq '/adm/imsimport')) {
10608:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10609:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10610:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10611:         } elsif ($actionurl eq '/adm/dependencies') {
10612:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10613:         }
10614:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10615:     } elsif ($numpathchg) {
10616:         my %pathchange = ();
10617:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10618:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10619:             $output .= '<p>'.&mt('or').'</p>'; 
10620:         }
10621:     }
10622:     return ($output,$counter,$numpathchg);
10623: }
10624: 
10625: =pod
10626: 
10627: =item * clean_path($name)
10628: 
10629: Performs clean-up of directories, subdirectories and filename in an
10630: embedded object, referenced in an HTML file which is being uploaded
10631: to a course or portfolio, where
10632: "Upload embedded images/multimedia files if HTML file" checkbox was
10633: checked.
10634: 
10635: Clean-up is similar to replacements in lonnet::clean_filename()
10636: except each / between sub-directory and next level is preserved.
10637: 
10638: =cut
10639: 
10640: sub clean_path {
10641:     my ($embed_file) = @_;
10642:     $embed_file =~s{^/+}{};
10643:     my @contents;
10644:     if ($embed_file =~ m{/}) {
10645:         @contents = split(/\//,$embed_file);
10646:     } else {
10647:         @contents = ($embed_file);
10648:     }
10649:     my $lastidx = scalar(@contents)-1;
10650:     for (my $i=0; $i<=$lastidx; $i++) {
10651:         $contents[$i]=~s{\\}{/}g;
10652:         $contents[$i]=~s/\s+/\_/g;
10653:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10654:         if ($i == $lastidx) {
10655:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10656:         }
10657:     }
10658:     if ($lastidx > 0) {
10659:         return join('/',@contents);
10660:     } else {
10661:         return $contents[0];
10662:     }
10663: }
10664: 
10665: sub embedded_file_element {
10666:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10667:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10668:                    (ref($codebase) eq 'HASH'));
10669:     my $output;
10670:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10671:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10672:     }
10673:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10674:                &escape($embed_file).'" />';
10675:     unless (($context eq 'upload_embedded') && 
10676:             ($mapping->{$embed_file} eq $embed_file)) {
10677:         $output .='
10678:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10679:     }
10680:     my $attrib;
10681:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10682:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10683:     }
10684:     $output .=
10685:         "\n\t\t".
10686:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10687:         $attrib.'" />';
10688:     if (exists($codebase->{$mapping->{$embed_file}})) {
10689:         $output .=
10690:             "\n\t\t".
10691:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10692:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10693:     }
10694:     return $output;
10695: }
10696: 
10697: sub get_dependency_details {
10698:     my ($currfile,$currsubfile,$embed_file) = @_;
10699:     my ($size,$mtime,$showsize,$showmtime);
10700:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10701:         if ($embed_file =~ m{/}) {
10702:             my ($path,$fname) = split(/\//,$embed_file);
10703:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10704:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10705:             }
10706:         } else {
10707:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10708:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10709:             }
10710:         }
10711:         $showsize = $size/1024.0;
10712:         $showsize = sprintf("%.1f",$showsize);
10713:         if ($mtime > 0) {
10714:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10715:         }
10716:     }
10717:     return ($showsize,$showmtime);
10718: }
10719: 
10720: sub ask_embedded_js {
10721:     return <<"END";
10722: <script type="text/javascript"">
10723: // <![CDATA[
10724: function toggleBrowse(counter) {
10725:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10726:     var fileid = document.getElementById('embedded_item_'+counter);
10727:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10728:     if (chkboxid.checked == true) {
10729:         uploaddivid.style.display='block';
10730:     } else {
10731:         uploaddivid.style.display='none';
10732:         fileid.value = '';
10733:     }
10734: }
10735: // ]]>
10736: </script>
10737: 
10738: END
10739: }
10740: 
10741: sub upload_embedded {
10742:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10743:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10744:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10745:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10746:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10747:         my $orig_uploaded_filename =
10748:             $env{'form.embedded_item_'.$i.'.filename'};
10749:         foreach my $type ('orig','ref','attrib','codebase') {
10750:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10751:                 $env{'form.embedded_'.$type.'_'.$i} =
10752:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10753:             }
10754:         }
10755:         my ($path,$fname) =
10756:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10757:         # no path, whole string is fname
10758:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10759:         $fname = &Apache::lonnet::clean_filename($fname);
10760:         # See if there is anything left
10761:         next if ($fname eq '');
10762: 
10763:         # Check if file already exists as a file or directory.
10764:         my ($state,$msg);
10765:         if ($context eq 'portfolio') {
10766:             my $port_path = $dirpath;
10767:             if ($group ne '') {
10768:                 $port_path = "groups/$group/$port_path";
10769:             }
10770:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10771:                                               $fname,$group,'embedded_item_'.$i,
10772:                                               $dir_root,$port_path,$disk_quota,
10773:                                               $current_disk_usage,$uname,$udom);
10774:             if ($state eq 'will_exceed_quota'
10775:                 || $state eq 'file_locked') {
10776:                 $output .= $msg;
10777:                 next;
10778:             }
10779:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10780:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10781:             if ($state eq 'exists') {
10782:                 $output .= $msg;
10783:                 next;
10784:             }
10785:         }
10786:         # Check if extension is valid
10787:         if (($fname =~ /\.(\w+)$/) &&
10788:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10789:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10790:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10791:             next;
10792:         } elsif (($fname =~ /\.(\w+)$/) &&
10793:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10794:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10795:             next;
10796:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10797:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10798:             next;
10799:         }
10800:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10801:         my $subdir = $path;
10802:         $subdir =~ s{/+$}{};
10803:         if ($context eq 'portfolio') {
10804:             my $result;
10805:             if ($state eq 'existingfile') {
10806:                 $result=
10807:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10808:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10809:             } else {
10810:                 $result=
10811:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10812:                                                     $dirpath.
10813:                                                     $env{'form.currentpath'}.$subdir);
10814:                 if ($result !~ m|^/uploaded/|) {
10815:                     $output .= '<span class="LC_error">'
10816:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10817:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10818:                                .'</span><br />';
10819:                     next;
10820:                 } else {
10821:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10822:                                $path.$fname.'</span>').'<br />';     
10823:                 }
10824:             }
10825:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10826:             my $extendedsubdir = $dirpath.'/'.$subdir;
10827:             $extendedsubdir =~ s{/+$}{};
10828:             my $result =
10829:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10830:             if ($result !~ m|^/uploaded/|) {
10831:                 $output .= '<span class="LC_error">'
10832:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10833:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10834:                            .'</span><br />';
10835:                     next;
10836:             } else {
10837:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10838:                            $path.$fname.'</span>').'<br />';
10839:                 if ($context eq 'syllabus') {
10840:                     &Apache::lonnet::make_public_indefinitely($result);
10841:                 }
10842:             }
10843:         } else {
10844: # Save the file
10845:             my $target = $env{'form.embedded_item_'.$i};
10846:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10847:             my $dest = $fullpath.$fname;
10848:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10849:             my @parts=split(/\//,"$dirpath/$path");
10850:             my $count;
10851:             my $filepath = $dir_root;
10852:             foreach my $subdir (@parts) {
10853:                 $filepath .= "/$subdir";
10854:                 if (!-e $filepath) {
10855:                     mkdir($filepath,0770);
10856:                 }
10857:             }
10858:             my $fh;
10859:             if (!open($fh,'>'.$dest)) {
10860:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10861:                 $output .= '<span class="LC_error">'.
10862:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10863:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10864:                            '</span><br />';
10865:             } else {
10866:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10867:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10868:                     $output .= '<span class="LC_error">'.
10869:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10870:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10871:                               '</span><br />';
10872:                 } else {
10873:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10874:                                $url.'</span>').'<br />';
10875:                     unless ($context eq 'testbank') {
10876:                         $footer .= &mt('View embedded file: [_1]',
10877:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10878:                     }
10879:                 }
10880:                 close($fh);
10881:             }
10882:         }
10883:         if ($env{'form.embedded_ref_'.$i}) {
10884:             $pathchange{$i} = 1;
10885:         }
10886:     }
10887:     if ($output) {
10888:         $output = '<p>'.$output.'</p>';
10889:     }
10890:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10891:     $returnflag = 'ok';
10892:     my $numpathchgs = scalar(keys(%pathchange));
10893:     if ($numpathchgs > 0) {
10894:         if ($context eq 'portfolio') {
10895:             $output .= '<p>'.&mt('or').'</p>';
10896:         } elsif ($context eq 'testbank') {
10897:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10898:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10899:             $returnflag = 'modify_orightml';
10900:         }
10901:     }
10902:     return ($output.$footer,$returnflag,$numpathchgs);
10903: }
10904: 
10905: sub modify_html_form {
10906:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10907:     my $end = 0;
10908:     my $modifyform;
10909:     if ($context eq 'upload_embedded') {
10910:         return unless (ref($pathchange) eq 'HASH');
10911:         if ($env{'form.number_embedded_items'}) {
10912:             $end += $env{'form.number_embedded_items'};
10913:         }
10914:         if ($env{'form.number_pathchange_items'}) {
10915:             $end += $env{'form.number_pathchange_items'};
10916:         }
10917:         if ($end) {
10918:             for (my $i=0; $i<$end; $i++) {
10919:                 if ($i < $env{'form.number_embedded_items'}) {
10920:                     next unless($pathchange->{$i});
10921:                 }
10922:                 $modifyform .=
10923:                     &start_data_table_row().
10924:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10925:                     'checked="checked" /></td>'.
10926:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10927:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10928:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10929:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10930:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10931:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10932:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10933:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10934:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10935:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10936:                     &end_data_table_row();
10937:             }
10938:         }
10939:     } else {
10940:         $modifyform = $pathchgtable;
10941:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10942:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10943:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10944:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10945:         }
10946:     }
10947:     if ($modifyform) {
10948:         if ($actionurl eq '/adm/dependencies') {
10949:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10950:         }
10951:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10952:                '<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".
10953:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10954:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10955:                '</ol></p>'."\n".'<p>'.
10956:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10957:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10958:                &start_data_table()."\n".
10959:                &start_data_table_header_row().
10960:                '<th>'.&mt('Change?').'</th>'.
10961:                '<th>'.&mt('Current reference').'</th>'.
10962:                '<th>'.&mt('Required reference').'</th>'.
10963:                &end_data_table_header_row()."\n".
10964:                $modifyform.
10965:                &end_data_table().'<br />'."\n".$hiddenstate.
10966:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10967:                '</form>'."\n";
10968:     }
10969:     return;
10970: }
10971: 
10972: sub modify_html_refs {
10973:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10974:     my $container;
10975:     if ($context eq 'portfolio') {
10976:         $container = $env{'form.container'};
10977:     } elsif ($context eq 'coursedoc') {
10978:         $container = $env{'form.primaryurl'};
10979:     } elsif ($context eq 'manage_dependencies') {
10980:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10981:         $container = "/$container";
10982:     } elsif ($context eq 'syllabus') {
10983:         $container = $url;
10984:     } else {
10985:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10986:     }
10987:     my (%allfiles,%codebase,$output,$content);
10988:     my @changes = &get_env_multiple('form.namechange');
10989:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
10990:         if (wantarray) {
10991:             return ('',0,0); 
10992:         } else {
10993:             return;
10994:         }
10995:     }
10996:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10997:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10998:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10999:             if (wantarray) {
11000:                 return ('',0,0);
11001:             } else {
11002:                 return;
11003:             }
11004:         } 
11005:         $content = &Apache::lonnet::getfile($container);
11006:         if ($content eq '-1') {
11007:             if (wantarray) {
11008:                 return ('',0,0);
11009:             } else {
11010:                 return;
11011:             }
11012:         }
11013:     } else {
11014:         unless ($container =~ /^\Q$dir_root\E/) {
11015:             if (wantarray) {
11016:                 return ('',0,0);
11017:             } else {
11018:                 return;
11019:             }
11020:         } 
11021:         if (open(my $fh,"<$container")) {
11022:             $content = join('', <$fh>);
11023:             close($fh);
11024:         } else {
11025:             if (wantarray) {
11026:                 return ('',0,0);
11027:             } else {
11028:                 return;
11029:             }
11030:         }
11031:     }
11032:     my ($count,$codebasecount) = (0,0);
11033:     my $mm = new File::MMagic;
11034:     my $mime_type = $mm->checktype_contents($content);
11035:     if ($mime_type eq 'text/html') {
11036:         my $parse_result = 
11037:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11038:                                                     \%codebase,\$content);
11039:         if ($parse_result eq 'ok') {
11040:             foreach my $i (@changes) {
11041:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11042:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11043:                 if ($allfiles{$ref}) {
11044:                     my $newname =  $orig;
11045:                     my ($attrib_regexp,$codebase);
11046:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11047:                     if ($attrib_regexp =~ /:/) {
11048:                         $attrib_regexp =~ s/\:/|/g;
11049:                     }
11050:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11051:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11052:                         $count += $numchg;
11053:                         $allfiles{$newname} = $allfiles{$ref};
11054:                         delete($allfiles{$ref});
11055:                     }
11056:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11057:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11058:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11059:                         $codebasecount ++;
11060:                     }
11061:                 }
11062:             }
11063:             my $skiprewrites;
11064:             if ($count || $codebasecount) {
11065:                 my $saveresult;
11066:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11067:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11068:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11069:                     if ($url eq $container) {
11070:                         my ($fname) = ($container =~ m{/([^/]+)$});
11071:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11072:                                             $count,'<span class="LC_filename">'.
11073:                                             $fname.'</span>').'</p>';
11074:                     } else {
11075:                          $output = '<p class="LC_error">'.
11076:                                    &mt('Error: update failed for: [_1].',
11077:                                    '<span class="LC_filename">'.
11078:                                    $container.'</span>').'</p>';
11079:                     }
11080:                     if ($context eq 'syllabus') {
11081:                         unless ($saveresult eq 'ok') {
11082:                             $skiprewrites = 1;
11083:                         }
11084:                     }
11085:                 } else {
11086:                     if (open(my $fh,">$container")) {
11087:                         print $fh $content;
11088:                         close($fh);
11089:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11090:                                   $count,'<span class="LC_filename">'.
11091:                                   $container.'</span>').'</p>';
11092:                     } else {
11093:                          $output = '<p class="LC_error">'.
11094:                                    &mt('Error: could not update [_1].',
11095:                                    '<span class="LC_filename">'.
11096:                                    $container.'</span>').'</p>';
11097:                     }
11098:                 }
11099:             }
11100:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11101:                 my ($actionurl,$state);
11102:                 $actionurl = "/public/$udom/$uname/syllabus";
11103:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11104:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11105:                                               \%codebase,
11106:                                               {'context' => 'rewrites',
11107:                                                'ignore_remote_references' => 1,});
11108:                 if (ref($mapping) eq 'HASH') {
11109:                     my $rewrites = 0;
11110:                     foreach my $key (keys(%{$mapping})) {
11111:                         next if ($key =~ m{^https?://});
11112:                         my $ref = $mapping->{$key};
11113:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11114:                         my $attrib;
11115:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11116:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11117:                         }
11118:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11119:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11120:                             $rewrites += $numchg;
11121:                         }
11122:                     }
11123:                     if ($rewrites) {
11124:                         my $saveresult;
11125:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11126:                         if ($url eq $container) {
11127:                             my ($fname) = ($container =~ m{/([^/]+)$});
11128:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11129:                                             $count,'<span class="LC_filename">'.
11130:                                             $fname.'</span>').'</p>';
11131:                         } else {
11132:                             $output .= '<p class="LC_error">'.
11133:                                        &mt('Error: could not update links in [_1].',
11134:                                        '<span class="LC_filename">'.
11135:                                        $container.'</span>').'</p>';
11136: 
11137:                         }
11138:                     }
11139:                 }
11140:             }
11141:         } else {
11142:             &logthis('Failed to parse '.$container.
11143:                      ' to modify references: '.$parse_result);
11144:         }
11145:     }
11146:     if (wantarray) {
11147:         return ($output,$count,$codebasecount);
11148:     } else {
11149:         return $output;
11150:     }
11151: }
11152: 
11153: sub check_for_existing {
11154:     my ($path,$fname,$element) = @_;
11155:     my ($state,$msg);
11156:     if (-d $path.'/'.$fname) {
11157:         $state = 'exists';
11158:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11159:     } elsif (-e $path.'/'.$fname) {
11160:         $state = 'exists';
11161:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11162:     }
11163:     if ($state eq 'exists') {
11164:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11165:     }
11166:     return ($state,$msg);
11167: }
11168: 
11169: sub check_for_upload {
11170:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11171:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11172:     my $filesize = length($env{'form.'.$element});
11173:     if (!$filesize) {
11174:         my $msg = '<span class="LC_error">'.
11175:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11176:                       '<span class="LC_filename">'.$fname.'</span>',
11177:                       $filesize).'<br />'.
11178:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11179:                   '</span>';
11180:         return ('zero_bytes',$msg);
11181:     }
11182:     $filesize =  $filesize/1000; #express in k (1024?)
11183:     my $getpropath = 1;
11184:     my ($dirlistref,$listerror) =
11185:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11186:     my $found_file = 0;
11187:     my $locked_file = 0;
11188:     my @lockers;
11189:     my $navmap;
11190:     if ($env{'request.course.id'}) {
11191:         $navmap = Apache::lonnavmaps::navmap->new();
11192:     }
11193:     if (ref($dirlistref) eq 'ARRAY') {
11194:         foreach my $line (@{$dirlistref}) {
11195:             my ($file_name,$rest)=split(/\&/,$line,2);
11196:             if ($file_name eq $fname){
11197:                 $file_name = $path.$file_name;
11198:                 if ($group ne '') {
11199:                     $file_name = $group.$file_name;
11200:                 }
11201:                 $found_file = 1;
11202:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11203:                     foreach my $lock (@lockers) {
11204:                         if (ref($lock) eq 'ARRAY') {
11205:                             my ($symb,$crsid) = @{$lock};
11206:                             if ($crsid eq $env{'request.course.id'}) {
11207:                                 if (ref($navmap)) {
11208:                                     my $res = $navmap->getBySymb($symb);
11209:                                     foreach my $part (@{$res->parts()}) { 
11210:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11211:                                         unless (($slot_status == $res->RESERVED) ||
11212:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11213:                                             $locked_file = 1;
11214:                                         }
11215:                                     }
11216:                                 } else {
11217:                                     $locked_file = 1;
11218:                                 }
11219:                             } else {
11220:                                 $locked_file = 1;
11221:                             }
11222:                         }
11223:                    }
11224:                 } else {
11225:                     my @info = split(/\&/,$rest);
11226:                     my $currsize = $info[6]/1000;
11227:                     if ($currsize < $filesize) {
11228:                         my $extra = $filesize - $currsize;
11229:                         if (($current_disk_usage + $extra) > $disk_quota) {
11230:                             my $msg = '<p class="LC_warning">'.
11231:                                       &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.',
11232:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11233:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11234:                                                    $disk_quota,$current_disk_usage).'</p>';
11235:                             return ('will_exceed_quota',$msg);
11236:                         }
11237:                     }
11238:                 }
11239:             }
11240:         }
11241:     }
11242:     if (($current_disk_usage + $filesize) > $disk_quota){
11243:         my $msg = '<p class="LC_warning">'.
11244:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11245:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11246:         return ('will_exceed_quota',$msg);
11247:     } elsif ($found_file) {
11248:         if ($locked_file) {
11249:             my $msg = '<p class="LC_warning">';
11250:             $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>');
11251:             $msg .= '</p>';
11252:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11253:             return ('file_locked',$msg);
11254:         } else {
11255:             my $msg = '<p class="LC_error">';
11256:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11257:             $msg .= '</p>';
11258:             return ('existingfile',$msg);
11259:         }
11260:     }
11261: }
11262: 
11263: sub check_for_traversal {
11264:     my ($path,$url,$toplevel) = @_;
11265:     my @parts=split(/\//,$path);
11266:     my $cleanpath;
11267:     my $fullpath = $url;
11268:     for (my $i=0;$i<@parts;$i++) {
11269:         next if ($parts[$i] eq '.');
11270:         if ($parts[$i] eq '..') {
11271:             $fullpath =~ s{([^/]+/)$}{};
11272:         } else {
11273:             $fullpath .= $parts[$i].'/';
11274:         }
11275:     }
11276:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11277:         $cleanpath = $1;
11278:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11279:         my $curr_toprel = $1;
11280:         my @parts = split(/\//,$curr_toprel);
11281:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11282:         my @urlparts = split(/\//,$url_toprel);
11283:         my $doubledots;
11284:         my $startdiff = -1;
11285:         for (my $i=0; $i<@urlparts; $i++) {
11286:             if ($startdiff == -1) {
11287:                 unless ($urlparts[$i] eq $parts[$i]) {
11288:                     $startdiff = $i;
11289:                     $doubledots .= '../';
11290:                 }
11291:             } else {
11292:                 $doubledots .= '../';
11293:             }
11294:         }
11295:         if ($startdiff > -1) {
11296:             $cleanpath = $doubledots;
11297:             for (my $i=$startdiff; $i<@parts; $i++) {
11298:                 $cleanpath .= $parts[$i].'/';
11299:             }
11300:         }
11301:     }
11302:     $cleanpath =~ s{(/)$}{};
11303:     return $cleanpath;
11304: }
11305: 
11306: sub is_archive_file {
11307:     my ($mimetype) = @_;
11308:     if (($mimetype eq 'application/octet-stream') ||
11309:         ($mimetype eq 'application/x-stuffit') ||
11310:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11311:         return 1;
11312:     }
11313:     return;
11314: }
11315: 
11316: sub decompress_form {
11317:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11318:     my %lt = &Apache::lonlocal::texthash (
11319:         this => 'This file is an archive file.',
11320:         camt => 'This file is a Camtasia archive file.',
11321:         itsc => 'Its contents are as follows:',
11322:         youm => 'You may wish to extract its contents.',
11323:         extr => 'Extract contents',
11324:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11325:         proa => 'Process automatically?',
11326:         yes  => 'Yes',
11327:         no   => 'No',
11328:         fold => 'Title for folder containing movie',
11329:         movi => 'Title for page containing embedded movie', 
11330:     );
11331:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11332:     my ($is_camtasia,$topdir,%toplevel,@paths);
11333:     my $info = &list_archive_contents($fileloc,\@paths);
11334:     if (@paths) {
11335:         foreach my $path (@paths) {
11336:             $path =~ s{^/}{};
11337:             if ($path =~ m{^([^/]+)/$}) {
11338:                 $topdir = $1;
11339:             }
11340:             if ($path =~ m{^([^/]+)/}) {
11341:                 $toplevel{$1} = $path;
11342:             } else {
11343:                 $toplevel{$path} = $path;
11344:             }
11345:         }
11346:     }
11347:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11348:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11349:                         "$topdir/media/",
11350:                         "$topdir/media/$topdir.mp4",
11351:                         "$topdir/media/FirstFrame.png",
11352:                         "$topdir/media/player.swf",
11353:                         "$topdir/media/swfobject.js",
11354:                         "$topdir/media/expressInstall.swf");
11355:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11356:                          "$topdir/$topdir.mp4",
11357:                          "$topdir/$topdir\_config.xml",
11358:                          "$topdir/$topdir\_controller.swf",
11359:                          "$topdir/$topdir\_embed.css",
11360:                          "$topdir/$topdir\_First_Frame.png",
11361:                          "$topdir/$topdir\_player.html",
11362:                          "$topdir/$topdir\_Thumbnails.png",
11363:                          "$topdir/playerProductInstall.swf",
11364:                          "$topdir/scripts/",
11365:                          "$topdir/scripts/config_xml.js",
11366:                          "$topdir/scripts/handlebars.js",
11367:                          "$topdir/scripts/jquery-1.7.1.min.js",
11368:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11369:                          "$topdir/scripts/modernizr.js",
11370:                          "$topdir/scripts/player-min.js",
11371:                          "$topdir/scripts/swfobject.js",
11372:                          "$topdir/skins/",
11373:                          "$topdir/skins/configuration_express.xml",
11374:                          "$topdir/skins/express_show/",
11375:                          "$topdir/skins/express_show/player-min.css",
11376:                          "$topdir/skins/express_show/spritesheet.png");
11377:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11378:                          "$topdir/$topdir.mp4",
11379:                          "$topdir/$topdir\_config.xml",
11380:                          "$topdir/$topdir\_controller.swf",
11381:                          "$topdir/$topdir\_embed.css",
11382:                          "$topdir/$topdir\_First_Frame.png",
11383:                          "$topdir/$topdir\_player.html",
11384:                          "$topdir/$topdir\_Thumbnails.png",
11385:                          "$topdir/playerProductInstall.swf",
11386:                          "$topdir/scripts/",
11387:                          "$topdir/scripts/config_xml.js",
11388:                          "$topdir/scripts/techsmith-smart-player.min.js",
11389:                          "$topdir/skins/",
11390:                          "$topdir/skins/configuration_express.xml",
11391:                          "$topdir/skins/express_show/",
11392:                          "$topdir/skins/express_show/spritesheet.min.css",
11393:                          "$topdir/skins/express_show/spritesheet.png",
11394:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11395:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11396:         if (@diffs == 0) {
11397:             $is_camtasia = 6;
11398:         } else {
11399:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11400:             if (@diffs == 0) {
11401:                 $is_camtasia = 8;
11402:             } else {
11403:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11404:                 if (@diffs == 0) {
11405:                     $is_camtasia = 8;
11406:                 }
11407:             }
11408:         }
11409:     }
11410:     my $output;
11411:     if ($is_camtasia) {
11412:         $output = <<"ENDCAM";
11413: <script type="text/javascript" language="Javascript">
11414: // <![CDATA[
11415: 
11416: function camtasiaToggle() {
11417:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11418:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11419:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11420:                 document.getElementById('camtasia_titles').style.display='block';
11421:             } else {
11422:                 document.getElementById('camtasia_titles').style.display='none';
11423:             }
11424:         }
11425:     }
11426:     return;
11427: }
11428: 
11429: // ]]>
11430: </script>
11431: <p>$lt{'camt'}</p>
11432: ENDCAM
11433:     } else {
11434:         $output = '<p>'.$lt{'this'};
11435:         if ($info eq '') {
11436:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11437:         } else {
11438:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11439:                        '<div><pre>'.$info.'</pre></div>';
11440:         }
11441:     }
11442:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11443:     my $duplicates;
11444:     my $num = 0;
11445:     if (ref($dirlist) eq 'ARRAY') {
11446:         foreach my $item (@{$dirlist}) {
11447:             if (ref($item) eq 'ARRAY') {
11448:                 if (exists($toplevel{$item->[0]})) {
11449:                     $duplicates .= 
11450:                         &start_data_table_row().
11451:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11452:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11453:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11454:                         'value="1" />'.&mt('Yes').'</label>'.
11455:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11456:                         '<td>'.$item->[0].'</td>';
11457:                     if ($item->[2]) {
11458:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11459:                     } else {
11460:                         $duplicates .= '<td>'.&mt('File').'</td>';
11461:                     }
11462:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11463:                                    '<td>'.
11464:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11465:                                    '</td>'.
11466:                                    &end_data_table_row();
11467:                     $num ++;
11468:                 }
11469:             }
11470:         }
11471:     }
11472:     my $itemcount;
11473:     if (@paths > 0) {
11474:         $itemcount = scalar(@paths);
11475:     } else {
11476:         $itemcount = 1;
11477:     }
11478:     if ($is_camtasia) {
11479:         $output .= $lt{'auto'}.'<br />'.
11480:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11481:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11482:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11483:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11484:                    $lt{'no'}.'</label></span><br />'.
11485:                    '<div id="camtasia_titles" style="display:block">'.
11486:                    &Apache::lonhtmlcommon::start_pick_box().
11487:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11488:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11489:                    &Apache::lonhtmlcommon::row_closure().
11490:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11491:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11492:                    &Apache::lonhtmlcommon::row_closure(1).
11493:                    &Apache::lonhtmlcommon::end_pick_box().
11494:                    '</div>';
11495:     }
11496:     $output .= 
11497:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11498:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11499:         "\n";
11500:     if ($duplicates ne '') {
11501:         $output .= '<p><span class="LC_warning">'.
11502:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11503:                    &start_data_table().
11504:                    &start_data_table_header_row().
11505:                    '<th>'.&mt('Overwrite?').'</th>'.
11506:                    '<th>'.&mt('Name').'</th>'.
11507:                    '<th>'.&mt('Type').'</th>'.
11508:                    '<th>'.&mt('Size').'</th>'.
11509:                    '<th>'.&mt('Last modified').'</th>'.
11510:                    &end_data_table_header_row().
11511:                    $duplicates.
11512:                    &end_data_table().
11513:                    '</p>';
11514:     }
11515:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11516:     if (ref($hiddenelements) eq 'HASH') {
11517:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11518:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11519:         }
11520:     }
11521:     $output .= <<"END";
11522: <br />
11523: <input type="submit" name="decompress" value="$lt{'extr'}" />
11524: </form>
11525: $noextract
11526: END
11527:     return $output;
11528: }
11529: 
11530: sub decompression_utility {
11531:     my ($program) = @_;
11532:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11533:     my $location;
11534:     if (grep(/^\Q$program\E$/,@utilities)) { 
11535:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11536:                          '/usr/sbin/') {
11537:             if (-x $dir.$program) {
11538:                 $location = $dir.$program;
11539:                 last;
11540:             }
11541:         }
11542:     }
11543:     return $location;
11544: }
11545: 
11546: sub list_archive_contents {
11547:     my ($file,$pathsref) = @_;
11548:     my (@cmd,$output);
11549:     my $needsregexp;
11550:     if ($file =~ /\.zip$/) {
11551:         @cmd = (&decompression_utility('unzip'),"-l");
11552:         $needsregexp = 1;
11553:     } elsif (($file =~ m/\.tar\.gz$/) ||
11554:              ($file =~ /\.tgz$/)) {
11555:         @cmd = (&decompression_utility('tar'),"-ztf");
11556:     } elsif ($file =~ /\.tar\.bz2$/) {
11557:         @cmd = (&decompression_utility('tar'),"-jtf");
11558:     } elsif ($file =~ m|\.tar$|) {
11559:         @cmd = (&decompression_utility('tar'),"-tf");
11560:     }
11561:     if (@cmd) {
11562:         undef($!);
11563:         undef($@);
11564:         if (open(my $fh,"-|", @cmd, $file)) {
11565:             while (my $line = <$fh>) {
11566:                 $output .= $line;
11567:                 chomp($line);
11568:                 my $item;
11569:                 if ($needsregexp) {
11570:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11571:                 } else {
11572:                     $item = $line;
11573:                 }
11574:                 if ($item ne '') {
11575:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11576:                         push(@{$pathsref},$item);
11577:                     } 
11578:                 }
11579:             }
11580:             close($fh);
11581:         }
11582:     }
11583:     return $output;
11584: }
11585: 
11586: sub decompress_uploaded_file {
11587:     my ($file,$dir) = @_;
11588:     &Apache::lonnet::appenv({'cgi.file' => $file});
11589:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11590:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11591:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11592:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11593:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11594:     my $decompressed = $env{'cgi.decompressed'};
11595:     &Apache::lonnet::delenv('cgi.file');
11596:     &Apache::lonnet::delenv('cgi.dir');
11597:     &Apache::lonnet::delenv('cgi.decompressed');
11598:     return ($decompressed,$result);
11599: }
11600: 
11601: sub process_decompression {
11602:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11603:     my ($dir,$error,$warning,$output);
11604:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
11605:         $error = &mt('Filename not a supported archive file type.').
11606:                  '<br />'.&mt('Filename should end with one of: [_1].',
11607:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11608:     } else {
11609:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11610:         if ($docuhome eq 'no_host') {
11611:             $error = &mt('Could not determine home server for course.');
11612:         } else {
11613:             my @ids=&Apache::lonnet::current_machine_ids();
11614:             my $currdir = "$dir_root/$destination";
11615:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11616:                 $dir = &LONCAPA::propath($docudom,$docuname).
11617:                        "$dir_root/$destination";
11618:             } else {
11619:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11620:                        "$dir_root/$docudom/$docuname/$destination";
11621:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11622:                     $error = &mt('Archive file not found.');
11623:                 }
11624:             }
11625:             my (@to_overwrite,@to_skip);
11626:             if ($env{'form.archive_overwrite_total'} > 0) {
11627:                 my $total = $env{'form.archive_overwrite_total'};
11628:                 for (my $i=0; $i<$total; $i++) {
11629:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11630:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11631:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11632:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11633:                     }
11634:                 }
11635:             }
11636:             my $numskip = scalar(@to_skip);
11637:             if (($numskip > 0) && 
11638:                 ($numskip == $env{'form.archive_itemcount'})) {
11639:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11640:             } elsif ($dir eq '') {
11641:                 $error = &mt('Directory containing archive file unavailable.');
11642:             } elsif (!$error) {
11643:                 my ($decompressed,$display);
11644:                 if ($numskip > 0) {
11645:                     my $tempdir = time.'_'.$$.int(rand(10000));
11646:                     mkdir("$dir/$tempdir",0755);
11647:                     system("mv $dir/$file $dir/$tempdir/$file");
11648:                     ($decompressed,$display) = 
11649:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11650:                     foreach my $item (@to_skip) {
11651:                         if (($item ne '') && ($item !~ /\.\./)) {
11652:                             if (-f "$dir/$tempdir/$item") { 
11653:                                 unlink("$dir/$tempdir/$item");
11654:                             } elsif (-d "$dir/$tempdir/$item") {
11655:                                 system("rm -rf $dir/$tempdir/$item");
11656:                             }
11657:                         }
11658:                     }
11659:                     system("mv $dir/$tempdir/* $dir");
11660:                     rmdir("$dir/$tempdir");   
11661:                 } else {
11662:                     ($decompressed,$display) = 
11663:                         &decompress_uploaded_file($file,$dir);
11664:                 }
11665:                 if ($decompressed eq 'ok') {
11666:                     $output = '<p class="LC_info">'.
11667:                               &mt('Files extracted successfully from archive.').
11668:                               '</p>'."\n";
11669:                     my ($warning,$result,@contents);
11670:                     my ($newdirlistref,$newlisterror) =
11671:                         &Apache::lonnet::dirlist($currdir,$docudom,
11672:                                                  $docuname,1);
11673:                     my (%is_dir,%changes,@newitems);
11674:                     my $dirptr = 16384;
11675:                     if (ref($newdirlistref) eq 'ARRAY') {
11676:                         foreach my $dir_line (@{$newdirlistref}) {
11677:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11678:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11679:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11680:                                 push(@newitems,$item);
11681:                                 if ($dirptr&$testdir) {
11682:                                     $is_dir{$item} = 1;
11683:                                 }
11684:                                 $changes{$item} = 1;
11685:                             }
11686:                         }
11687:                     }
11688:                     if (keys(%changes) > 0) {
11689:                         foreach my $item (sort(@newitems)) {
11690:                             if ($changes{$item}) {
11691:                                 push(@contents,$item);
11692:                             }
11693:                         }
11694:                     }
11695:                     if (@contents > 0) {
11696:                         my $wantform;
11697:                         unless ($env{'form.autoextract_camtasia'}) {
11698:                             $wantform = 1;
11699:                         }
11700:                         my (%children,%parent,%dirorder,%titles);
11701:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11702:                                                                 $currdir,\%is_dir,
11703:                                                                 \%children,\%parent,
11704:                                                                 \@contents,\%dirorder,
11705:                                                                 \%titles,$wantform);
11706:                         if ($datatable ne '') {
11707:                             $output .= &archive_options_form('decompressed',$datatable,
11708:                                                              $count,$hiddenelem);
11709:                             my $startcount = 6;
11710:                             $output .= &archive_javascript($startcount,$count,
11711:                                                            \%titles,\%children);
11712:                         }
11713:                         if ($env{'form.autoextract_camtasia'}) {
11714:                             my $version = $env{'form.autoextract_camtasia'};
11715:                             my %displayed;
11716:                             my $total = 1;
11717:                             $env{'form.archive_directory'} = [];
11718:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11719:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11720:                                 $path =~ s{/$}{};
11721:                                 my $item;
11722:                                 if ($path ne '') {
11723:                                     $item = "$path/$titles{$i}";
11724:                                 } else {
11725:                                     $item = $titles{$i};
11726:                                 }
11727:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11728:                                 if ($item eq $contents[0]) {
11729:                                     push(@{$env{'form.archive_directory'}},$i);
11730:                                     $env{'form.archive_'.$i} = 'display';
11731:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11732:                                     $displayed{'folder'} = $i;
11733:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11734:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11735:                                     $env{'form.archive_'.$i} = 'display';
11736:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11737:                                     $displayed{'web'} = $i;
11738:                                 } else {
11739:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11740:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11741:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11742:                                         push(@{$env{'form.archive_directory'}},$i);
11743:                                     }
11744:                                     $env{'form.archive_'.$i} = 'dependency';
11745:                                 }
11746:                                 $total ++;
11747:                             }
11748:                             for (my $i=1; $i<$total; $i++) {
11749:                                 next if ($i == $displayed{'web'});
11750:                                 next if ($i == $displayed{'folder'});
11751:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11752:                             }
11753:                             $env{'form.phase'} = 'decompress_cleanup';
11754:                             $env{'form.archivedelete'} = 1;
11755:                             $env{'form.archive_count'} = $total-1;
11756:                             $output .=
11757:                                 &process_extracted_files('coursedocs',$docudom,
11758:                                                          $docuname,$destination,
11759:                                                          $dir_root,$hiddenelem);
11760:                         }
11761:                     } else {
11762:                         $warning = &mt('No new items extracted from archive file.');
11763:                     }
11764:                 } else {
11765:                     $output = $display;
11766:                     $error = &mt('An error occurred during extraction from the archive file.');
11767:                 }
11768:             }
11769:         }
11770:     }
11771:     if ($error) {
11772:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11773:                    $error.'</p>'."\n";
11774:     }
11775:     if ($warning) {
11776:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11777:     }
11778:     return $output;
11779: }
11780: 
11781: sub get_extracted {
11782:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11783:         $titles,$wantform) = @_;
11784:     my $count = 0;
11785:     my $depth = 0;
11786:     my $datatable;
11787:     my @hierarchy;
11788:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11789:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11790:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11791:     foreach my $item (@{$contents}) {
11792:         $count ++;
11793:         @{$dirorder->{$count}} = @hierarchy;
11794:         $titles->{$count} = $item;
11795:         &archive_hierarchy($depth,$count,$parent,$children);
11796:         if ($wantform) {
11797:             $datatable .= &archive_row($is_dir->{$item},$item,
11798:                                        $currdir,$depth,$count);
11799:         }
11800:         if ($is_dir->{$item}) {
11801:             $depth ++;
11802:             push(@hierarchy,$count);
11803:             $parent->{$depth} = $count;
11804:             $datatable .=
11805:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11806:                                            \$depth,\$count,\@hierarchy,$dirorder,
11807:                                            $children,$parent,$titles,$wantform);
11808:             $depth --;
11809:             pop(@hierarchy);
11810:         }
11811:     }
11812:     return ($count,$datatable);
11813: }
11814: 
11815: sub recurse_extracted_archive {
11816:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11817:         $children,$parent,$titles,$wantform) = @_;
11818:     my $result='';
11819:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11820:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11821:             (ref($dirorder) eq 'HASH')) {
11822:         return $result;
11823:     }
11824:     my $dirptr = 16384;
11825:     my ($newdirlistref,$newlisterror) =
11826:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11827:     if (ref($newdirlistref) eq 'ARRAY') {
11828:         foreach my $dir_line (@{$newdirlistref}) {
11829:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11830:             unless ($item =~ /^\.+$/) {
11831:                 $$count ++;
11832:                 @{$dirorder->{$$count}} = @{$hierarchy};
11833:                 $titles->{$$count} = $item;
11834:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11835: 
11836:                 my $is_dir;
11837:                 if ($dirptr&$testdir) {
11838:                     $is_dir = 1;
11839:                 }
11840:                 if ($wantform) {
11841:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11842:                 }
11843:                 if ($is_dir) {
11844:                     $$depth ++;
11845:                     push(@{$hierarchy},$$count);
11846:                     $parent->{$$depth} = $$count;
11847:                     $result .=
11848:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11849:                                                    $docuname,$depth,$count,
11850:                                                    $hierarchy,$dirorder,$children,
11851:                                                    $parent,$titles,$wantform);
11852:                     $$depth --;
11853:                     pop(@{$hierarchy});
11854:                 }
11855:             }
11856:         }
11857:     }
11858:     return $result;
11859: }
11860: 
11861: sub archive_hierarchy {
11862:     my ($depth,$count,$parent,$children) =@_;
11863:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11864:         if (exists($parent->{$depth})) {
11865:              $children->{$parent->{$depth}} .= $count.':';
11866:         }
11867:     }
11868:     return;
11869: }
11870: 
11871: sub archive_row {
11872:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11873:     my ($name) = ($item =~ m{([^/]+)$});
11874:     my %choices = &Apache::lonlocal::texthash (
11875:                                        'display'    => 'Add as file',
11876:                                        'dependency' => 'Include as dependency',
11877:                                        'discard'    => 'Discard',
11878:                                       );
11879:     if ($is_dir) {
11880:         $choices{'display'} = &mt('Add as folder'); 
11881:     }
11882:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11883:     my $offset = 0;
11884:     foreach my $action ('display','dependency','discard') {
11885:         $offset ++;
11886:         if ($action ne 'display') {
11887:             $offset ++;
11888:         }  
11889:         $output .= '<td><span class="LC_nobreak">'.
11890:                    '<label><input type="radio" name="archive_'.$count.
11891:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11892:         my $text = $choices{$action};
11893:         if ($is_dir) {
11894:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11895:             if ($action eq 'display') {
11896:                 $text = &mt('Add as folder');
11897:             }
11898:         } else {
11899:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11900: 
11901:         }
11902:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11903:         if ($action eq 'dependency') {
11904:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11905:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11906:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11907:                        '<option value=""></option>'."\n".
11908:                        '</select>'."\n".
11909:                        '</div>';
11910:         } elsif ($action eq 'display') {
11911:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11912:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11913:                        '</div>';
11914:         }
11915:         $output .= '</td>';
11916:     }
11917:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11918:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11919:     for (my $i=0; $i<$depth; $i++) {
11920:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11921:     }
11922:     if ($is_dir) {
11923:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11924:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11925:     } else {
11926:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11927:     }
11928:     $output .= '&nbsp;'.$name.'</td>'."\n".
11929:                &end_data_table_row();
11930:     return $output;
11931: }
11932: 
11933: sub archive_options_form {
11934:     my ($form,$display,$count,$hiddenelem) = @_;
11935:     my %lt = &Apache::lonlocal::texthash(
11936:                perm => 'Permanently remove archive file?',
11937:                hows => 'How should each extracted item be incorporated in the course?',
11938:                cont => 'Content actions for all',
11939:                addf => 'Add as folder/file',
11940:                incd => 'Include as dependency for a displayed file',
11941:                disc => 'Discard',
11942:                no   => 'No',
11943:                yes  => 'Yes',
11944:                save => 'Save',
11945:     );
11946:     my $output = <<"END";
11947: <form name="$form" method="post" action="">
11948: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11949: <label>
11950:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11951: </label>
11952: &nbsp;
11953: <label>
11954:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11955: </span>
11956: </p>
11957: <input type="hidden" name="phase" value="decompress_cleanup" />
11958: <br />$lt{'hows'}
11959: <div class="LC_columnSection">
11960:   <fieldset>
11961:     <legend>$lt{'cont'}</legend>
11962:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11963:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11964:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11965:   </fieldset>
11966: </div>
11967: END
11968:     return $output.
11969:            &start_data_table()."\n".
11970:            $display."\n".
11971:            &end_data_table()."\n".
11972:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11973:            $hiddenelem.
11974:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11975:            '</form>';
11976: }
11977: 
11978: sub archive_javascript {
11979:     my ($startcount,$numitems,$titles,$children) = @_;
11980:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11981:     my $maintitle = $env{'form.comment'};
11982:     my $scripttag = <<START;
11983: <script type="text/javascript">
11984: // <![CDATA[
11985: 
11986: function checkAll(form,prefix) {
11987:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11988:     for (var i=0; i < form.elements.length; i++) {
11989:         var id = form.elements[i].id;
11990:         if ((id != '') && (id != undefined)) {
11991:             if (idstr.test(id)) {
11992:                 if (form.elements[i].type == 'radio') {
11993:                     form.elements[i].checked = true;
11994:                     var nostart = i-$startcount;
11995:                     var offset = nostart%7;
11996:                     var count = (nostart-offset)/7;    
11997:                     dependencyCheck(form,count,offset);
11998:                 }
11999:             }
12000:         }
12001:     }
12002: }
12003: 
12004: function propagateCheck(form,count) {
12005:     if (count > 0) {
12006:         var startelement = $startcount + ((count-1) * 7);
12007:         for (var j=1; j<6; j++) {
12008:             if ((j != 2) && (j != 4)) {
12009:                 var item = startelement + j; 
12010:                 if (form.elements[item].type == 'radio') {
12011:                     if (form.elements[item].checked) {
12012:                         containerCheck(form,count,j);
12013:                         break;
12014:                     }
12015:                 }
12016:             }
12017:         }
12018:     }
12019: }
12020: 
12021: numitems = $numitems
12022: var titles = new Array(numitems);
12023: var parents = new Array(numitems);
12024: for (var i=0; i<numitems; i++) {
12025:     parents[i] = new Array;
12026: }
12027: var maintitle = '$maintitle';
12028: 
12029: START
12030: 
12031:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12032:         my @contents = split(/:/,$children->{$container});
12033:         for (my $i=0; $i<@contents; $i ++) {
12034:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12035:         }
12036:     }
12037: 
12038:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12039:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12040:     }
12041: 
12042:     $scripttag .= <<END;
12043: 
12044: function containerCheck(form,count,offset) {
12045:     if (count > 0) {
12046:         dependencyCheck(form,count,offset);
12047:         var item = (offset+$startcount)+7*(count-1);
12048:         form.elements[item].checked = true;
12049:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12050:             if (parents[count].length > 0) {
12051:                 for (var j=0; j<parents[count].length; j++) {
12052:                     containerCheck(form,parents[count][j],offset);
12053:                 }
12054:             }
12055:         }
12056:     }
12057: }
12058: 
12059: function dependencyCheck(form,count,offset) {
12060:     if (count > 0) {
12061:         var chosen = (offset+$startcount)+7*(count-1);
12062:         var depitem = $startcount + ((count-1) * 7) + 4;
12063:         var currtype = form.elements[depitem].type;
12064:         if (form.elements[chosen].value == 'dependency') {
12065:             document.getElementById('arc_depon_'+count).style.display='block'; 
12066:             form.elements[depitem].options.length = 0;
12067:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12068:             for (var i=1; i<=numitems; i++) {
12069:                 if (i == count) {
12070:                     continue;
12071:                 }
12072:                 var startelement = $startcount + (i-1) * 7;
12073:                 for (var j=1; j<6; j++) {
12074:                     if ((j != 2) && (j!= 4)) {
12075:                         var item = startelement + j;
12076:                         if (form.elements[item].type == 'radio') {
12077:                             if (form.elements[item].checked) {
12078:                                 if (form.elements[item].value == 'display') {
12079:                                     var n = form.elements[depitem].options.length;
12080:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12081:                                 }
12082:                             }
12083:                         }
12084:                     }
12085:                 }
12086:             }
12087:         } else {
12088:             document.getElementById('arc_depon_'+count).style.display='none';
12089:             form.elements[depitem].options.length = 0;
12090:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12091:         }
12092:         titleCheck(form,count,offset);
12093:     }
12094: }
12095: 
12096: function propagateSelect(form,count,offset) {
12097:     if (count > 0) {
12098:         var item = (1+offset+$startcount)+7*(count-1);
12099:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12100:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12101:             if (parents[count].length > 0) {
12102:                 for (var j=0; j<parents[count].length; j++) {
12103:                     containerSelect(form,parents[count][j],offset,picked);
12104:                 }
12105:             }
12106:         }
12107:     }
12108: }
12109: 
12110: function containerSelect(form,count,offset,picked) {
12111:     if (count > 0) {
12112:         var item = (offset+$startcount)+7*(count-1);
12113:         if (form.elements[item].type == 'radio') {
12114:             if (form.elements[item].value == 'dependency') {
12115:                 if (form.elements[item+1].type == 'select-one') {
12116:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12117:                         if (form.elements[item+1].options[i].value == picked) {
12118:                             form.elements[item+1].selectedIndex = i;
12119:                             break;
12120:                         }
12121:                     }
12122:                 }
12123:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12124:                     if (parents[count].length > 0) {
12125:                         for (var j=0; j<parents[count].length; j++) {
12126:                             containerSelect(form,parents[count][j],offset,picked);
12127:                         }
12128:                     }
12129:                 }
12130:             }
12131:         }
12132:     }
12133: }
12134: 
12135: function titleCheck(form,count,offset) {
12136:     if (count > 0) {
12137:         var chosen = (offset+$startcount)+7*(count-1);
12138:         var depitem = $startcount + ((count-1) * 7) + 2;
12139:         var currtype = form.elements[depitem].type;
12140:         if (form.elements[chosen].value == 'display') {
12141:             document.getElementById('arc_title_'+count).style.display='block';
12142:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12143:                 document.getElementById('archive_title_'+count).value=maintitle;
12144:             }
12145:         } else {
12146:             document.getElementById('arc_title_'+count).style.display='none';
12147:             if (currtype == 'text') { 
12148:                 document.getElementById('archive_title_'+count).value='';
12149:             }
12150:         }
12151:     }
12152:     return;
12153: }
12154: 
12155: // ]]>
12156: </script>
12157: END
12158:     return $scripttag;
12159: }
12160: 
12161: sub process_extracted_files {
12162:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12163:     my $numitems = $env{'form.archive_count'};
12164:     return unless ($numitems);
12165:     my @ids=&Apache::lonnet::current_machine_ids();
12166:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12167:         %folders,%containers,%mapinner,%prompttofetch);
12168:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12169:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12170:         $prefix = &LONCAPA::propath($docudom,$docuname);
12171:         $pathtocheck = "$dir_root/$destination";
12172:         $dir = $dir_root;
12173:         $ishome = 1;
12174:     } else {
12175:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12176:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12177:         $dir = "$dir_root/$docudom/$docuname";    
12178:     }
12179:     my $currdir = "$dir_root/$destination";
12180:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12181:     if ($env{'form.folderpath'}) {
12182:         my @items = split('&',$env{'form.folderpath'});
12183:         $folders{'0'} = $items[-2];
12184:         if ($env{'form.folderpath'} =~ /\:1$/) {
12185:             $containers{'0'}='page';
12186:         } else {
12187:             $containers{'0'}='sequence';
12188:         }
12189:     }
12190:     my @archdirs = &get_env_multiple('form.archive_directory');
12191:     if ($numitems) {
12192:         for (my $i=1; $i<=$numitems; $i++) {
12193:             my $path = $env{'form.archive_content_'.$i};
12194:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12195:                 my $item = $1;
12196:                 $toplevelitems{$item} = $i;
12197:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12198:                     $is_dir{$item} = 1;
12199:                 }
12200:             }
12201:         }
12202:     }
12203:     my ($output,%children,%parent,%titles,%dirorder,$result);
12204:     if (keys(%toplevelitems) > 0) {
12205:         my @contents = sort(keys(%toplevelitems));
12206:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12207:                                            \%parent,\@contents,\%dirorder,\%titles);
12208:     }
12209:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12210:     if ($numitems) {
12211:         for (my $i=1; $i<=$numitems; $i++) {
12212:             next if ($env{'form.archive_'.$i} eq 'dependency');
12213:             my $path = $env{'form.archive_content_'.$i};
12214:             if ($path =~ /^\Q$pathtocheck\E/) {
12215:                 if ($env{'form.archive_'.$i} eq 'discard') {
12216:                     if ($prefix ne '' && $path ne '') {
12217:                         if (-e $prefix.$path) {
12218:                             if ((@archdirs > 0) && 
12219:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12220:                                 $todeletedir{$prefix.$path} = 1;
12221:                             } else {
12222:                                 $todelete{$prefix.$path} = 1;
12223:                             }
12224:                         }
12225:                     }
12226:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12227:                     my ($docstitle,$title,$url,$outer);
12228:                     ($title) = ($path =~ m{/([^/]+)$});
12229:                     $docstitle = $env{'form.archive_title_'.$i};
12230:                     if ($docstitle eq '') {
12231:                         $docstitle = $title;
12232:                     }
12233:                     $outer = 0;
12234:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12235:                         if (@{$dirorder{$i}} > 0) {
12236:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12237:                                 if ($env{'form.archive_'.$item} eq 'display') {
12238:                                     $outer = $item;
12239:                                     last;
12240:                                 }
12241:                             }
12242:                         }
12243:                     }
12244:                     my ($errtext,$fatal) = 
12245:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12246:                                                '/'.$folders{$outer}.'.'.
12247:                                                $containers{$outer});
12248:                     next if ($fatal);
12249:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12250:                         if ($context eq 'coursedocs') {
12251:                             $mapinner{$i} = time;
12252:                             $folders{$i} = 'default_'.$mapinner{$i};
12253:                             $containers{$i} = 'sequence';
12254:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12255:                                       $folders{$i}.'.'.$containers{$i};
12256:                             my $newidx = &LONCAPA::map::getresidx();
12257:                             $LONCAPA::map::resources[$newidx]=
12258:                                 $docstitle.':'.$url.':false:normal:res';
12259:                             push(@LONCAPA::map::order,$newidx);
12260:                             my ($outtext,$errtext) =
12261:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12262:                                                         $docuname.'/'.$folders{$outer}.
12263:                                                         '.'.$containers{$outer},1,1);
12264:                             $newseqid{$i} = $newidx;
12265:                             unless ($errtext) {
12266:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12267:                             }
12268:                         }
12269:                     } else {
12270:                         if ($context eq 'coursedocs') {
12271:                             my $newidx=&LONCAPA::map::getresidx();
12272:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12273:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12274:                                       $title;
12275:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12276:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12277:                             }
12278:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12279:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12280:                             }
12281:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12282:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12283:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12284:                                 unless ($ishome) {
12285:                                     my $fetch = "$newdest{$i}/$title";
12286:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12287:                                     $prompttofetch{$fetch} = 1;
12288:                                 }
12289:                             }
12290:                             $LONCAPA::map::resources[$newidx]=
12291:                                 $docstitle.':'.$url.':false:normal:res';
12292:                             push(@LONCAPA::map::order, $newidx);
12293:                             my ($outtext,$errtext)=
12294:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12295:                                                         $docuname.'/'.$folders{$outer}.
12296:                                                         '.'.$containers{$outer},1,1);
12297:                             unless ($errtext) {
12298:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12299:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12300:                                 }
12301:                             }
12302:                         }
12303:                     }
12304:                 }
12305:             } else {
12306:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12307:             }
12308:         }
12309:         for (my $i=1; $i<=$numitems; $i++) {
12310:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12311:             my $path = $env{'form.archive_content_'.$i};
12312:             if ($path =~ /^\Q$pathtocheck\E/) {
12313:                 my ($title) = ($path =~ m{/([^/]+)$});
12314:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12315:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12316:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12317:                         my ($itemidx,$fullpath,$relpath);
12318:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12319:                             my $container = $dirorder{$referrer{$i}}->[-1];
12320:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12321:                                 if ($dirorder{$i}->[$j] eq $container) {
12322:                                     $itemidx = $j;
12323:                                 }
12324:                             }
12325:                         }
12326:                         if ($itemidx eq '') {
12327:                             $itemidx =  0;
12328:                         }
12329:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12330:                             if ($mapinner{$referrer{$i}}) {
12331:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12332:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12333:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12334:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12335:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12336:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12337:                                             if (!-e $fullpath) {
12338:                                                 mkdir($fullpath,0755);
12339:                                             }
12340:                                         }
12341:                                     } else {
12342:                                         last;
12343:                                     }
12344:                                 }
12345:                             }
12346:                         } elsif ($newdest{$referrer{$i}}) {
12347:                             $fullpath = $newdest{$referrer{$i}};
12348:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12349:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12350:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12351:                                     last;
12352:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12353:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12354:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12355:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12356:                                         if (!-e $fullpath) {
12357:                                             mkdir($fullpath,0755);
12358:                                         }
12359:                                     }
12360:                                 } else {
12361:                                     last;
12362:                                 }
12363:                             }
12364:                         }
12365:                         if ($fullpath ne '') {
12366:                             if (-e "$prefix$path") {
12367:                                 system("mv $prefix$path $fullpath/$title");
12368:                             }
12369:                             if (-e "$fullpath/$title") {
12370:                                 my $showpath;
12371:                                 if ($relpath ne '') {
12372:                                     $showpath = "$relpath/$title";
12373:                                 } else {
12374:                                     $showpath = "/$title";
12375:                                 }
12376:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12377:                             }
12378:                             unless ($ishome) {
12379:                                 my $fetch = "$fullpath/$title";
12380:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12381:                                 $prompttofetch{$fetch} = 1;
12382:                             }
12383:                         }
12384:                     }
12385:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12386:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12387:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12388:                 }
12389:             } else {
12390:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12391:             }
12392:         }
12393:         if (keys(%todelete)) {
12394:             foreach my $key (keys(%todelete)) {
12395:                 unlink($key);
12396:             }
12397:         }
12398:         if (keys(%todeletedir)) {
12399:             foreach my $key (keys(%todeletedir)) {
12400:                 rmdir($key);
12401:             }
12402:         }
12403:         foreach my $dir (sort(keys(%is_dir))) {
12404:             if (($pathtocheck ne '') && ($dir ne ''))  {
12405:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12406:             }
12407:         }
12408:         if ($result ne '') {
12409:             $output .= '<ul>'."\n".
12410:                        $result."\n".
12411:                        '</ul>';
12412:         }
12413:         unless ($ishome) {
12414:             my $replicationfail;
12415:             foreach my $item (keys(%prompttofetch)) {
12416:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12417:                 unless ($fetchresult eq 'ok') {
12418:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12419:                 }
12420:             }
12421:             if ($replicationfail) {
12422:                 $output .= '<p class="LC_error">'.
12423:                            &mt('Course home server failed to retrieve:').'<ul>'.
12424:                            $replicationfail.
12425:                            '</ul></p>';
12426:             }
12427:         }
12428:     } else {
12429:         $warning = &mt('No items found in archive.');
12430:     }
12431:     if ($error) {
12432:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12433:                    $error.'</p>'."\n";
12434:     }
12435:     if ($warning) {
12436:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12437:     }
12438:     return $output;
12439: }
12440: 
12441: sub cleanup_empty_dirs {
12442:     my ($path) = @_;
12443:     if (($path ne '') && (-d $path)) {
12444:         if (opendir(my $dirh,$path)) {
12445:             my @dircontents = grep(!/^\./,readdir($dirh));
12446:             my $numitems = 0;
12447:             foreach my $item (@dircontents) {
12448:                 if (-d "$path/$item") {
12449:                     &cleanup_empty_dirs("$path/$item");
12450:                     if (-e "$path/$item") {
12451:                         $numitems ++;
12452:                     }
12453:                 } else {
12454:                     $numitems ++;
12455:                 }
12456:             }
12457:             if ($numitems == 0) {
12458:                 rmdir($path);
12459:             }
12460:             closedir($dirh);
12461:         }
12462:     }
12463:     return;
12464: }
12465: 
12466: =pod
12467: 
12468: =item * &get_folder_hierarchy()
12469: 
12470: Provides hierarchy of names of folders/sub-folders containing the current
12471: item,
12472: 
12473: Inputs: 3
12474:      - $navmap - navmaps object
12475: 
12476:      - $map - url for map (either the trigger itself, or map containing
12477:                            the resource, which is the trigger).
12478: 
12479:      - $showitem - 1 => show title for map itself; 0 => do not show.
12480: 
12481: Outputs: 1 @pathitems - array of folder/subfolder names.
12482: 
12483: =cut
12484: 
12485: sub get_folder_hierarchy {
12486:     my ($navmap,$map,$showitem) = @_;
12487:     my @pathitems;
12488:     if (ref($navmap)) {
12489:         my $mapres = $navmap->getResourceByUrl($map);
12490:         if (ref($mapres)) {
12491:             my $pcslist = $mapres->map_hierarchy();
12492:             if ($pcslist ne '') {
12493:                 my @pcs = split(/,/,$pcslist);
12494:                 foreach my $pc (@pcs) {
12495:                     if ($pc == 1) {
12496:                         push(@pathitems,&mt('Main Content'));
12497:                     } else {
12498:                         my $res = $navmap->getByMapPc($pc);
12499:                         if (ref($res)) {
12500:                             my $title = $res->compTitle();
12501:                             $title =~ s/\W+/_/g;
12502:                             if ($title ne '') {
12503:                                 push(@pathitems,$title);
12504:                             }
12505:                         }
12506:                     }
12507:                 }
12508:             }
12509:             if ($showitem) {
12510:                 if ($mapres->{ID} eq '0.0') {
12511:                     push(@pathitems,&mt('Main Content'));
12512:                 } else {
12513:                     my $maptitle = $mapres->compTitle();
12514:                     $maptitle =~ s/\W+/_/g;
12515:                     if ($maptitle ne '') {
12516:                         push(@pathitems,$maptitle);
12517:                     }
12518:                 }
12519:             }
12520:         }
12521:     }
12522:     return @pathitems;
12523: }
12524: 
12525: =pod
12526: 
12527: =item * &get_turnedin_filepath()
12528: 
12529: Determines path in a user's portfolio file for storage of files uploaded
12530: to a specific essayresponse or dropbox item.
12531: 
12532: Inputs: 3 required + 1 optional.
12533: $symb is symb for resource, $uname and $udom are for current user (required).
12534: $caller is optional (can be "submission", if routine is called when storing
12535: an upoaded file when "Submit Answer" button was pressed).
12536: 
12537: Returns array containing $path and $multiresp. 
12538: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12539: than one file upload item.  Callers of routine should append partid as a 
12540: subdirectory to $path in cases where $multiresp is 1.
12541: 
12542: Called by: homework/essayresponse.pm and homework/structuretags.pm
12543: 
12544: =cut
12545: 
12546: sub get_turnedin_filepath {
12547:     my ($symb,$uname,$udom,$caller) = @_;
12548:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12549:     my $turnindir;
12550:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12551:     $turnindir = $userhash{'turnindir'};
12552:     my ($path,$multiresp);
12553:     if ($turnindir eq '') {
12554:         if ($caller eq 'submission') {
12555:             $turnindir = &mt('turned in');
12556:             $turnindir =~ s/\W+/_/g;
12557:             my %newhash = (
12558:                             'turnindir' => $turnindir,
12559:                           );
12560:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12561:         }
12562:     }
12563:     if ($turnindir ne '') {
12564:         $path = '/'.$turnindir.'/';
12565:         my ($multipart,$turnin,@pathitems);
12566:         my $navmap = Apache::lonnavmaps::navmap->new();
12567:         if (defined($navmap)) {
12568:             my $mapres = $navmap->getResourceByUrl($map);
12569:             if (ref($mapres)) {
12570:                 my $pcslist = $mapres->map_hierarchy();
12571:                 if ($pcslist ne '') {
12572:                     foreach my $pc (split(/,/,$pcslist)) {
12573:                         my $res = $navmap->getByMapPc($pc);
12574:                         if (ref($res)) {
12575:                             my $title = $res->compTitle();
12576:                             $title =~ s/\W+/_/g;
12577:                             if ($title ne '') {
12578:                                 if (($pc > 1) && (length($title) > 12)) {
12579:                                     $title = substr($title,0,12);
12580:                                 }
12581:                                 push(@pathitems,$title);
12582:                             }
12583:                         }
12584:                     }
12585:                 }
12586:                 my $maptitle = $mapres->compTitle();
12587:                 $maptitle =~ s/\W+/_/g;
12588:                 if ($maptitle ne '') {
12589:                     if (length($maptitle) > 12) {
12590:                         $maptitle = substr($maptitle,0,12);
12591:                     }
12592:                     push(@pathitems,$maptitle);
12593:                 }
12594:                 unless ($env{'request.state'} eq 'construct') {
12595:                     my $res = $navmap->getBySymb($symb);
12596:                     if (ref($res)) {
12597:                         my $partlist = $res->parts();
12598:                         my $totaluploads = 0;
12599:                         if (ref($partlist) eq 'ARRAY') {
12600:                             foreach my $part (@{$partlist}) {
12601:                                 my @types = $res->responseType($part);
12602:                                 my @ids = $res->responseIds($part);
12603:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12604:                                     if ($types[$i] eq 'essay') {
12605:                                         my $partid = $part.'_'.$ids[$i];
12606:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12607:                                             $totaluploads ++;
12608:                                         }
12609:                                     }
12610:                                 }
12611:                             }
12612:                             if ($totaluploads > 1) {
12613:                                 $multiresp = 1;
12614:                             }
12615:                         }
12616:                     }
12617:                 }
12618:             } else {
12619:                 return;
12620:             }
12621:         } else {
12622:             return;
12623:         }
12624:         my $restitle=&Apache::lonnet::gettitle($symb);
12625:         $restitle =~ s/\W+/_/g;
12626:         if ($restitle eq '') {
12627:             $restitle = ($resurl =~ m{/[^/]+$});
12628:             if ($restitle eq '') {
12629:                 $restitle = time;
12630:             }
12631:         }
12632:         if (length($restitle) > 12) {
12633:             $restitle = substr($restitle,0,12);
12634:         }
12635:         push(@pathitems,$restitle);
12636:         $path .= join('/',@pathitems);
12637:     }
12638:     return ($path,$multiresp);
12639: }
12640: 
12641: =pod
12642: 
12643: =back
12644: 
12645: =head1 CSV Upload/Handling functions
12646: 
12647: =over 4
12648: 
12649: =item * &upfile_store($r)
12650: 
12651: Store uploaded file, $r should be the HTTP Request object,
12652: needs $env{'form.upfile'}
12653: returns $datatoken to be put into hidden field
12654: 
12655: =cut
12656: 
12657: sub upfile_store {
12658:     my $r=shift;
12659:     $env{'form.upfile'}=~s/\r/\n/gs;
12660:     $env{'form.upfile'}=~s/\f/\n/gs;
12661:     $env{'form.upfile'}=~s/\n+/\n/gs;
12662:     $env{'form.upfile'}=~s/\n+$//gs;
12663: 
12664:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12665: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12666:     {
12667:         my $datafile = $r->dir_config('lonDaemons').
12668:                            '/tmp/'.$datatoken.'.tmp';
12669:         if ( open(my $fh,">$datafile") ) {
12670:             print $fh $env{'form.upfile'};
12671:             close($fh);
12672:         }
12673:     }
12674:     return $datatoken;
12675: }
12676: 
12677: =pod
12678: 
12679: =item * &load_tmp_file($r)
12680: 
12681: Load uploaded file from tmp, $r should be the HTTP Request object,
12682: needs $env{'form.datatoken'},
12683: sets $env{'form.upfile'} to the contents of the file
12684: 
12685: =cut
12686: 
12687: sub load_tmp_file {
12688:     my $r=shift;
12689:     my @studentdata=();
12690:     {
12691:         my $studentfile = $r->dir_config('lonDaemons').
12692:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12693:         if ( open(my $fh,"<$studentfile") ) {
12694:             @studentdata=<$fh>;
12695:             close($fh);
12696:         }
12697:     }
12698:     $env{'form.upfile'}=join('',@studentdata);
12699: }
12700: 
12701: =pod
12702: 
12703: =item * &upfile_record_sep()
12704: 
12705: Separate uploaded file into records
12706: returns array of records,
12707: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12708: 
12709: =cut
12710: 
12711: sub upfile_record_sep {
12712:     if ($env{'form.upfiletype'} eq 'xml') {
12713:     } else {
12714: 	my @records;
12715: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12716: 	    if ($line=~/^\s*$/) { next; }
12717: 	    push(@records,$line);
12718: 	}
12719: 	return @records;
12720:     }
12721: }
12722: 
12723: =pod
12724: 
12725: =item * &record_sep($record)
12726: 
12727: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12728: 
12729: =cut
12730: 
12731: sub takeleft {
12732:     my $index=shift;
12733:     return substr('0000'.$index,-4,4);
12734: }
12735: 
12736: sub record_sep {
12737:     my $record=shift;
12738:     my %components=();
12739:     if ($env{'form.upfiletype'} eq 'xml') {
12740:     } elsif ($env{'form.upfiletype'} eq 'space') {
12741:         my $i=0;
12742:         foreach my $field (split(/\s+/,$record)) {
12743:             $field=~s/^(\"|\')//;
12744:             $field=~s/(\"|\')$//;
12745:             $components{&takeleft($i)}=$field;
12746:             $i++;
12747:         }
12748:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12749:         my $i=0;
12750:         foreach my $field (split(/\t/,$record)) {
12751:             $field=~s/^(\"|\')//;
12752:             $field=~s/(\"|\')$//;
12753:             $components{&takeleft($i)}=$field;
12754:             $i++;
12755:         }
12756:     } else {
12757:         my $separator=',';
12758:         if ($env{'form.upfiletype'} eq 'semisv') {
12759:             $separator=';';
12760:         }
12761:         my $i=0;
12762: # the character we are looking for to indicate the end of a quote or a record 
12763:         my $looking_for=$separator;
12764: # do not add the characters to the fields
12765:         my $ignore=0;
12766: # we just encountered a separator (or the beginning of the record)
12767:         my $just_found_separator=1;
12768: # store the field we are working on here
12769:         my $field='';
12770: # work our way through all characters in record
12771:         foreach my $character ($record=~/(.)/g) {
12772:             if ($character eq $looking_for) {
12773:                if ($character ne $separator) {
12774: # Found the end of a quote, again looking for separator
12775:                   $looking_for=$separator;
12776:                   $ignore=1;
12777:                } else {
12778: # Found a separator, store away what we got
12779:                   $components{&takeleft($i)}=$field;
12780: 	          $i++;
12781:                   $just_found_separator=1;
12782:                   $ignore=0;
12783:                   $field='';
12784:                }
12785:                next;
12786:             }
12787: # single or double quotation marks after a separator indicate beginning of a quote
12788: # we are now looking for the end of the quote and need to ignore separators
12789:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12790:                $looking_for=$character;
12791:                next;
12792:             }
12793: # ignore would be true after we reached the end of a quote
12794:             if ($ignore) { next; }
12795:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12796:             $field.=$character;
12797:             $just_found_separator=0; 
12798:         }
12799: # catch the very last entry, since we never encountered the separator
12800:         $components{&takeleft($i)}=$field;
12801:     }
12802:     return %components;
12803: }
12804: 
12805: ######################################################
12806: ######################################################
12807: 
12808: =pod
12809: 
12810: =item * &upfile_select_html()
12811: 
12812: Return HTML code to select a file from the users machine and specify 
12813: the file type.
12814: 
12815: =cut
12816: 
12817: ######################################################
12818: ######################################################
12819: sub upfile_select_html {
12820:     my %Types = (
12821:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12822:                  semisv => &mt('Semicolon separated values'),
12823:                  space => &mt('Space separated'),
12824:                  tab   => &mt('Tabulator separated'),
12825: #                 xml   => &mt('HTML/XML'),
12826:                  );
12827:     my $Str = '<input type="file" name="upfile" size="50" />'.
12828:         '<br />'.&mt('Type').': <select name="upfiletype">';
12829:     foreach my $type (sort(keys(%Types))) {
12830:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12831:     }
12832:     $Str .= "</select>\n";
12833:     return $Str;
12834: }
12835: 
12836: sub get_samples {
12837:     my ($records,$toget) = @_;
12838:     my @samples=({});
12839:     my $got=0;
12840:     foreach my $rec (@$records) {
12841: 	my %temp = &record_sep($rec);
12842: 	if (! grep(/\S/, values(%temp))) { next; }
12843: 	if (%temp) {
12844: 	    $samples[$got]=\%temp;
12845: 	    $got++;
12846: 	    if ($got == $toget) { last; }
12847: 	}
12848:     }
12849:     return \@samples;
12850: }
12851: 
12852: ######################################################
12853: ######################################################
12854: 
12855: =pod
12856: 
12857: =item * &csv_print_samples($r,$records)
12858: 
12859: Prints a table of sample values from each column uploaded $r is an
12860: Apache Request ref, $records is an arrayref from
12861: &Apache::loncommon::upfile_record_sep
12862: 
12863: =cut
12864: 
12865: ######################################################
12866: ######################################################
12867: sub csv_print_samples {
12868:     my ($r,$records) = @_;
12869:     my $samples = &get_samples($records,5);
12870: 
12871:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12872:               &start_data_table_header_row());
12873:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12874:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12875:     $r->print(&end_data_table_header_row());
12876:     foreach my $hash (@$samples) {
12877: 	$r->print(&start_data_table_row());
12878: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12879: 	    $r->print('<td>');
12880: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12881: 	    $r->print('</td>');
12882: 	}
12883: 	$r->print(&end_data_table_row());
12884:     }
12885:     $r->print(&end_data_table().'<br />'."\n");
12886: }
12887: 
12888: ######################################################
12889: ######################################################
12890: 
12891: =pod
12892: 
12893: =item * &csv_print_select_table($r,$records,$d)
12894: 
12895: Prints a table to create associations between values and table columns.
12896: 
12897: $r is an Apache Request ref,
12898: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12899: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12900: 
12901: =cut
12902: 
12903: ######################################################
12904: ######################################################
12905: sub csv_print_select_table {
12906:     my ($r,$records,$d) = @_;
12907:     my $i=0;
12908:     my $samples = &get_samples($records,1);
12909:     $r->print(&mt('Associate columns with student attributes.')."\n".
12910: 	      &start_data_table().&start_data_table_header_row().
12911:               '<th>'.&mt('Attribute').'</th>'.
12912:               '<th>'.&mt('Column').'</th>'.
12913:               &end_data_table_header_row()."\n");
12914:     foreach my $array_ref (@$d) {
12915: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12916: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12917: 
12918: 	$r->print('<td><select name="f'.$i.'"'.
12919: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12920: 	$r->print('<option value="none"></option>');
12921: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12922: 	    $r->print('<option value="'.$sample.'"'.
12923:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12924:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12925: 	}
12926: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12927: 	$i++;
12928:     }
12929:     $r->print(&end_data_table());
12930:     $i--;
12931:     return $i;
12932: }
12933: 
12934: ######################################################
12935: ######################################################
12936: 
12937: =pod
12938: 
12939: =item * &csv_samples_select_table($r,$records,$d)
12940: 
12941: Prints a table of sample values from the upload and can make associate samples to internal names.
12942: 
12943: $r is an Apache Request ref,
12944: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12945: $d is an array of 2 element arrays (internal name, displayed name)
12946: 
12947: =cut
12948: 
12949: ######################################################
12950: ######################################################
12951: sub csv_samples_select_table {
12952:     my ($r,$records,$d) = @_;
12953:     my $i=0;
12954:     #
12955:     my $max_samples = 5;
12956:     my $samples = &get_samples($records,$max_samples);
12957:     $r->print(&start_data_table().
12958:               &start_data_table_header_row().'<th>'.
12959:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12960:               &end_data_table_header_row());
12961: 
12962:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12963: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12964: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12965: 	foreach my $option (@$d) {
12966: 	    my ($value,$display,$defaultcol)=@{ $option };
12967: 	    $r->print('<option value="'.$value.'"'.
12968:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12969:                       $display.'</option>');
12970: 	}
12971: 	$r->print('</select></td><td>');
12972: 	foreach my $line (0..($max_samples-1)) {
12973: 	    if (defined($samples->[$line]{$key})) { 
12974: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12975: 	    }
12976: 	}
12977: 	$r->print('</td>'.&end_data_table_row());
12978: 	$i++;
12979:     }
12980:     $r->print(&end_data_table());
12981:     $i--;
12982:     return($i);
12983: }
12984: 
12985: ######################################################
12986: ######################################################
12987: 
12988: =pod
12989: 
12990: =item * &clean_excel_name($name)
12991: 
12992: Returns a replacement for $name which does not contain any illegal characters.
12993: 
12994: =cut
12995: 
12996: ######################################################
12997: ######################################################
12998: sub clean_excel_name {
12999:     my ($name) = @_;
13000:     $name =~ s/[:\*\?\/\\]//g;
13001:     if (length($name) > 31) {
13002:         $name = substr($name,0,31);
13003:     }
13004:     return $name;
13005: }
13006: 
13007: =pod
13008: 
13009: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13010: 
13011: Returns either 1 or undef
13012: 
13013: 1 if the part is to be hidden, undef if it is to be shown
13014: 
13015: Arguments are:
13016: 
13017: $id the id of the part to be checked
13018: $symb, optional the symb of the resource to check
13019: $udom, optional the domain of the user to check for
13020: $uname, optional the username of the user to check for
13021: 
13022: =cut
13023: 
13024: sub check_if_partid_hidden {
13025:     my ($id,$symb,$udom,$uname) = @_;
13026:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13027: 					 $symb,$udom,$uname);
13028:     my $truth=1;
13029:     #if the string starts with !, then the list is the list to show not hide
13030:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13031:     my @hiddenlist=split(/,/,$hiddenparts);
13032:     foreach my $checkid (@hiddenlist) {
13033: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13034:     }
13035:     return !$truth;
13036: }
13037: 
13038: 
13039: ############################################################
13040: ############################################################
13041: 
13042: =pod
13043: 
13044: =back 
13045: 
13046: =head1 cgi-bin script and graphing routines
13047: 
13048: =over 4
13049: 
13050: =item * &get_cgi_id()
13051: 
13052: Inputs: none
13053: 
13054: Returns an id which can be used to pass environment variables
13055: to various cgi-bin scripts.  These environment variables will
13056: be removed from the users environment after a given time by
13057: the routine &Apache::lonnet::transfer_profile_to_env.
13058: 
13059: =cut
13060: 
13061: ############################################################
13062: ############################################################
13063: my $uniq=0;
13064: sub get_cgi_id {
13065:     $uniq=($uniq+1)%100000;
13066:     return (time.'_'.$$.'_'.$uniq);
13067: }
13068: 
13069: ############################################################
13070: ############################################################
13071: 
13072: =pod
13073: 
13074: =item * &DrawBarGraph()
13075: 
13076: Facilitates the plotting of data in a (stacked) bar graph.
13077: Puts plot definition data into the users environment in order for 
13078: graph.png to plot it.  Returns an <img> tag for the plot.
13079: The bars on the plot are labeled '1','2',...,'n'.
13080: 
13081: Inputs:
13082: 
13083: =over 4
13084: 
13085: =item $Title: string, the title of the plot
13086: 
13087: =item $xlabel: string, text describing the X-axis of the plot
13088: 
13089: =item $ylabel: string, text describing the Y-axis of the plot
13090: 
13091: =item $Max: scalar, the maximum Y value to use in the plot
13092: If $Max is < any data point, the graph will not be rendered.
13093: 
13094: =item $colors: array ref holding the colors to be used for the data sets when
13095: they are plotted.  If undefined, default values will be used.
13096: 
13097: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13098: 
13099: =item @Values: An array of array references.  Each array reference holds data
13100: to be plotted in a stacked bar chart.
13101: 
13102: =item If the final element of @Values is a hash reference the key/value
13103: pairs will be added to the graph definition.
13104: 
13105: =back
13106: 
13107: Returns:
13108: 
13109: An <img> tag which references graph.png and the appropriate identifying
13110: information for the plot.
13111: 
13112: =cut
13113: 
13114: ############################################################
13115: ############################################################
13116: sub DrawBarGraph {
13117:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13118:     #
13119:     if (! defined($colors)) {
13120:         $colors = ['#33ff00', 
13121:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13122:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13123:                   ]; 
13124:     }
13125:     my $extra_settings = {};
13126:     if (ref($Values[-1]) eq 'HASH') {
13127:         $extra_settings = pop(@Values);
13128:     }
13129:     #
13130:     my $identifier = &get_cgi_id();
13131:     my $id = 'cgi.'.$identifier;        
13132:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13133:         return '';
13134:     }
13135:     #
13136:     my @Labels;
13137:     if (defined($labels)) {
13138:         @Labels = @$labels;
13139:     } else {
13140:         for (my $i=0;$i<@{$Values[0]};$i++) {
13141:             push (@Labels,$i+1);
13142:         }
13143:     }
13144:     #
13145:     my $NumBars = scalar(@{$Values[0]});
13146:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13147:     my %ValuesHash;
13148:     my $NumSets=1;
13149:     foreach my $array (@Values) {
13150:         next if (! ref($array));
13151:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13152:             join(',',@$array);
13153:     }
13154:     #
13155:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13156:     if ($NumBars < 3) {
13157:         $width = 120+$NumBars*32;
13158:         $xskip = 1;
13159:         $bar_width = 30;
13160:     } elsif ($NumBars < 5) {
13161:         $width = 120+$NumBars*20;
13162:         $xskip = 1;
13163:         $bar_width = 20;
13164:     } elsif ($NumBars < 10) {
13165:         $width = 120+$NumBars*15;
13166:         $xskip = 1;
13167:         $bar_width = 15;
13168:     } elsif ($NumBars <= 25) {
13169:         $width = 120+$NumBars*11;
13170:         $xskip = 5;
13171:         $bar_width = 8;
13172:     } elsif ($NumBars <= 50) {
13173:         $width = 120+$NumBars*8;
13174:         $xskip = 5;
13175:         $bar_width = 4;
13176:     } else {
13177:         $width = 120+$NumBars*8;
13178:         $xskip = 5;
13179:         $bar_width = 4;
13180:     }
13181:     #
13182:     $Max = 1 if ($Max < 1);
13183:     if ( int($Max) < $Max ) {
13184:         $Max++;
13185:         $Max = int($Max);
13186:     }
13187:     $Title  = '' if (! defined($Title));
13188:     $xlabel = '' if (! defined($xlabel));
13189:     $ylabel = '' if (! defined($ylabel));
13190:     $ValuesHash{$id.'.title'}    = &escape($Title);
13191:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13192:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13193:     $ValuesHash{$id.'.y_max_value'} = $Max;
13194:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13195:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13196:     $ValuesHash{$id.'.PlotType'} = 'bar';
13197:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13198:     $ValuesHash{$id.'.height'}   = $height;
13199:     $ValuesHash{$id.'.width'}    = $width;
13200:     $ValuesHash{$id.'.xskip'}    = $xskip;
13201:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13202:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13203:     #
13204:     # Deal with other parameters
13205:     while (my ($key,$value) = each(%$extra_settings)) {
13206:         $ValuesHash{$id.'.'.$key} = $value;
13207:     }
13208:     #
13209:     &Apache::lonnet::appenv(\%ValuesHash);
13210:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13211: }
13212: 
13213: ############################################################
13214: ############################################################
13215: 
13216: =pod
13217: 
13218: =item * &DrawXYGraph()
13219: 
13220: Facilitates the plotting of data in an XY graph.
13221: Puts plot definition data into the users environment in order for 
13222: graph.png to plot it.  Returns an <img> tag for the plot.
13223: 
13224: Inputs:
13225: 
13226: =over 4
13227: 
13228: =item $Title: string, the title of the plot
13229: 
13230: =item $xlabel: string, text describing the X-axis of the plot
13231: 
13232: =item $ylabel: string, text describing the Y-axis of the plot
13233: 
13234: =item $Max: scalar, the maximum Y value to use in the plot
13235: If $Max is < any data point, the graph will not be rendered.
13236: 
13237: =item $colors: Array ref containing the hex color codes for the data to be 
13238: plotted in.  If undefined, default values will be used.
13239: 
13240: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13241: 
13242: =item $Ydata: Array ref containing Array refs.  
13243: Each of the contained arrays will be plotted as a separate curve.
13244: 
13245: =item %Values: hash indicating or overriding any default values which are 
13246: passed to graph.png.  
13247: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13248: 
13249: =back
13250: 
13251: Returns:
13252: 
13253: An <img> tag which references graph.png and the appropriate identifying
13254: information for the plot.
13255: 
13256: =cut
13257: 
13258: ############################################################
13259: ############################################################
13260: sub DrawXYGraph {
13261:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13262:     #
13263:     # Create the identifier for the graph
13264:     my $identifier = &get_cgi_id();
13265:     my $id = 'cgi.'.$identifier;
13266:     #
13267:     $Title  = '' if (! defined($Title));
13268:     $xlabel = '' if (! defined($xlabel));
13269:     $ylabel = '' if (! defined($ylabel));
13270:     my %ValuesHash = 
13271:         (
13272:          $id.'.title'  => &escape($Title),
13273:          $id.'.xlabel' => &escape($xlabel),
13274:          $id.'.ylabel' => &escape($ylabel),
13275:          $id.'.y_max_value'=> $Max,
13276:          $id.'.labels'     => join(',',@$Xlabels),
13277:          $id.'.PlotType'   => 'XY',
13278:          );
13279:     #
13280:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13281:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13282:     }
13283:     #
13284:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13285:         return '';
13286:     }
13287:     my $NumSets=1;
13288:     foreach my $array (@{$Ydata}){
13289:         next if (! ref($array));
13290:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13291:     }
13292:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13293:     #
13294:     # Deal with other parameters
13295:     while (my ($key,$value) = each(%Values)) {
13296:         $ValuesHash{$id.'.'.$key} = $value;
13297:     }
13298:     #
13299:     &Apache::lonnet::appenv(\%ValuesHash);
13300:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13301: }
13302: 
13303: ############################################################
13304: ############################################################
13305: 
13306: =pod
13307: 
13308: =item * &DrawXYYGraph()
13309: 
13310: Facilitates the plotting of data in an XY graph with two Y axes.
13311: Puts plot definition data into the users environment in order for 
13312: graph.png to plot it.  Returns an <img> tag for the plot.
13313: 
13314: Inputs:
13315: 
13316: =over 4
13317: 
13318: =item $Title: string, the title of the plot
13319: 
13320: =item $xlabel: string, text describing the X-axis of the plot
13321: 
13322: =item $ylabel: string, text describing the Y-axis of the plot
13323: 
13324: =item $colors: Array ref containing the hex color codes for the data to be 
13325: plotted in.  If undefined, default values will be used.
13326: 
13327: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13328: 
13329: =item $Ydata1: The first data set
13330: 
13331: =item $Min1: The minimum value of the left Y-axis
13332: 
13333: =item $Max1: The maximum value of the left Y-axis
13334: 
13335: =item $Ydata2: The second data set
13336: 
13337: =item $Min2: The minimum value of the right Y-axis
13338: 
13339: =item $Max2: The maximum value of the left Y-axis
13340: 
13341: =item %Values: hash indicating or overriding any default values which are 
13342: passed to graph.png.  
13343: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13344: 
13345: =back
13346: 
13347: Returns:
13348: 
13349: An <img> tag which references graph.png and the appropriate identifying
13350: information for the plot.
13351: 
13352: =cut
13353: 
13354: ############################################################
13355: ############################################################
13356: sub DrawXYYGraph {
13357:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13358:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13359:     #
13360:     # Create the identifier for the graph
13361:     my $identifier = &get_cgi_id();
13362:     my $id = 'cgi.'.$identifier;
13363:     #
13364:     $Title  = '' if (! defined($Title));
13365:     $xlabel = '' if (! defined($xlabel));
13366:     $ylabel = '' if (! defined($ylabel));
13367:     my %ValuesHash = 
13368:         (
13369:          $id.'.title'  => &escape($Title),
13370:          $id.'.xlabel' => &escape($xlabel),
13371:          $id.'.ylabel' => &escape($ylabel),
13372:          $id.'.labels' => join(',',@$Xlabels),
13373:          $id.'.PlotType' => 'XY',
13374:          $id.'.NumSets' => 2,
13375:          $id.'.two_axes' => 1,
13376:          $id.'.y1_max_value' => $Max1,
13377:          $id.'.y1_min_value' => $Min1,
13378:          $id.'.y2_max_value' => $Max2,
13379:          $id.'.y2_min_value' => $Min2,
13380:          );
13381:     #
13382:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13383:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13384:     }
13385:     #
13386:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13387:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13388:         return '';
13389:     }
13390:     my $NumSets=1;
13391:     foreach my $array ($Ydata1,$Ydata2){
13392:         next if (! ref($array));
13393:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13394:     }
13395:     #
13396:     # Deal with other parameters
13397:     while (my ($key,$value) = each(%Values)) {
13398:         $ValuesHash{$id.'.'.$key} = $value;
13399:     }
13400:     #
13401:     &Apache::lonnet::appenv(\%ValuesHash);
13402:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13403: }
13404: 
13405: ############################################################
13406: ############################################################
13407: 
13408: =pod
13409: 
13410: =back 
13411: 
13412: =head1 Statistics helper routines?  
13413: 
13414: Bad place for them but what the hell.
13415: 
13416: =over 4
13417: 
13418: =item * &chartlink()
13419: 
13420: Returns a link to the chart for a specific student.  
13421: 
13422: Inputs:
13423: 
13424: =over 4
13425: 
13426: =item $linktext: The text of the link
13427: 
13428: =item $sname: The students username
13429: 
13430: =item $sdomain: The students domain
13431: 
13432: =back
13433: 
13434: =back
13435: 
13436: =cut
13437: 
13438: ############################################################
13439: ############################################################
13440: sub chartlink {
13441:     my ($linktext, $sname, $sdomain) = @_;
13442:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13443:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13444:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13445:        '">'.$linktext.'</a>';
13446: }
13447: 
13448: #######################################################
13449: #######################################################
13450: 
13451: =pod
13452: 
13453: =head1 Course Environment Routines
13454: 
13455: =over 4
13456: 
13457: =item * &restore_course_settings()
13458: 
13459: =item * &store_course_settings()
13460: 
13461: Restores/Store indicated form parameters from the course environment.
13462: Will not overwrite existing values of the form parameters.
13463: 
13464: Inputs: 
13465: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13466: 
13467: a hash ref describing the data to be stored.  For example:
13468:    
13469: %Save_Parameters = ('Status' => 'scalar',
13470:     'chartoutputmode' => 'scalar',
13471:     'chartoutputdata' => 'scalar',
13472:     'Section' => 'array',
13473:     'Group' => 'array',
13474:     'StudentData' => 'array',
13475:     'Maps' => 'array');
13476: 
13477: Returns: both routines return nothing
13478: 
13479: =back
13480: 
13481: =cut
13482: 
13483: #######################################################
13484: #######################################################
13485: sub store_course_settings {
13486:     return &store_settings($env{'request.course.id'},@_);
13487: }
13488: 
13489: sub store_settings {
13490:     # save to the environment
13491:     # appenv the same items, just to be safe
13492:     my $udom  = $env{'user.domain'};
13493:     my $uname = $env{'user.name'};
13494:     my ($context,$prefix,$Settings) = @_;
13495:     my %SaveHash;
13496:     my %AppHash;
13497:     while (my ($setting,$type) = each(%$Settings)) {
13498:         my $basename = join('.','internal',$context,$prefix,$setting);
13499:         my $envname = 'environment.'.$basename;
13500:         if (exists($env{'form.'.$setting})) {
13501:             # Save this value away
13502:             if ($type eq 'scalar' &&
13503:                 (! exists($env{$envname}) || 
13504:                  $env{$envname} ne $env{'form.'.$setting})) {
13505:                 $SaveHash{$basename} = $env{'form.'.$setting};
13506:                 $AppHash{$envname}   = $env{'form.'.$setting};
13507:             } elsif ($type eq 'array') {
13508:                 my $stored_form;
13509:                 if (ref($env{'form.'.$setting})) {
13510:                     $stored_form = join(',',
13511:                                         map {
13512:                                             &escape($_);
13513:                                         } sort(@{$env{'form.'.$setting}}));
13514:                 } else {
13515:                     $stored_form = 
13516:                         &escape($env{'form.'.$setting});
13517:                 }
13518:                 # Determine if the array contents are the same.
13519:                 if ($stored_form ne $env{$envname}) {
13520:                     $SaveHash{$basename} = $stored_form;
13521:                     $AppHash{$envname}   = $stored_form;
13522:                 }
13523:             }
13524:         }
13525:     }
13526:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13527:                                           $udom,$uname);
13528:     if ($put_result !~ /^(ok|delayed)/) {
13529:         &Apache::lonnet::logthis('unable to save form parameters, '.
13530:                                  'got error:'.$put_result);
13531:     }
13532:     # Make sure these settings stick around in this session, too
13533:     &Apache::lonnet::appenv(\%AppHash);
13534:     return;
13535: }
13536: 
13537: sub restore_course_settings {
13538:     return &restore_settings($env{'request.course.id'},@_);
13539: }
13540: 
13541: sub restore_settings {
13542:     my ($context,$prefix,$Settings) = @_;
13543:     while (my ($setting,$type) = each(%$Settings)) {
13544:         next if (exists($env{'form.'.$setting}));
13545:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13546:             '.'.$setting;
13547:         if (exists($env{$envname})) {
13548:             if ($type eq 'scalar') {
13549:                 $env{'form.'.$setting} = $env{$envname};
13550:             } elsif ($type eq 'array') {
13551:                 $env{'form.'.$setting} = [ 
13552:                                            map { 
13553:                                                &unescape($_); 
13554:                                            } split(',',$env{$envname})
13555:                                            ];
13556:             }
13557:         }
13558:     }
13559: }
13560: 
13561: #######################################################
13562: #######################################################
13563: 
13564: =pod
13565: 
13566: =head1 Domain E-mail Routines  
13567: 
13568: =over 4
13569: 
13570: =item * &build_recipient_list()
13571: 
13572: Build recipient lists for following types of e-mail:
13573: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13574: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13575: module change checking, student/employee ID conflict checks, as
13576: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13577: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13578: 
13579: Inputs:
13580: defmail (scalar - email address of default recipient),
13581: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13582: requestsmail, updatesmail, or idconflictsmail).
13583: 
13584: defdom (domain for which to retrieve configuration settings),
13585: 
13586: origmail (scalar - email address of recipient from loncapa.conf,
13587: i.e., predates configuration by DC via domainprefs.pm
13588: 
13589: Returns: comma separated list of addresses to which to send e-mail.
13590: 
13591: =back
13592: 
13593: =cut
13594: 
13595: ############################################################
13596: ############################################################
13597: sub build_recipient_list {
13598:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13599:     my @recipients;
13600:     my $otheremails;
13601:     my %domconfig =
13602:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13603:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13604:         if (exists($domconfig{'contacts'}{$mailing})) {
13605:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13606:                 my @contacts = ('adminemail','supportemail');
13607:                 foreach my $item (@contacts) {
13608:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13609:                         my $addr = $domconfig{'contacts'}{$item}; 
13610:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13611:                             push(@recipients,$addr);
13612:                         }
13613:                     }
13614:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13615:                 }
13616:             }
13617:         } elsif ($origmail ne '') {
13618:             push(@recipients,$origmail);
13619:         }
13620:     } elsif ($origmail ne '') {
13621:         push(@recipients,$origmail);
13622:     }
13623:     if (defined($defmail)) {
13624:         if ($defmail ne '') {
13625:             push(@recipients,$defmail);
13626:         }
13627:     }
13628:     if ($otheremails) {
13629:         my @others;
13630:         if ($otheremails =~ /,/) {
13631:             @others = split(/,/,$otheremails);
13632:         } else {
13633:             push(@others,$otheremails);
13634:         }
13635:         foreach my $addr (@others) {
13636:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13637:                 push(@recipients,$addr);
13638:             }
13639:         }
13640:     }
13641:     my $recipientlist = join(',',@recipients); 
13642:     return $recipientlist;
13643: }
13644: 
13645: ############################################################
13646: ############################################################
13647: 
13648: =pod
13649: 
13650: =head1 Course Catalog Routines
13651: 
13652: =over 4
13653: 
13654: =item * &gather_categories()
13655: 
13656: Converts category definitions - keys of categories hash stored in  
13657: coursecategories in configuration.db on the primary library server in a 
13658: domain - to an array.  Also generates javascript and idx hash used to 
13659: generate Domain Coordinator interface for editing Course Categories.
13660: 
13661: Inputs:
13662: 
13663: categories (reference to hash of category definitions).
13664: 
13665: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13666:       categories and subcategories).
13667: 
13668: idx (reference to hash of counters used in Domain Coordinator interface for 
13669:       editing Course Categories).
13670: 
13671: jsarray (reference to array of categories used to create Javascript arrays for
13672:          Domain Coordinator interface for editing Course Categories).
13673: 
13674: Returns: nothing
13675: 
13676: Side effects: populates cats, idx and jsarray. 
13677: 
13678: =cut
13679: 
13680: sub gather_categories {
13681:     my ($categories,$cats,$idx,$jsarray) = @_;
13682:     my %counters;
13683:     my $num = 0;
13684:     foreach my $item (keys(%{$categories})) {
13685:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13686:         if ($container eq '' && $depth == 0) {
13687:             $cats->[$depth][$categories->{$item}] = $cat;
13688:         } else {
13689:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13690:         }
13691:         my ($escitem,$tail) = split(/:/,$item,2);
13692:         if ($counters{$tail} eq '') {
13693:             $counters{$tail} = $num;
13694:             $num ++;
13695:         }
13696:         if (ref($idx) eq 'HASH') {
13697:             $idx->{$item} = $counters{$tail};
13698:         }
13699:         if (ref($jsarray) eq 'ARRAY') {
13700:             push(@{$jsarray->[$counters{$tail}]},$item);
13701:         }
13702:     }
13703:     return;
13704: }
13705: 
13706: =pod
13707: 
13708: =item * &extract_categories()
13709: 
13710: Used to generate breadcrumb trails for course categories.
13711: 
13712: Inputs:
13713: 
13714: categories (reference to hash of category definitions).
13715: 
13716: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13717:       categories and subcategories).
13718: 
13719: trails (reference to array of breacrumb trails for each category).
13720: 
13721: allitems (reference to hash - key is category key 
13722:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13723: 
13724: idx (reference to hash of counters used in Domain Coordinator interface for
13725:       editing Course Categories).
13726: 
13727: jsarray (reference to array of categories used to create Javascript arrays for
13728:          Domain Coordinator interface for editing Course Categories).
13729: 
13730: subcats (reference to hash of arrays containing all subcategories within each 
13731:          category, -recursive)
13732: 
13733: Returns: nothing
13734: 
13735: Side effects: populates trails and allitems hash references.
13736: 
13737: =cut
13738: 
13739: sub extract_categories {
13740:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13741:     if (ref($categories) eq 'HASH') {
13742:         &gather_categories($categories,$cats,$idx,$jsarray);
13743:         if (ref($cats->[0]) eq 'ARRAY') {
13744:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13745:                 my $name = $cats->[0][$i];
13746:                 my $item = &escape($name).'::0';
13747:                 my $trailstr;
13748:                 if ($name eq 'instcode') {
13749:                     $trailstr = &mt('Official courses (with institutional codes)');
13750:                 } elsif ($name eq 'communities') {
13751:                     $trailstr = &mt('Communities');
13752:                 } else {
13753:                     $trailstr = $name;
13754:                 }
13755:                 if ($allitems->{$item} eq '') {
13756:                     push(@{$trails},$trailstr);
13757:                     $allitems->{$item} = scalar(@{$trails})-1;
13758:                 }
13759:                 my @parents = ($name);
13760:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13761:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13762:                         my $category = $cats->[1]{$name}[$j];
13763:                         if (ref($subcats) eq 'HASH') {
13764:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13765:                         }
13766:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13767:                     }
13768:                 } else {
13769:                     if (ref($subcats) eq 'HASH') {
13770:                         $subcats->{$item} = [];
13771:                     }
13772:                 }
13773:             }
13774:         }
13775:     }
13776:     return;
13777: }
13778: 
13779: =pod
13780: 
13781: =item * &recurse_categories()
13782: 
13783: Recursively used to generate breadcrumb trails for course categories.
13784: 
13785: Inputs:
13786: 
13787: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13788:       categories and subcategories).
13789: 
13790: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13791: 
13792: category (current course category, for which breadcrumb trail is being generated).
13793: 
13794: trails (reference to array of breadcrumb trails for each category).
13795: 
13796: allitems (reference to hash - key is category key
13797:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13798: 
13799: parents (array containing containers directories for current category, 
13800:          back to top level). 
13801: 
13802: Returns: nothing
13803: 
13804: Side effects: populates trails and allitems hash references
13805: 
13806: =cut
13807: 
13808: sub recurse_categories {
13809:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13810:     my $shallower = $depth - 1;
13811:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13812:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13813:             my $name = $cats->[$depth]{$category}[$k];
13814:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13815:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13816:             if ($allitems->{$item} eq '') {
13817:                 push(@{$trails},$trailstr);
13818:                 $allitems->{$item} = scalar(@{$trails})-1;
13819:             }
13820:             my $deeper = $depth+1;
13821:             push(@{$parents},$category);
13822:             if (ref($subcats) eq 'HASH') {
13823:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13824:                 for (my $j=@{$parents}; $j>=0; $j--) {
13825:                     my $higher;
13826:                     if ($j > 0) {
13827:                         $higher = &escape($parents->[$j]).':'.
13828:                                   &escape($parents->[$j-1]).':'.$j;
13829:                     } else {
13830:                         $higher = &escape($parents->[$j]).'::'.$j;
13831:                     }
13832:                     push(@{$subcats->{$higher}},$subcat);
13833:                 }
13834:             }
13835:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13836:                                 $subcats);
13837:             pop(@{$parents});
13838:         }
13839:     } else {
13840:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13841:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13842:         if ($allitems->{$item} eq '') {
13843:             push(@{$trails},$trailstr);
13844:             $allitems->{$item} = scalar(@{$trails})-1;
13845:         }
13846:     }
13847:     return;
13848: }
13849: 
13850: =pod
13851: 
13852: =item * &assign_categories_table()
13853: 
13854: Create a datatable for display of hierarchical categories in a domain,
13855: with checkboxes to allow a course to be categorized. 
13856: 
13857: Inputs:
13858: 
13859: cathash - reference to hash of categories defined for the domain (from
13860:           configuration.db)
13861: 
13862: currcat - scalar with an & separated list of categories assigned to a course. 
13863: 
13864: type    - scalar contains course type (Course or Community).
13865: 
13866: Returns: $output (markup to be displayed) 
13867: 
13868: =cut
13869: 
13870: sub assign_categories_table {
13871:     my ($cathash,$currcat,$type) = @_;
13872:     my $output;
13873:     if (ref($cathash) eq 'HASH') {
13874:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13875:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13876:         $maxdepth = scalar(@cats);
13877:         if (@cats > 0) {
13878:             my $itemcount = 0;
13879:             if (ref($cats[0]) eq 'ARRAY') {
13880:                 my @currcategories;
13881:                 if ($currcat ne '') {
13882:                     @currcategories = split('&',$currcat);
13883:                 }
13884:                 my $table;
13885:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13886:                     my $parent = $cats[0][$i];
13887:                     next if ($parent eq 'instcode');
13888:                     if ($type eq 'Community') {
13889:                         next unless ($parent eq 'communities');
13890:                     } else {
13891:                         next if ($parent eq 'communities');
13892:                     }
13893:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13894:                     my $item = &escape($parent).'::0';
13895:                     my $checked = '';
13896:                     if (@currcategories > 0) {
13897:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13898:                             $checked = ' checked="checked"';
13899:                         }
13900:                     }
13901:                     my $parent_title = $parent;
13902:                     if ($parent eq 'communities') {
13903:                         $parent_title = &mt('Communities');
13904:                     }
13905:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13906:                               '<input type="checkbox" name="usecategory" value="'.
13907:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13908:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13909:                     my $depth = 1;
13910:                     push(@path,$parent);
13911:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13912:                     pop(@path);
13913:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13914:                     $itemcount ++;
13915:                 }
13916:                 if ($itemcount) {
13917:                     $output = &Apache::loncommon::start_data_table().
13918:                               $table.
13919:                               &Apache::loncommon::end_data_table();
13920:                 }
13921:             }
13922:         }
13923:     }
13924:     return $output;
13925: }
13926: 
13927: =pod
13928: 
13929: =item * &assign_category_rows()
13930: 
13931: Create a datatable row for display of nested categories in a domain,
13932: with checkboxes to allow a course to be categorized,called recursively.
13933: 
13934: Inputs:
13935: 
13936: itemcount - track row number for alternating colors
13937: 
13938: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13939:       categories and subcategories.
13940: 
13941: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13942: 
13943: parent - parent of current category item
13944: 
13945: path - Array containing all categories back up through the hierarchy from the
13946:        current category to the top level.
13947: 
13948: currcategories - reference to array of current categories assigned to the course
13949: 
13950: Returns: $output (markup to be displayed).
13951: 
13952: =cut
13953: 
13954: sub assign_category_rows {
13955:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13956:     my ($text,$name,$item,$chgstr);
13957:     if (ref($cats) eq 'ARRAY') {
13958:         my $maxdepth = scalar(@{$cats});
13959:         if (ref($cats->[$depth]) eq 'HASH') {
13960:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13961:                 my $numchildren = @{$cats->[$depth]{$parent}};
13962:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13963:                 $text .= '<td><table class="LC_data_table">';
13964:                 for (my $j=0; $j<$numchildren; $j++) {
13965:                     $name = $cats->[$depth]{$parent}[$j];
13966:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13967:                     my $deeper = $depth+1;
13968:                     my $checked = '';
13969:                     if (ref($currcategories) eq 'ARRAY') {
13970:                         if (@{$currcategories} > 0) {
13971:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13972:                                 $checked = ' checked="checked"';
13973:                             }
13974:                         }
13975:                     }
13976:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13977:                              '<input type="checkbox" name="usecategory" value="'.
13978:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13979:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13980:                              '</td><td>';
13981:                     if (ref($path) eq 'ARRAY') {
13982:                         push(@{$path},$name);
13983:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13984:                         pop(@{$path});
13985:                     }
13986:                     $text .= '</td></tr>';
13987:                 }
13988:                 $text .= '</table></td>';
13989:             }
13990:         }
13991:     }
13992:     return $text;
13993: }
13994: 
13995: =pod
13996: 
13997: =back
13998: 
13999: =cut
14000: 
14001: ############################################################
14002: ############################################################
14003: 
14004: 
14005: sub commit_customrole {
14006:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14007:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14008:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14009:                          ($end?', ending '.localtime($end):'').': <b>'.
14010:               &Apache::lonnet::assigncustomrole(
14011:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14012:                  '</b><br />';
14013:     return $output;
14014: }
14015: 
14016: sub commit_standardrole {
14017:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14018:     my ($output,$logmsg,$linefeed);
14019:     if ($context eq 'auto') {
14020:         $linefeed = "\n";
14021:     } else {
14022:         $linefeed = "<br />\n";
14023:     }  
14024:     if ($three eq 'st') {
14025:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14026:                                          $one,$two,$sec,$context,$credits);
14027:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14028:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14029:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14030:         } else {
14031:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14032:                ($start?', '.&mt('starting').' '.localtime($start):'').
14033:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14034:             if ($context eq 'auto') {
14035:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14036:             } else {
14037:                $output .= '<b>'.$result.'</b>'.$linefeed.
14038:                &mt('Add to classlist').': <b>ok</b>';
14039:             }
14040:             $output .= $linefeed;
14041:         }
14042:     } else {
14043:         $output = &mt('Assigning').' '.$three.' in '.$url.
14044:                ($start?', '.&mt('starting').' '.localtime($start):'').
14045:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14046:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14047:         if ($context eq 'auto') {
14048:             $output .= $result.$linefeed;
14049:         } else {
14050:             $output .= '<b>'.$result.'</b>'.$linefeed;
14051:         }
14052:     }
14053:     return $output;
14054: }
14055: 
14056: sub commit_studentrole {
14057:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14058:         $credits) = @_;
14059:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14060:     if ($context eq 'auto') {
14061:         $linefeed = "\n";
14062:     } else {
14063:         $linefeed = '<br />'."\n";
14064:     }
14065:     if (defined($one) && defined($two)) {
14066:         my $cid=$one.'_'.$two;
14067:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14068:         my $secchange = 0;
14069:         my $expire_role_result;
14070:         my $modify_section_result;
14071:         if ($oldsec ne '-1') { 
14072:             if ($oldsec ne $sec) {
14073:                 $secchange = 1;
14074:                 my $now = time;
14075:                 my $uurl='/'.$cid;
14076:                 $uurl=~s/\_/\//g;
14077:                 if ($oldsec) {
14078:                     $uurl.='/'.$oldsec;
14079:                 }
14080:                 $oldsecurl = $uurl;
14081:                 $expire_role_result = 
14082:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14083:                 if ($env{'request.course.sec'} ne '') { 
14084:                     if ($expire_role_result eq 'refused') {
14085:                         my @roles = ('st');
14086:                         my @statuses = ('previous');
14087:                         my @roledoms = ($one);
14088:                         my $withsec = 1;
14089:                         my %roleshash = 
14090:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14091:                                               \@statuses,\@roles,\@roledoms,$withsec);
14092:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14093:                             my ($oldstart,$oldend) = 
14094:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14095:                             if ($oldend > 0 && $oldend <= $now) {
14096:                                 $expire_role_result = 'ok';
14097:                             }
14098:                         }
14099:                     }
14100:                 }
14101:                 $result = $expire_role_result;
14102:             }
14103:         }
14104:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14105:             $modify_section_result = 
14106:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14107:                                                            undef,undef,undef,$sec,
14108:                                                            $end,$start,'','',$cid,
14109:                                                            '',$context,$credits);
14110:             if ($modify_section_result =~ /^ok/) {
14111:                 if ($secchange == 1) {
14112:                     if ($sec eq '') {
14113:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14114:                     } else {
14115:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14116:                     }
14117:                 } elsif ($oldsec eq '-1') {
14118:                     if ($sec eq '') {
14119:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14120:                     } else {
14121:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14122:                     }
14123:                 } else {
14124:                     if ($sec eq '') {
14125:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14126:                     } else {
14127:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14128:                     }
14129:                 }
14130:             } else {
14131:                 if ($secchange) {       
14132:                     $$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;
14133:                 } else {
14134:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14135:                 }
14136:             }
14137:             $result = $modify_section_result;
14138:         } elsif ($secchange == 1) {
14139:             if ($oldsec eq '') {
14140:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14141:             } else {
14142:                 $$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;
14143:             }
14144:             if ($expire_role_result eq 'refused') {
14145:                 my $newsecurl = '/'.$cid;
14146:                 $newsecurl =~ s/\_/\//g;
14147:                 if ($sec ne '') {
14148:                     $newsecurl.='/'.$sec;
14149:                 }
14150:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14151:                     if ($sec eq '') {
14152:                         $$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;
14153:                     } else {
14154:                         $$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;
14155:                     }
14156:                 }
14157:             }
14158:         }
14159:     } else {
14160:         $$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;
14161:         $result = "error: incomplete course id\n";
14162:     }
14163:     return $result;
14164: }
14165: 
14166: sub show_role_extent {
14167:     my ($scope,$context,$role) = @_;
14168:     $scope =~ s{^/}{};
14169:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14170:     push(@courseroles,'co');
14171:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14172:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14173:         $scope =~ s{/}{_};
14174:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14175:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14176:         my ($audom,$auname) = split(/\//,$scope);
14177:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14178:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14179:     } else {
14180:         $scope =~ s{/$}{};
14181:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14182:                    &Apache::lonnet::domain($scope,'description').'</span>');
14183:     }
14184: }
14185: 
14186: ############################################################
14187: ############################################################
14188: 
14189: sub check_clone {
14190:     my ($args,$linefeed) = @_;
14191:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14192:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14193:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14194:     my $clonemsg;
14195:     my $can_clone = 0;
14196:     my $lctype = lc($args->{'crstype'});
14197:     if ($lctype ne 'community') {
14198:         $lctype = 'course';
14199:     }
14200:     if ($clonehome eq 'no_host') {
14201:         if ($args->{'crstype'} eq 'Community') {
14202:             $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'});
14203:         } else {
14204:             $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'});
14205:         }     
14206:     } else {
14207: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14208:         if ($args->{'crstype'} eq 'Community') {
14209:             if ($clonedesc{'type'} ne 'Community') {
14210:                  $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'});
14211:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14212:             }
14213:         }
14214: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
14215:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14216: 	    $can_clone = 1;
14217: 	} else {
14218: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14219: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14220:             if ($clonehash{'cloners'} eq '') {
14221:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14222:                 if ($domdefs{'canclone'}) {
14223:                     unless ($domdefs{'canclone'} eq 'none') {
14224:                         if ($domdefs{'canclone'} eq 'domain') {
14225:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14226:                                 $can_clone = 1;
14227:                             }
14228:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14229:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14230:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14231:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14232:                                 $can_clone = 1;
14233:                             }
14234:                         }
14235:                     }
14236:                 }
14237:             } else {
14238: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14239:                 if (grep(/^\*$/,@cloners)) {
14240:                     $can_clone = 1;
14241:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14242:                     $can_clone = 1;
14243:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14244:                     $can_clone = 1;
14245:                 }
14246:                 unless ($can_clone) {
14247:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14248:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14249:                         my (%gotdomdefaults,%gotcodedefaults);
14250:                         foreach my $cloner (@cloners) {
14251:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14252:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14253:                                 my (%codedefaults,@code_order);
14254:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14255:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14256:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14257:                                     }
14258:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14259:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14260:                                     }
14261:                                 } else {
14262:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14263:                                                                             \%codedefaults,
14264:                                                                             \@code_order);
14265:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14266:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14267:                                 }
14268:                                 if (@code_order > 0) {
14269:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14270:                                                                                 $cloner,$clonehash{'internal.coursecode'},
14271:                                                                                 $args->{'crscode'})) {
14272:                                         $can_clone = 1;
14273:                                         last;
14274:                                     }
14275:                                 }
14276:                             }
14277:                         }
14278:                     }
14279:                 }
14280:             }
14281:             unless ($can_clone) {
14282:                 my $ccrole = 'cc';
14283:                 if ($args->{'crstype'} eq 'Community') {
14284:                     $ccrole = 'co';
14285:                 }
14286:                 my %roleshash =
14287:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
14288:                                                   $args->{'ccdomain'},
14289:                                                   'userroles',['active'],[$ccrole],
14290:                                                   [$args->{'clonedomain'}]);
14291:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14292:                     $can_clone = 1;
14293:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14294:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
14295:                     $can_clone = 1;
14296:                 }
14297:             }
14298:             unless ($can_clone) {
14299:                 if ($args->{'crstype'} eq 'Community') {
14300:                     $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'});
14301:                 } else {
14302:                     $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'});
14303: 	        }
14304: 	    }
14305:         }
14306:     }
14307:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14308: }
14309: 
14310: sub construct_course {
14311:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14312:     my $outcome;
14313:     my $linefeed =  '<br />'."\n";
14314:     if ($context eq 'auto') {
14315:         $linefeed = "\n";
14316:     }
14317: 
14318: #
14319: # Are we cloning?
14320: #
14321:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14322:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14323: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14324: 	if ($context ne 'auto') {
14325:             if ($clonemsg ne '') {
14326: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14327:             }
14328: 	}
14329: 	$outcome .= $clonemsg.$linefeed;
14330: 
14331:         if (!$can_clone) {
14332: 	    return (0,$outcome);
14333: 	}
14334:     }
14335: 
14336: #
14337: # Open course
14338: #
14339:     my $crstype = lc($args->{'crstype'});
14340:     my %cenv=();
14341:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14342:                                              $args->{'cdescr'},
14343:                                              $args->{'curl'},
14344:                                              $args->{'course_home'},
14345:                                              $args->{'nonstandard'},
14346:                                              $args->{'crscode'},
14347:                                              $args->{'ccuname'}.':'.
14348:                                              $args->{'ccdomain'},
14349:                                              $args->{'crstype'},
14350:                                              $cnum,$context,$category);
14351: 
14352:     # Note: The testing routines depend on this being output; see 
14353:     # Utils::Course. This needs to at least be output as a comment
14354:     # if anyone ever decides to not show this, and Utils::Course::new
14355:     # will need to be suitably modified.
14356:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14357:     if ($$courseid =~ /^error:/) {
14358:         return (0,$outcome);
14359:     }
14360: 
14361: #
14362: # Check if created correctly
14363: #
14364:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14365:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14366:     if ($crsuhome eq 'no_host') {
14367:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14368:         return (0,$outcome);
14369:     }
14370:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14371: 
14372: #
14373: # Do the cloning
14374: #   
14375:     if ($can_clone && $cloneid) {
14376: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14377: 	if ($context ne 'auto') {
14378: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14379: 	}
14380: 	$outcome .= $clonemsg.$linefeed;
14381: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14382: # Copy all files
14383: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14384: # Restore URL
14385: 	$cenv{'url'}=$oldcenv{'url'};
14386: # Restore title
14387: 	$cenv{'description'}=$oldcenv{'description'};
14388: # Restore creation date, creator and creation context.
14389:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14390:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14391:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14392: # Mark as cloned
14393: 	$cenv{'clonedfrom'}=$cloneid;
14394: # Need to clone grading mode
14395:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14396:         $cenv{'grading'}=$newenv{'grading'};
14397: # Do not clone these environment entries
14398:         &Apache::lonnet::del('environment',
14399:                   ['default_enrollment_start_date',
14400:                    'default_enrollment_end_date',
14401:                    'question.email',
14402:                    'policy.email',
14403:                    'comment.email',
14404:                    'pch.users.denied',
14405:                    'plc.users.denied',
14406:                    'hidefromcat',
14407:                    'checkforpriv',
14408:                    'categories',
14409:                    'internal.uniquecode'],
14410:                    $$crsudom,$$crsunum);
14411:         if ($args->{'textbook'}) {
14412:             $cenv{'internal.textbook'} = $args->{'textbook'};
14413:         }
14414:     }
14415: 
14416: #
14417: # Set environment (will override cloned, if existing)
14418: #
14419:     my @sections = ();
14420:     my @xlists = ();
14421:     if ($args->{'crstype'}) {
14422:         $cenv{'type'}=$args->{'crstype'};
14423:     }
14424:     if ($args->{'crsid'}) {
14425:         $cenv{'courseid'}=$args->{'crsid'};
14426:     }
14427:     if ($args->{'crscode'}) {
14428:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14429:     }
14430:     if ($args->{'crsquota'} ne '') {
14431:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14432:     } else {
14433:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14434:     }
14435:     if ($args->{'ccuname'}) {
14436:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14437:                                         ':'.$args->{'ccdomain'};
14438:     } else {
14439:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14440:     }
14441:     if ($args->{'defaultcredits'}) {
14442:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14443:     }
14444:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14445:     if ($args->{'crssections'}) {
14446:         $cenv{'internal.sectionnums'} = '';
14447:         if ($args->{'crssections'} =~ m/,/) {
14448:             @sections = split/,/,$args->{'crssections'};
14449:         } else {
14450:             $sections[0] = $args->{'crssections'};
14451:         }
14452:         if (@sections > 0) {
14453:             foreach my $item (@sections) {
14454:                 my ($sec,$gp) = split/:/,$item;
14455:                 my $class = $args->{'crscode'}.$sec;
14456:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14457:                 $cenv{'internal.sectionnums'} .= $item.',';
14458:                 unless ($addcheck eq 'ok') {
14459:                     push @badclasses, $class;
14460:                 }
14461:             }
14462:             $cenv{'internal.sectionnums'} =~ s/,$//;
14463:         }
14464:     }
14465: # do not hide course coordinator from staff listing, 
14466: # even if privileged
14467:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14468: # add course coordinator's domain to domains to check for privileged users
14469: # if different to course domain
14470:     if ($$crsudom ne $args->{'ccdomain'}) {
14471:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14472:     }
14473: # add crosslistings
14474:     if ($args->{'crsxlist'}) {
14475:         $cenv{'internal.crosslistings'}='';
14476:         if ($args->{'crsxlist'} =~ m/,/) {
14477:             @xlists = split/,/,$args->{'crsxlist'};
14478:         } else {
14479:             $xlists[0] = $args->{'crsxlist'};
14480:         }
14481:         if (@xlists > 0) {
14482:             foreach my $item (@xlists) {
14483:                 my ($xl,$gp) = split/:/,$item;
14484:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14485:                 $cenv{'internal.crosslistings'} .= $item.',';
14486:                 unless ($addcheck eq 'ok') {
14487:                     push @badclasses, $xl;
14488:                 }
14489:             }
14490:             $cenv{'internal.crosslistings'} =~ s/,$//;
14491:         }
14492:     }
14493:     if ($args->{'autoadds'}) {
14494:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14495:     }
14496:     if ($args->{'autodrops'}) {
14497:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14498:     }
14499: # check for notification of enrollment changes
14500:     my @notified = ();
14501:     if ($args->{'notify_owner'}) {
14502:         if ($args->{'ccuname'} ne '') {
14503:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14504:         }
14505:     }
14506:     if ($args->{'notify_dc'}) {
14507:         if ($uname ne '') { 
14508:             push(@notified,$uname.':'.$udom);
14509:         }
14510:     }
14511:     if (@notified > 0) {
14512:         my $notifylist;
14513:         if (@notified > 1) {
14514:             $notifylist = join(',',@notified);
14515:         } else {
14516:             $notifylist = $notified[0];
14517:         }
14518:         $cenv{'internal.notifylist'} = $notifylist;
14519:     }
14520:     if (@badclasses > 0) {
14521:         my %lt=&Apache::lonlocal::texthash(
14522:                 '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',
14523:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14524:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14525:         );
14526:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14527:                            ' ('.$lt{'adby'}.')';
14528:         if ($context eq 'auto') {
14529:             $outcome .= $badclass_msg.$linefeed;
14530:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14531:             foreach my $item (@badclasses) {
14532:                 if ($context eq 'auto') {
14533:                     $outcome .= " - $item\n";
14534:                 } else {
14535:                     $outcome .= "<li>$item</li>\n";
14536:                 }
14537:             }
14538:             if ($context eq 'auto') {
14539:                 $outcome .= $linefeed;
14540:             } else {
14541:                 $outcome .= "</ul><br /><br /></div>\n";
14542:             }
14543:         } 
14544:     }
14545:     if ($args->{'no_end_date'}) {
14546:         $args->{'endaccess'} = 0;
14547:     }
14548:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14549:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14550:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14551:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14552:     if ($args->{'showphotos'}) {
14553:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14554:     }
14555:     $cenv{'internal.authtype'} = $args->{'authtype'};
14556:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14557:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14558:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14559:             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'); 
14560:             if ($context eq 'auto') {
14561:                 $outcome .= $krb_msg;
14562:             } else {
14563:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14564:             }
14565:             $outcome .= $linefeed;
14566:         }
14567:     }
14568:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14569:        if ($args->{'setpolicy'}) {
14570:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14571:        }
14572:        if ($args->{'setcontent'}) {
14573:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14574:        }
14575:     }
14576:     if ($args->{'reshome'}) {
14577: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14578: 	$cenv{'reshome'}=~s/\/+$/\//;
14579:     }
14580: #
14581: # course has keyed access
14582: #
14583:     if ($args->{'setkeys'}) {
14584:        $cenv{'keyaccess'}='yes';
14585:     }
14586: # if specified, key authority is not course, but user
14587: # only active if keyaccess is yes
14588:     if ($args->{'keyauth'}) {
14589: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14590: 	$user = &LONCAPA::clean_username($user);
14591: 	$domain = &LONCAPA::clean_username($domain);
14592: 	if ($user ne '' && $domain ne '') {
14593: 	    $cenv{'keyauth'}=$user.':'.$domain;
14594: 	}
14595:     }
14596: 
14597: #
14598: #  generate and store uniquecode (available to course requester), if course should have one.
14599: #
14600:     if ($args->{'uniquecode'}) {
14601:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14602:         if ($code) {
14603:             $cenv{'internal.uniquecode'} = $code;
14604:             my %crsinfo =
14605:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14606:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14607:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14608:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14609:             }
14610:             if (ref($coderef)) {
14611:                 $$coderef = $code;
14612:             }
14613:         }
14614:     }
14615: 
14616:     if ($args->{'disresdis'}) {
14617:         $cenv{'pch.roles.denied'}='st';
14618:     }
14619:     if ($args->{'disablechat'}) {
14620:         $cenv{'plc.roles.denied'}='st';
14621:     }
14622: 
14623:     # Record we've not yet viewed the Course Initialization Helper for this 
14624:     # course
14625:     $cenv{'course.helper.not.run'} = 1;
14626:     #
14627:     # Use new Randomseed
14628:     #
14629:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14630:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14631:     #
14632:     # The encryption code and receipt prefix for this course
14633:     #
14634:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14635:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14636:     #
14637:     # By default, use standard grading
14638:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14639: 
14640:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14641:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14642: #
14643: # Open all assignments
14644: #
14645:     if ($args->{'openall'}) {
14646:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14647:        my %storecontent = ($storeunder         => time,
14648:                            $storeunder.'.type' => 'date_start');
14649:        
14650:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14651:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14652:    }
14653: #
14654: # Set first page
14655: #
14656:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14657: 	    || ($cloneid)) {
14658: 	use LONCAPA::map;
14659: 	$outcome .= &mt('Setting first resource').': ';
14660: 
14661: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14662:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14663: 
14664:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14665:         my $title; my $url;
14666:         if ($args->{'firstres'} eq 'syl') {
14667: 	    $title=&mt('Syllabus');
14668:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14669:         } else {
14670:             $title=&mt('Table of Contents');
14671:             $url='/adm/navmaps';
14672:         }
14673: 
14674:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14675: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14676: 
14677: 	if ($errtext) { $fatal=2; }
14678:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14679:     }
14680: 
14681:     return (1,$outcome);
14682: }
14683: 
14684: sub make_unique_code {
14685:     my ($cdom,$cnum) = @_;
14686:     # get lock on uniquecodes db
14687:     my $lockhash = {
14688:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
14689:                                                   ':'.$env{'user.domain'},
14690:                    };
14691:     my $tries = 0;
14692:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14693:     my ($code,$error);
14694: 
14695:     while (($gotlock ne 'ok') && ($tries<3)) {
14696:         $tries ++;
14697:         sleep 1;
14698:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14699:     }
14700:     if ($gotlock eq 'ok') {
14701:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14702:         my $gotcode;
14703:         my $attempts = 0;
14704:         while ((!$gotcode) && ($attempts < 100)) {
14705:             $code = &generate_code();
14706:             if (!exists($currcodes{$code})) {
14707:                 $gotcode = 1;
14708:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14709:                     $error = 'nostore';
14710:                 }
14711:             }
14712:             $attempts ++;
14713:         }
14714:         my @del_lock = ($cnum."\0".'uniquecodes');
14715:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14716:     } else {
14717:         $error = 'nolock';
14718:     }
14719:     return ($code,$error);
14720: }
14721: 
14722: sub generate_code {
14723:     my $code;
14724:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14725:     for (my $i=0; $i<6; $i++) {
14726:         my $lettnum = int (rand 2);
14727:         my $item = '';
14728:         if ($lettnum) {
14729:             $item = $letts[int( rand(18) )];
14730:         } else {
14731:             $item = 1+int( rand(8) );
14732:         }
14733:         $code .= $item;
14734:     }
14735:     return $code;
14736: }
14737: 
14738: ############################################################
14739: ############################################################
14740: 
14741: #SD
14742: # only Community and Course, or anything else?
14743: sub course_type {
14744:     my ($cid) = @_;
14745:     if (!defined($cid)) {
14746:         $cid = $env{'request.course.id'};
14747:     }
14748:     if (defined($env{'course.'.$cid.'.type'})) {
14749:         return $env{'course.'.$cid.'.type'};
14750:     } else {
14751:         return 'Course';
14752:     }
14753: }
14754: 
14755: sub group_term {
14756:     my $crstype = &course_type();
14757:     my %names = (
14758:                   'Course' => 'group',
14759:                   'Community' => 'group',
14760:                 );
14761:     return $names{$crstype};
14762: }
14763: 
14764: sub course_types {
14765:     my @types = ('official','unofficial','community','textbook');
14766:     my %typename = (
14767:                          official   => 'Official course',
14768:                          unofficial => 'Unofficial course',
14769:                          community  => 'Community',
14770:                          textbook   => 'Textbook course',
14771:                    );
14772:     return (\@types,\%typename);
14773: }
14774: 
14775: sub icon {
14776:     my ($file)=@_;
14777:     my $curfext = lc((split(/\./,$file))[-1]);
14778:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14779:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14780:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14781: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14782: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14783: 	            $curfext.".gif") {
14784: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14785: 		$curfext.".gif";
14786: 	}
14787:     }
14788:     return &lonhttpdurl($iconname);
14789: } 
14790: 
14791: sub lonhttpdurl {
14792: #
14793: # Had been used for "small fry" static images on separate port 8080.
14794: # Modify here if lightweight http functionality desired again.
14795: # Currently eliminated due to increasing firewall issues.
14796: #
14797:     my ($url)=@_;
14798:     return $url;
14799: }
14800: 
14801: sub connection_aborted {
14802:     my ($r)=@_;
14803:     $r->print(" ");$r->rflush();
14804:     my $c = $r->connection;
14805:     return $c->aborted();
14806: }
14807: 
14808: #    Escapes strings that may have embedded 's that will be put into
14809: #    strings as 'strings'.
14810: sub escape_single {
14811:     my ($input) = @_;
14812:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14813:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14814:     return $input;
14815: }
14816: 
14817: #  Same as escape_single, but escape's "'s  This 
14818: #  can be used for  "strings"
14819: sub escape_double {
14820:     my ($input) = @_;
14821:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14822:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14823:     return $input;
14824: }
14825:  
14826: #   Escapes the last element of a full URL.
14827: sub escape_url {
14828:     my ($url)   = @_;
14829:     my @urlslices = split(/\//, $url,-1);
14830:     my $lastitem = &escape(pop(@urlslices));
14831:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
14832: }
14833: 
14834: sub compare_arrays {
14835:     my ($arrayref1,$arrayref2) = @_;
14836:     my (@difference,%count);
14837:     @difference = ();
14838:     %count = ();
14839:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14840:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14841:         foreach my $element (keys(%count)) {
14842:             if ($count{$element} == 1) {
14843:                 push(@difference,$element);
14844:             }
14845:         }
14846:     }
14847:     return @difference;
14848: }
14849: 
14850: # -------------------------------------------------------- Initialize user login
14851: sub init_user_environment {
14852:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14853:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14854: 
14855:     my $public=($username eq 'public' && $domain eq 'public');
14856: 
14857: # See if old ID present, if so, remove
14858: 
14859:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14860:     my $now=time;
14861: 
14862:     if ($public) {
14863: 	my $max_public=100;
14864: 	my $oldest;
14865: 	my $oldest_time=0;
14866: 	for(my $next=1;$next<=$max_public;$next++) {
14867: 	    if (-e $lonids."/publicuser_$next.id") {
14868: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14869: 		if ($mtime<$oldest_time || !$oldest_time) {
14870: 		    $oldest_time=$mtime;
14871: 		    $oldest=$next;
14872: 		}
14873: 	    } else {
14874: 		$cookie="publicuser_$next";
14875: 		last;
14876: 	    }
14877: 	}
14878: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14879:     } else {
14880: 	# if this isn't a robot, kill any existing non-robot sessions
14881: 	if (!$args->{'robot'}) {
14882: 	    opendir(DIR,$lonids);
14883: 	    while ($filename=readdir(DIR)) {
14884: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14885: 		    unlink($lonids.'/'.$filename);
14886: 		}
14887: 	    }
14888: 	    closedir(DIR);
14889: # If there is a undeleted lockfile for the user's paste buffer remove it.
14890:             my $namespace = 'nohist_courseeditor';
14891:             my $lockingkey = 'paste'."\0".'locked_num';
14892:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
14893:                                                 $domain,$username);
14894:             if (exists($lockhash{$lockingkey})) {
14895:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
14896:                 unless ($delresult eq 'ok') {
14897:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
14898:                 }
14899:             }
14900: 	}
14901: # Give them a new cookie
14902: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14903: 		                   : $now.$$.int(rand(10000)));
14904: 	$cookie="$username\_$id\_$domain\_$authhost";
14905:     
14906: # Initialize roles
14907: 
14908: 	($userroles,$firstaccenv,$timerintenv) = 
14909:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14910:     }
14911: # ------------------------------------ Check browser type and MathML capability
14912: 
14913:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
14914:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
14915: 
14916: # ------------------------------------------------------------- Get environment
14917: 
14918:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14919:     my ($tmp) = keys(%userenv);
14920:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14921:     } else {
14922: 	undef(%userenv);
14923:     }
14924:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14925: 	$form->{'interface'}=$userenv{'interface'};
14926:     }
14927:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14928: 
14929: # --------------- Do not trust query string to be put directly into environment
14930:     foreach my $option ('interface','localpath','localres') {
14931:         $form->{$option}=~s/[\n\r\=]//gs;
14932:     }
14933: # --------------------------------------------------------- Write first profile
14934: 
14935:     {
14936: 	my %initial_env = 
14937: 	    ("user.name"          => $username,
14938: 	     "user.domain"        => $domain,
14939: 	     "user.home"          => $authhost,
14940: 	     "browser.type"       => $clientbrowser,
14941: 	     "browser.version"    => $clientversion,
14942: 	     "browser.mathml"     => $clientmathml,
14943: 	     "browser.unicode"    => $clientunicode,
14944: 	     "browser.os"         => $clientos,
14945:              "browser.mobile"     => $clientmobile,
14946:              "browser.info"       => $clientinfo,
14947:              "browser.osversion"  => $clientosversion,
14948: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14949: 	     "request.course.fn"  => '',
14950: 	     "request.course.uri" => '',
14951: 	     "request.course.sec" => '',
14952: 	     "request.role"       => 'cm',
14953: 	     "request.role.adv"   => $env{'user.adv'},
14954: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14955: 
14956:         if ($form->{'localpath'}) {
14957: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14958: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14959:         }
14960: 	
14961: 	if ($form->{'interface'}) {
14962: 	    $form->{'interface'}=~s/\W//gs;
14963: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14964: 	    $env{'browser.interface'}=$form->{'interface'};
14965: 	}
14966: 
14967:         if ($form->{'iptoken'}) {
14968:             my $lonhost = $r->dir_config('lonHostID');
14969:             $initial_env{"user.noloadbalance"} = $lonhost;
14970:             $env{'user.noloadbalance'} = $lonhost;
14971:         }
14972: 
14973:         my %is_adv = ( is_adv => $env{'user.adv'} );
14974:         my %domdef;
14975:         unless ($domain eq 'public') {
14976:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14977:         }
14978: 
14979:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14980:             $userenv{'availabletools.'.$tool} = 
14981:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14982:                                                   undef,\%userenv,\%domdef,\%is_adv);
14983:         }
14984: 
14985:         foreach my $crstype ('official','unofficial','community','textbook') {
14986:             $userenv{'canrequest.'.$crstype} =
14987:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14988:                                                   'reload','requestcourses',
14989:                                                   \%userenv,\%domdef,\%is_adv);
14990:         }
14991: 
14992:         $userenv{'canrequest.author'} =
14993:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14994:                                         'reload','requestauthor',
14995:                                         \%userenv,\%domdef,\%is_adv);
14996:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14997:                                              $domain,$username);
14998:         my $reqstatus = $reqauthor{'author_status'};
14999:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15000:             if (ref($reqauthor{'author'}) eq 'HASH') {
15001:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
15002:                                                   $reqauthor{'author'}{'timestamp'};
15003:             }
15004:         }
15005: 
15006: 	$env{'user.environment'} = "$lonids/$cookie.id";
15007: 
15008: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15009: 		 &GDBM_WRCREAT(),0640)) {
15010: 	    &_add_to_env(\%disk_env,\%initial_env);
15011: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15012: 	    &_add_to_env(\%disk_env,$userroles);
15013:             if (ref($firstaccenv) eq 'HASH') {
15014:                 &_add_to_env(\%disk_env,$firstaccenv);
15015:             }
15016:             if (ref($timerintenv) eq 'HASH') {
15017:                 &_add_to_env(\%disk_env,$timerintenv);
15018:             }
15019: 	    if (ref($args->{'extra_env'})) {
15020: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15021: 	    }
15022: 	    untie(%disk_env);
15023: 	} else {
15024: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15025: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15026: 	    return 'error: '.$!;
15027: 	}
15028:     }
15029:     $env{'request.role'}='cm';
15030:     $env{'request.role.adv'}=$env{'user.adv'};
15031:     $env{'browser.type'}=$clientbrowser;
15032: 
15033:     return $cookie;
15034: 
15035: }
15036: 
15037: sub _add_to_env {
15038:     my ($idf,$env_data,$prefix) = @_;
15039:     if (ref($env_data) eq 'HASH') {
15040:         while (my ($key,$value) = each(%$env_data)) {
15041: 	    $idf->{$prefix.$key} = $value;
15042: 	    $env{$prefix.$key}   = $value;
15043:         }
15044:     }
15045: }
15046: 
15047: # --- Get the symbolic name of a problem and the url
15048: sub get_symb {
15049:     my ($request,$silent) = @_;
15050:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15051:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15052:     if ($symb eq '') {
15053:         if (!$silent) {
15054:             if (ref($request)) { 
15055:                 $request->print("Unable to handle ambiguous references:$url:.");
15056:             }
15057:             return ();
15058:         }
15059:     }
15060:     &Apache::lonenc::check_decrypt(\$symb);
15061:     return ($symb);
15062: }
15063: 
15064: # --------------------------------------------------------------Get annotation
15065: 
15066: sub get_annotation {
15067:     my ($symb,$enc) = @_;
15068: 
15069:     my $key = $symb;
15070:     if (!$enc) {
15071:         $key =
15072:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15073:     }
15074:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15075:     return $annotation{$key};
15076: }
15077: 
15078: sub clean_symb {
15079:     my ($symb,$delete_enc) = @_;
15080: 
15081:     &Apache::lonenc::check_decrypt(\$symb);
15082:     my $enc = $env{'request.enc'};
15083:     if ($delete_enc) {
15084:         delete($env{'request.enc'});
15085:     }
15086: 
15087:     return ($symb,$enc);
15088: }
15089: 
15090: ############################################################
15091: ############################################################
15092: 
15093: =pod
15094: 
15095: =head1 Routines for building display used to search for courses
15096: 
15097: 
15098: =over 4
15099: 
15100: =item * &build_filters()
15101: 
15102: Create markup for a table used to set filters to use when selecting
15103: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15104: and quotacheck.pl
15105: 
15106: 
15107: Inputs:
15108: 
15109: filterlist - anonymous array of fields to include as potential filters
15110: 
15111: crstype - course type
15112: 
15113: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15114:               to pop-open a course selector (will contain "extra element").
15115: 
15116: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15117: 
15118: filter - anonymous hash of criteria and their values
15119: 
15120: action - form action
15121: 
15122: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15123: 
15124: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15125: 
15126: cloneruname - username of owner of new course who wants to clone
15127: 
15128: clonerudom - domain of owner of new course who wants to clone
15129: 
15130: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15131: 
15132: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15133: 
15134: codedom - domain
15135: 
15136: formname - value of form element named "form".
15137: 
15138: fixeddom - domain, if fixed.
15139: 
15140: prevphase - value to assign to form element named "phase" when going back to the previous screen
15141: 
15142: cnameelement - name of form element in form on opener page which will receive title of selected course
15143: 
15144: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15145: 
15146: cdomelement - name of form element in form on opener page which will receive domain of selected course
15147: 
15148: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15149: 
15150: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15151: 
15152: clonewarning - warning message about missing information for intended course owner when DC creates a course
15153: 
15154: 
15155: Returns: $output - HTML for display of search criteria, and hidden form elements.
15156: 
15157: 
15158: Side Effects: None
15159: 
15160: =cut
15161: 
15162: # ---------------------------------------------- search for courses based on last activity etc.
15163: 
15164: sub build_filters {
15165:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15166:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15167:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15168:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15169:         $clonetext,$clonewarning) = @_;
15170:     my ($list,$jscript);
15171:     my $onchange = 'javascript:updateFilters(this)';
15172:     my ($domainselectform,$sincefilterform,$createdfilterform,
15173:         $ownerdomselectform,$persondomselectform,$instcodeform,
15174:         $typeselectform,$instcodetitle);
15175:     if ($formname eq '') {
15176:         $formname = $caller;
15177:     }
15178:     foreach my $item (@{$filterlist}) {
15179:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15180:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15181:             if ($item eq 'domainfilter') {
15182:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15183:             } elsif ($item eq 'coursefilter') {
15184:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15185:             } elsif ($item eq 'ownerfilter') {
15186:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15187:             } elsif ($item eq 'ownerdomfilter') {
15188:                 $filter->{'ownerdomfilter'} =
15189:                     &LONCAPA::clean_domain($filter->{$item});
15190:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15191:                                                        'ownerdomfilter',1);
15192:             } elsif ($item eq 'personfilter') {
15193:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15194:             } elsif ($item eq 'persondomfilter') {
15195:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15196:                                                         'persondomfilter',1);
15197:             } else {
15198:                 $filter->{$item} =~ s/\W//g;
15199:             }
15200:             if (!$filter->{$item}) {
15201:                 $filter->{$item} = '';
15202:             }
15203:         }
15204:         if ($item eq 'domainfilter') {
15205:             my $allow_blank = 1;
15206:             if ($formname eq 'portform') {
15207:                 $allow_blank=0;
15208:             } elsif ($formname eq 'studentform') {
15209:                 $allow_blank=0;
15210:             }
15211:             if ($fixeddom) {
15212:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15213:                                     ' value="'.$codedom.'" />'.
15214:                                     &Apache::lonnet::domain($codedom,'description');
15215:             } else {
15216:                 $domainselectform = &select_dom_form($filter->{$item},
15217:                                                      'domainfilter',
15218:                                                       $allow_blank,'',$onchange);
15219:             }
15220:         } else {
15221:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15222:         }
15223:     }
15224: 
15225:     # last course activity filter and selection
15226:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15227: 
15228:     # course created filter and selection
15229:     if (exists($filter->{'createdfilter'})) {
15230:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15231:     }
15232: 
15233:     my %lt = &Apache::lonlocal::texthash(
15234:                 'cac' => "$crstype Activity",
15235:                 'ccr' => "$crstype Created",
15236:                 'cde' => "$crstype Title",
15237:                 'cdo' => "$crstype Domain",
15238:                 'ins' => 'Institutional Code',
15239:                 'inc' => 'Institutional Categorization',
15240:                 'cow' => "$crstype Owner/Co-owner",
15241:                 'cop' => "$crstype Personnel Includes",
15242:                 'cog' => 'Type',
15243:              );
15244: 
15245:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15246:         my $typeval = 'Course';
15247:         if ($crstype eq 'Community') {
15248:             $typeval = 'Community';
15249:         }
15250:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15251:     } else {
15252:         $typeselectform =  '<select name="type" size="1"';
15253:         if ($onchange) {
15254:             $typeselectform .= ' onchange="'.$onchange.'"';
15255:         }
15256:         $typeselectform .= '>'."\n";
15257:         foreach my $posstype ('Course','Community') {
15258:             $typeselectform.='<option value="'.$posstype.'"'.
15259:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15260:         }
15261:         $typeselectform.="</select>";
15262:     }
15263: 
15264:     my ($cloneableonlyform,$cloneabletitle);
15265:     if (exists($filter->{'cloneableonly'})) {
15266:         my $cloneableon = '';
15267:         my $cloneableoff = ' checked="checked"';
15268:         if ($filter->{'cloneableonly'}) {
15269:             $cloneableon = $cloneableoff;
15270:             $cloneableoff = '';
15271:         }
15272:         $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>';
15273:         if ($formname eq 'ccrs') {
15274:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15275:         } else {
15276:             $cloneabletitle = &mt('Cloneable by you');
15277:         }
15278:     }
15279:     my $officialjs;
15280:     if ($crstype eq 'Course') {
15281:         if (exists($filter->{'instcodefilter'})) {
15282: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15283: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15284:             if ($codedom) {
15285:                 $officialjs = 1;
15286:                 ($instcodeform,$jscript,$$numtitlesref) =
15287:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15288:                                                                   $officialjs,$codetitlesref);
15289:                 if ($jscript) {
15290:                     $jscript = '<script type="text/javascript">'."\n".
15291:                                '// <![CDATA['."\n".
15292:                                $jscript."\n".
15293:                                '// ]]>'."\n".
15294:                                '</script>'."\n";
15295:                 }
15296:             }
15297:             if ($instcodeform eq '') {
15298:                 $instcodeform =
15299:                     '<input type="text" name="instcodefilter" size="10" value="'.
15300:                     $list->{'instcodefilter'}.'" />';
15301:                 $instcodetitle = $lt{'ins'};
15302:             } else {
15303:                 $instcodetitle = $lt{'inc'};
15304:             }
15305:             if ($fixeddom) {
15306:                 $instcodetitle .= '<br />('.$codedom.')';
15307:             }
15308:         }
15309:     }
15310:     my $output = qq|
15311: <form method="post" name="filterpicker" action="$action">
15312: <input type="hidden" name="form" value="$formname" />
15313: |;
15314:     if ($formname eq 'modifycourse') {
15315:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15316:                    '<input type="hidden" name="prevphase" value="'.
15317:                    $prevphase.'" />'."\n";
15318:     } elsif ($formname eq 'quotacheck') {
15319:         $output .= qq|
15320: <input type="hidden" name="sortby" value="" />
15321: <input type="hidden" name="sortorder" value="" />
15322: |;
15323:     } else {
15324:         my $name_input;
15325:         if ($cnameelement ne '') {
15326:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15327:                           $cnameelement.'" />';
15328:         }
15329:         $output .= qq|
15330: <input type="hidden" name="cnumelement" value="$cnumelement" />
15331: <input type="hidden" name="cdomelement" value="$cdomelement" />
15332: $name_input
15333: $roleelement
15334: $multelement
15335: $typeelement
15336: |;
15337:         if ($formname eq 'portform') {
15338:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15339:         }
15340:     }
15341:     if ($fixeddom) {
15342:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15343:     }
15344:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15345:     if ($sincefilterform) {
15346:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15347:                   .$sincefilterform
15348:                   .&Apache::lonhtmlcommon::row_closure();
15349:     }
15350:     if ($createdfilterform) {
15351:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15352:                   .$createdfilterform
15353:                   .&Apache::lonhtmlcommon::row_closure();
15354:     }
15355:     if ($domainselectform) {
15356:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15357:                   .$domainselectform
15358:                   .&Apache::lonhtmlcommon::row_closure();
15359:     }
15360:     if ($typeselectform) {
15361:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15362:             $output .= $typeselectform;
15363:         } else {
15364:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15365:                       .$typeselectform
15366:                       .&Apache::lonhtmlcommon::row_closure();
15367:         }
15368:     }
15369:     if ($instcodeform) {
15370:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15371:                   .$instcodeform
15372:                   .&Apache::lonhtmlcommon::row_closure();
15373:     }
15374:     if (exists($filter->{'ownerfilter'})) {
15375:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15376:                    '<table><tr><td>'.&mt('Username').'<br />'.
15377:                    '<input type="text" name="ownerfilter" size="20" value="'.
15378:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15379:                    $ownerdomselectform.'</td></tr></table>'.
15380:                    &Apache::lonhtmlcommon::row_closure();
15381:     }
15382:     if (exists($filter->{'personfilter'})) {
15383:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15384:                    '<table><tr><td>'.&mt('Username').'<br />'.
15385:                    '<input type="text" name="personfilter" size="20" value="'.
15386:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15387:                    $persondomselectform.'</td></tr></table>'.
15388:                    &Apache::lonhtmlcommon::row_closure();
15389:     }
15390:     if (exists($filter->{'coursefilter'})) {
15391:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15392:                   .'<input type="text" name="coursefilter" size="25" value="'
15393:                   .$list->{'coursefilter'}.'" />'
15394:                   .&Apache::lonhtmlcommon::row_closure();
15395:     }
15396:     if ($cloneableonlyform) {
15397:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15398:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15399:     }
15400:     if (exists($filter->{'descriptfilter'})) {
15401:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15402:                   .'<input type="text" name="descriptfilter" size="40" value="'
15403:                   .$list->{'descriptfilter'}.'" />'
15404:                   .&Apache::lonhtmlcommon::row_closure(1);
15405:     }
15406:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15407:                '<input type="hidden" name="updater" value="" />'."\n".
15408:                '<input type="submit" name="gosearch" value="'.
15409:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15410:     return $jscript.$clonewarning.$output;
15411: }
15412: 
15413: =pod
15414: 
15415: =item * &timebased_select_form()
15416: 
15417: Create markup for a dropdown list used to select a time-based
15418: filter e.g., Course Activity, Course Created, when searching for courses
15419: or communities
15420: 
15421: Inputs:
15422: 
15423: item - name of form element (sincefilter or createdfilter)
15424: 
15425: filter - anonymous hash of criteria and their values
15426: 
15427: Returns: HTML for a select box contained a blank, then six time selections,
15428:          with value set in incoming form variables currently selected.
15429: 
15430: Side Effects: None
15431: 
15432: =cut
15433: 
15434: sub timebased_select_form {
15435:     my ($item,$filter) = @_;
15436:     if (ref($filter) eq 'HASH') {
15437:         $filter->{$item} =~ s/[^\d-]//g;
15438:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15439:         return &select_form(
15440:                             $filter->{$item},
15441:                             $item,
15442:                             {      '-1' => '',
15443:                                 '86400' => &mt('today'),
15444:                                '604800' => &mt('last week'),
15445:                               '2592000' => &mt('last month'),
15446:                               '7776000' => &mt('last three months'),
15447:                              '15552000' => &mt('last six months'),
15448:                              '31104000' => &mt('last year'),
15449:                     'select_form_order' =>
15450:                            ['-1','86400','604800','2592000','7776000',
15451:                             '15552000','31104000']});
15452:     }
15453: }
15454: 
15455: =pod
15456: 
15457: =item * &js_changer()
15458: 
15459: Create script tag containing Javascript used to submit course search form
15460: when course type or domain is changed, and also to hide 'Searching ...' on
15461: page load completion for page showing search result.
15462: 
15463: Inputs: None
15464: 
15465: Returns: markup containing updateFilters() and hideSearching() javascript functions.
15466: 
15467: Side Effects: None
15468: 
15469: =cut
15470: 
15471: sub js_changer {
15472:     return <<ENDJS;
15473: <script type="text/javascript">
15474: // <![CDATA[
15475: function updateFilters(caller) {
15476:     if (typeof(caller) != "undefined") {
15477:         document.filterpicker.updater.value = caller.name;
15478:     }
15479:     document.filterpicker.submit();
15480: }
15481: 
15482: function hideSearching() {
15483:     if (document.getElementById('searching')) {
15484:         document.getElementById('searching').style.display = 'none';
15485:     }
15486:     return;
15487: }
15488: 
15489: // ]]>
15490: </script>
15491: 
15492: ENDJS
15493: }
15494: 
15495: =pod
15496: 
15497: =item * &search_courses()
15498: 
15499: Process selected filters form course search form and pass to lonnet::courseiddump
15500: to retrieve a hash for which keys are courseIDs which match the selected filters.
15501: 
15502: Inputs:
15503: 
15504: dom - domain being searched
15505: 
15506: type - course type ('Course' or 'Community' or '.' if any).
15507: 
15508: filter - anonymous hash of criteria and their values
15509: 
15510: numtitles - for institutional codes - number of categories
15511: 
15512: cloneruname - optional username of new course owner
15513: 
15514: clonerudom - optional domain of new course owner
15515: 
15516: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
15517:             (used when DC is using course creation form)
15518: 
15519: codetitles - reference to array of titles of components in institutional codes (official courses).
15520: 
15521: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
15522:            (and so can clone automatically)
15523: 
15524: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
15525: 
15526: reqinstcode - institutional code of new course, where search_courses is used to identify potential
15527:               courses to clone
15528: 
15529: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
15530: 
15531: 
15532: Side Effects: None
15533: 
15534: =cut
15535: 
15536: 
15537: sub search_courses {
15538:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
15539:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
15540:     my (%courses,%showcourses,$cloner);
15541:     if (($filter->{'ownerfilter'} ne '') ||
15542:         ($filter->{'ownerdomfilter'} ne '')) {
15543:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
15544:                                        $filter->{'ownerdomfilter'};
15545:     }
15546:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
15547:         if (!$filter->{$item}) {
15548:             $filter->{$item}='.';
15549:         }
15550:     }
15551:     my $now = time;
15552:     my $timefilter =
15553:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
15554:     my ($createdbefore,$createdafter);
15555:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
15556:         $createdbefore = $now;
15557:         $createdafter = $now-$filter->{'createdfilter'};
15558:     }
15559:     my ($instcodefilter,$regexpok);
15560:     if ($numtitles) {
15561:         if ($env{'form.official'} eq 'on') {
15562:             $instcodefilter =
15563:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15564:             $regexpok = 1;
15565:         } elsif ($env{'form.official'} eq 'off') {
15566:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15567:             unless ($instcodefilter eq '') {
15568:                 $regexpok = -1;
15569:             }
15570:         }
15571:     } else {
15572:         $instcodefilter = $filter->{'instcodefilter'};
15573:     }
15574:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
15575:     if ($type eq '') { $type = '.'; }
15576: 
15577:     if (($clonerudom ne '') && ($cloneruname ne '')) {
15578:         $cloner = $cloneruname.':'.$clonerudom;
15579:     }
15580:     %courses = &Apache::lonnet::courseiddump($dom,
15581:                                              $filter->{'descriptfilter'},
15582:                                              $timefilter,
15583:                                              $instcodefilter,
15584:                                              $filter->{'combownerfilter'},
15585:                                              $filter->{'coursefilter'},
15586:                                              undef,undef,$type,$regexpok,undef,undef,
15587:                                              undef,undef,$cloner,$cc_clone,
15588:                                              $filter->{'cloneableonly'},
15589:                                              $createdbefore,$createdafter,undef,
15590:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
15591:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
15592:         my $ccrole;
15593:         if ($type eq 'Community') {
15594:             $ccrole = 'co';
15595:         } else {
15596:             $ccrole = 'cc';
15597:         }
15598:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
15599:                                                      $filter->{'persondomfilter'},
15600:                                                      'userroles',undef,
15601:                                                      [$ccrole,'in','ad','ep','ta','cr'],
15602:                                                      $dom);
15603:         foreach my $role (keys(%rolehash)) {
15604:             my ($cnum,$cdom,$courserole) = split(':',$role);
15605:             my $cid = $cdom.'_'.$cnum;
15606:             if (exists($courses{$cid})) {
15607:                 if (ref($courses{$cid}) eq 'HASH') {
15608:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
15609:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
15610:                             push (@{$courses{$cid}{roles}},$courserole);
15611:                         }
15612:                     } else {
15613:                         $courses{$cid}{roles} = [$courserole];
15614:                     }
15615:                     $showcourses{$cid} = $courses{$cid};
15616:                 }
15617:             }
15618:         }
15619:         %courses = %showcourses;
15620:     }
15621:     return %courses;
15622: }
15623: 
15624: =pod
15625: 
15626: =back
15627: 
15628: =head1 Routines for version requirements for current course.
15629: 
15630: =over 4
15631: 
15632: =item * &check_release_required()
15633: 
15634: Compares required LON-CAPA version with version on server, and
15635: if required version is newer looks for a server with the required version.
15636: 
15637: Looks first at servers in user's owen domain; if none suitable, looks at
15638: servers in course's domain are permitted to host sessions for user's domain.
15639: 
15640: Inputs:
15641: 
15642: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15643: 
15644: $courseid - Course ID of current course
15645: 
15646: $rolecode - User's current role in course (for switchserver query string).
15647: 
15648: $required - LON-CAPA version needed by course (format: Major.Minor).
15649: 
15650: 
15651: Returns:
15652: 
15653: $switchserver - query string tp append to /adm/switchserver call (if
15654:                 current server's LON-CAPA version is too old.
15655: 
15656: $warning - Message is displayed if no suitable server could be found.
15657: 
15658: =cut
15659: 
15660: sub check_release_required {
15661:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
15662:     my ($switchserver,$warning);
15663:     if ($required ne '') {
15664:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
15665:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15666:         if ($reqdmajor ne '' && $reqdminor ne '') {
15667:             my $otherserver;
15668:             if (($major eq '' && $minor eq '') ||
15669:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
15670:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
15671:                 my $switchlcrev =
15672:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
15673:                                                            $userdomserver);
15674:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15675:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
15676:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
15677:                     my $cdom = $env{'course.'.$courseid.'.domain'};
15678:                     if ($cdom ne $env{'user.domain'}) {
15679:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
15680:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
15681:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
15682:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
15683:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
15684:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
15685:                         my $canhost =
15686:                             &Apache::lonnet::can_host_session($env{'user.domain'},
15687:                                                               $coursedomserver,
15688:                                                               $remoterev,
15689:                                                               $udomdefaults{'remotesessions'},
15690:                                                               $defdomdefaults{'hostedsessions'});
15691: 
15692:                         if ($canhost) {
15693:                             $otherserver = $coursedomserver;
15694:                         } else {
15695:                             $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.");
15696:                         }
15697:                     } else {
15698:                         $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).");
15699:                     }
15700:                 } else {
15701:                     $otherserver = $userdomserver;
15702:                 }
15703:             }
15704:             if ($otherserver ne '') {
15705:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
15706:             }
15707:         }
15708:     }
15709:     return ($switchserver,$warning);
15710: }
15711: 
15712: =pod
15713: 
15714: =item * &check_release_result()
15715: 
15716: Inputs:
15717: 
15718: $switchwarning - Warning message if no suitable server found to host session.
15719: 
15720: $switchserver - query string to append to /adm/switchserver containing lonHostID
15721:                 and current role.
15722: 
15723: Returns: HTML to display with information about requirement to switch server.
15724:          Either displaying warning with link to Roles/Courses screen or
15725:          display link to switchserver.
15726: 
15727: =cut
15728: 
15729: sub check_release_result {
15730:     my ($switchwarning,$switchserver) = @_;
15731:     my $output = &start_page('Selected course unavailable on this server').
15732:                  '<p class="LC_warning">';
15733:     if ($switchwarning) {
15734:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
15735:         if (&show_course()) {
15736:             $output .= &mt('Display courses');
15737:         } else {
15738:             $output .= &mt('Display roles');
15739:         }
15740:         $output .= '</a>';
15741:     } elsif ($switchserver) {
15742:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
15743:                    '<br />'.
15744:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
15745:                    &mt('Switch Server').
15746:                    '</a>';
15747:     }
15748:     $output .= '</p>'.&end_page();
15749:     return $output;
15750: }
15751: 
15752: =pod
15753: 
15754: =item * &needs_coursereinit()
15755: 
15756: Determine if course contents stored for user's session needs to be
15757: refreshed, because content has changed since "Big Hash" last tied.
15758: 
15759: Check for change is made if time last checked is more than 10 minutes ago
15760: (by default).
15761: 
15762: Inputs:
15763: 
15764: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15765: 
15766: $interval (optional) - Time which may elapse (in s) between last check for content
15767:                        change in current course. (default: 600 s).
15768: 
15769: Returns: an array; first element is:
15770: 
15771: =over 4
15772: 
15773: 'switch' - if content updates mean user's session
15774:            needs to be switched to a server running a newer LON-CAPA version
15775: 
15776: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
15777:            on current server hosting user's session
15778: 
15779: ''       - if no action required.
15780: 
15781: =back
15782: 
15783: If first item element is 'switch':
15784: 
15785: second item is $switchwarning - Warning message if no suitable server found to host session.
15786: 
15787: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
15788:                               and current role.
15789: 
15790: otherwise: no other elements returned.
15791: 
15792: =back
15793: 
15794: =cut
15795: 
15796: sub needs_coursereinit {
15797:     my ($loncaparev,$interval) = @_;
15798:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
15799:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
15800:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
15801:     my $now = time;
15802:     if ($interval eq '') {
15803:         $interval = 600;
15804:     }
15805:     if (($now-$env{'request.course.timechecked'})>$interval) {
15806:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
15807:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
15808:         if ($lastchange > $env{'request.course.tied'}) {
15809:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15810:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
15811:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
15812:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
15813:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
15814:                                              $curr_reqd_hash{'internal.releaserequired'}});
15815:                     my ($switchserver,$switchwarning) =
15816:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
15817:                                                 $curr_reqd_hash{'internal.releaserequired'});
15818:                     if ($switchwarning ne '' || $switchserver ne '') {
15819:                         return ('switch',$switchwarning,$switchserver);
15820:                     }
15821:                 }
15822:             }
15823:             return ('update');
15824:         }
15825:     }
15826:     return ();
15827: }
15828: 
15829: sub update_content_constraints {
15830:     my ($cdom,$cnum,$chome,$cid) = @_;
15831:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15832:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
15833:     my %checkresponsetypes;
15834:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
15835:         my ($item,$name,$value) = split(/:/,$key);
15836:         if ($item eq 'resourcetag') {
15837:             if ($name eq 'responsetype') {
15838:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
15839:             }
15840:         }
15841:     }
15842:     my $navmap = Apache::lonnavmaps::navmap->new();
15843:     if (defined($navmap)) {
15844:         my %allresponses;
15845:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
15846:             my %responses = $res->responseTypes();
15847:             foreach my $key (keys(%responses)) {
15848:                 next unless(exists($checkresponsetypes{$key}));
15849:                 $allresponses{$key} += $responses{$key};
15850:             }
15851:         }
15852:         foreach my $key (keys(%allresponses)) {
15853:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
15854:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
15855:                 ($reqdmajor,$reqdminor) = ($major,$minor);
15856:             }
15857:         }
15858:         undef($navmap);
15859:     }
15860:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
15861:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
15862:     }
15863:     return;
15864: }
15865: 
15866: sub allmaps_incourse {
15867:     my ($cdom,$cnum,$chome,$cid) = @_;
15868:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
15869:         $cid = $env{'request.course.id'};
15870:         $cdom = $env{'course.'.$cid.'.domain'};
15871:         $cnum = $env{'course.'.$cid.'.num'};
15872:         $chome = $env{'course.'.$cid.'.home'};
15873:     }
15874:     my %allmaps = ();
15875:     my $lastchange =
15876:         &Apache::lonnet::get_coursechange($cdom,$cnum);
15877:     if ($lastchange > $env{'request.course.tied'}) {
15878:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
15879:         unless ($ferr) {
15880:             &update_content_constraints($cdom,$cnum,$chome,$cid);
15881:         }
15882:     }
15883:     my $navmap = Apache::lonnavmaps::navmap->new();
15884:     if (defined($navmap)) {
15885:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
15886:             $allmaps{$res->src()} = 1;
15887:         }
15888:     }
15889:     return \%allmaps;
15890: }
15891: 
15892: sub parse_supplemental_title {
15893:     my ($title) = @_;
15894: 
15895:     my ($foldertitle,$renametitle);
15896:     if ($title =~ /&amp;&amp;&amp;/) {
15897:         $title = &HTML::Entites::decode($title);
15898:     }
15899:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
15900:         $renametitle=$4;
15901:         my ($time,$uname,$udom) = ($1,$2,$3);
15902:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
15903:         my $name =  &plainname($uname,$udom);
15904:         $name = &HTML::Entities::encode($name,'"<>&\'');
15905:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
15906:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
15907:             $name.': <br />'.$foldertitle;
15908:     }
15909:     if (wantarray) {
15910:         return ($title,$foldertitle,$renametitle);
15911:     }
15912:     return $title;
15913: }
15914: 
15915: sub recurse_supplemental {
15916:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
15917:     if ($suppmap) {
15918:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
15919:         if ($fatal) {
15920:             $errors ++;
15921:         } else {
15922:             if ($#LONCAPA::map::resources > 0) {
15923:                 foreach my $res (@LONCAPA::map::resources) {
15924:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
15925:                     if (($src ne '') && ($status eq 'res')) {
15926:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
15927:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
15928:                         } else {
15929:                             $numfiles ++;
15930:                         }
15931:                     }
15932:                 }
15933:             }
15934:         }
15935:     }
15936:     return ($numfiles,$errors);
15937: }
15938: 
15939: sub symb_to_docspath {
15940:     my ($symb) = @_;
15941:     return unless ($symb);
15942:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
15943:     if ($resurl=~/\.(sequence|page)$/) {
15944:         $mapurl=$resurl;
15945:     } elsif ($resurl eq 'adm/navmaps') {
15946:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
15947:     }
15948:     my $mapresobj;
15949:     my $navmap = Apache::lonnavmaps::navmap->new();
15950:     if (ref($navmap)) {
15951:         $mapresobj = $navmap->getResourceByUrl($mapurl);
15952:     }
15953:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
15954:     my $type=$2;
15955:     my $path;
15956:     if (ref($mapresobj)) {
15957:         my $pcslist = $mapresobj->map_hierarchy();
15958:         if ($pcslist ne '') {
15959:             foreach my $pc (split(/,/,$pcslist)) {
15960:                 next if ($pc <= 1);
15961:                 my $res = $navmap->getByMapPc($pc);
15962:                 if (ref($res)) {
15963:                     my $thisurl = $res->src();
15964:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
15965:                     my $thistitle = $res->title();
15966:                     $path .= '&'.
15967:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
15968:                              &escape($thistitle).
15969:                              ':'.$res->randompick().
15970:                              ':'.$res->randomout().
15971:                              ':'.$res->encrypted().
15972:                              ':'.$res->randomorder().
15973:                              ':'.$res->is_page();
15974:                 }
15975:             }
15976:         }
15977:         $path =~ s/^\&//;
15978:         my $maptitle = $mapresobj->title();
15979:         if ($mapurl eq 'default') {
15980:             $maptitle = 'Main Content';
15981:         }
15982:         $path .= (($path ne '')? '&' : '').
15983:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15984:                  &escape($maptitle).
15985:                  ':'.$mapresobj->randompick().
15986:                  ':'.$mapresobj->randomout().
15987:                  ':'.$mapresobj->encrypted().
15988:                  ':'.$mapresobj->randomorder().
15989:                  ':'.$mapresobj->is_page();
15990:     } else {
15991:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
15992:         my $ispage = (($type eq 'page')? 1 : '');
15993:         if ($mapurl eq 'default') {
15994:             $maptitle = 'Main Content';
15995:         }
15996:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15997:                 &escape($maptitle).':::::'.$ispage;
15998:     }
15999:     unless ($mapurl eq 'default') {
16000:         $path = 'default&'.
16001:                 &escape('Main Content').
16002:                 ':::::&'.$path;
16003:     }
16004:     return $path;
16005: }
16006: 
16007: sub captcha_display {
16008:     my ($context,$lonhost) = @_;
16009:     my ($output,$error);
16010:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
16011:     if ($captcha eq 'original') {
16012:         $output = &create_captcha();
16013:         unless ($output) {
16014:             $error = 'captcha';
16015:         }
16016:     } elsif ($captcha eq 'recaptcha') {
16017:         $output = &create_recaptcha($pubkey);
16018:         unless ($output) {
16019:             $error = 'recaptcha';
16020:         }
16021:     }
16022:     return ($output,$error,$captcha);
16023: }
16024: 
16025: sub captcha_response {
16026:     my ($context,$lonhost) = @_;
16027:     my ($captcha_chk,$captcha_error);
16028:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
16029:     if ($captcha eq 'original') {
16030:         ($captcha_chk,$captcha_error) = &check_captcha();
16031:     } elsif ($captcha eq 'recaptcha') {
16032:         $captcha_chk = &check_recaptcha($privkey);
16033:     } else {
16034:         $captcha_chk = 1;
16035:     }
16036:     return ($captcha_chk,$captcha_error);
16037: }
16038: 
16039: sub get_captcha_config {
16040:     my ($context,$lonhost) = @_;
16041:     my ($captcha,$pubkey,$privkey,$hashtocheck);
16042:     my $hostname = &Apache::lonnet::hostname($lonhost);
16043:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16044:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16045:     if ($context eq 'usercreation') {
16046:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16047:         if (ref($domconfig{$context}) eq 'HASH') {
16048:             $hashtocheck = $domconfig{$context}{'cancreate'};
16049:             if (ref($hashtocheck) eq 'HASH') {
16050:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16051:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16052:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16053:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16054:                     }
16055:                     if ($privkey && $pubkey) {
16056:                         $captcha = 'recaptcha';
16057:                     } else {
16058:                         $captcha = 'original';
16059:                     }
16060:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16061:                     $captcha = 'original';
16062:                 }
16063:             }
16064:         } else {
16065:             $captcha = 'captcha';
16066:         }
16067:     } elsif ($context eq 'login') {
16068:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16069:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16070:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16071:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16072:             if ($privkey && $pubkey) {
16073:                 $captcha = 'recaptcha';
16074:             } else {
16075:                 $captcha = 'original';
16076:             }
16077:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16078:             $captcha = 'original';
16079:         }
16080:     }
16081:     return ($captcha,$pubkey,$privkey);
16082: }
16083: 
16084: sub create_captcha {
16085:     my %captcha_params = &captcha_settings();
16086:     my ($output,$maxtries,$tries) = ('',10,0);
16087:     while ($tries < $maxtries) {
16088:         $tries ++;
16089:         my $captcha = Authen::Captcha->new (
16090:                                            output_folder => $captcha_params{'output_dir'},
16091:                                            data_folder   => $captcha_params{'db_dir'},
16092:                                           );
16093:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16094: 
16095:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16096:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16097:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16098:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16099:                       '<br />'.
16100:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16101:             last;
16102:         }
16103:     }
16104:     return $output;
16105: }
16106: 
16107: sub captcha_settings {
16108:     my %captcha_params = (
16109:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16110:                            www_output_dir => "/captchaspool",
16111:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16112:                            numchars       => '5',
16113:                          );
16114:     return %captcha_params;
16115: }
16116: 
16117: sub check_captcha {
16118:     my ($captcha_chk,$captcha_error);
16119:     my $code = $env{'form.code'};
16120:     my $md5sum = $env{'form.crypt'};
16121:     my %captcha_params = &captcha_settings();
16122:     my $captcha = Authen::Captcha->new(
16123:                       output_folder => $captcha_params{'output_dir'},
16124:                       data_folder   => $captcha_params{'db_dir'},
16125:                   );
16126:     $captcha_chk = $captcha->check_code($code,$md5sum);
16127:     my %captcha_hash = (
16128:                         0       => 'Code not checked (file error)',
16129:                        -1      => 'Failed: code expired',
16130:                        -2      => 'Failed: invalid code (not in database)',
16131:                        -3      => 'Failed: invalid code (code does not match crypt)',
16132:     );
16133:     if ($captcha_chk != 1) {
16134:         $captcha_error = $captcha_hash{$captcha_chk}
16135:     }
16136:     return ($captcha_chk,$captcha_error);
16137: }
16138: 
16139: sub create_recaptcha {
16140:     my ($pubkey) = @_;
16141:     my $use_ssl;
16142:     if ($ENV{'SERVER_PORT'} == 443) {
16143:         $use_ssl = 1;
16144:     }
16145:     my $captcha = Captcha::reCAPTCHA->new;
16146:     return $captcha->get_options_setter({theme => 'white'})."\n".
16147:            $captcha->get_html($pubkey,undef,$use_ssl).
16148:            &mt('If the text is hard to read, [_1] will replace them.',
16149:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16150:            '<br /><br />';
16151: }
16152: 
16153: sub check_recaptcha {
16154:     my ($privkey) = @_;
16155:     my $captcha_chk;
16156:     my $captcha = Captcha::reCAPTCHA->new;
16157:     my $captcha_result =
16158:         $captcha->check_answer(
16159:                                 $privkey,
16160:                                 $ENV{'REMOTE_ADDR'},
16161:                                 $env{'form.recaptcha_challenge_field'},
16162:                                 $env{'form.recaptcha_response_field'},
16163:                               );
16164:     if ($captcha_result->{is_valid}) {
16165:         $captcha_chk = 1;
16166:     }
16167:     return $captcha_chk;
16168: }
16169: 
16170: sub emailusername_info {
16171:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
16172:     my %titles = &Apache::lonlocal::texthash (
16173:                      lastname      => 'Last Name',
16174:                      firstname     => 'First Name',
16175:                      institution   => 'School/college/university',
16176:                      location      => "School's city, state/province, country",
16177:                      web           => "School's web address",
16178:                      officialemail => 'E-mail address at institution (if different)',
16179:                  );
16180:     return (\@fields,\%titles);
16181: }
16182: 
16183: sub cleanup_html {
16184:     my ($incoming) = @_;
16185:     my $outgoing;
16186:     if ($incoming ne '') {
16187:         $outgoing = $incoming;
16188:         $outgoing =~ s/;/&#059;/g;
16189:         $outgoing =~ s/\#/&#035;/g;
16190:         $outgoing =~ s/\&/&#038;/g;
16191:         $outgoing =~ s/</&#060;/g;
16192:         $outgoing =~ s/>/&#062;/g;
16193:         $outgoing =~ s/\(/&#040/g;
16194:         $outgoing =~ s/\)/&#041;/g;
16195:         $outgoing =~ s/"/&#034;/g;
16196:         $outgoing =~ s/'/&#039;/g;
16197:         $outgoing =~ s/\$/&#036;/g;
16198:         $outgoing =~ s{/}{&#047;}g;
16199:         $outgoing =~ s/=/&#061;/g;
16200:         $outgoing =~ s/\\/&#092;/g
16201:     }
16202:     return $outgoing;
16203: }
16204: 
16205: # Checks for critical messages and returns a redirect url if one exists.
16206: # $interval indicates how often to check for messages.
16207: sub critical_redirect {
16208:     my ($interval) = @_;
16209:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16210:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16211:                                         $env{'user.name'});
16212:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16213:         my $redirecturl;
16214:         if ($what[0]) {
16215:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16216:                 $redirecturl='/adm/email?critical=display';
16217:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
16218:                 return (1, $url);
16219:             }
16220:         }
16221:     }
16222:     return ();
16223: }
16224: 
16225: # Use:
16226: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16227: #
16228: ##################################################
16229: #          password associated functions         #
16230: ##################################################
16231: sub des_keys {
16232:     # Make a new key for DES encryption.
16233:     # Each key has two parts which are returned separately.
16234:     # Please note:  Each key must be passed through the &hex function
16235:     # before it is output to the web browser.  The hex versions cannot
16236:     # be used to decrypt.
16237:     my @hexstr=('0','1','2','3','4','5','6','7',
16238:                 '8','9','a','b','c','d','e','f');
16239:     my $lkey='';
16240:     for (0..7) {
16241:         $lkey.=$hexstr[rand(15)];
16242:     }
16243:     my $ukey='';
16244:     for (0..7) {
16245:         $ukey.=$hexstr[rand(15)];
16246:     }
16247:     return ($lkey,$ukey);
16248: }
16249: 
16250: sub des_decrypt {
16251:     my ($key,$cyphertext) = @_;
16252:     my $keybin=pack("H16",$key);
16253:     my $cypher;
16254:     if ($Crypt::DES::VERSION>=2.03) {
16255:         $cypher=new Crypt::DES $keybin;
16256:     } else {
16257:         $cypher=new DES $keybin;
16258:     }
16259:     my $plaintext=
16260:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
16261:     $plaintext.=
16262:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
16263:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
16264:     return $plaintext;
16265: }
16266: 
16267: 1;
16268: __END__;
16269: 

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