File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1278: download - view: text, annotated - select for diffs
Tue Mar 21 23:19:29 2017 UTC (7 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Suppress offers from Chrome to translate the page, because the
  determination of language used in a LON-CAPA page is unreliable.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1278 2017/03/21 23:19:29 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale;
   76: use Encode();
   77: use Text::Aspell;
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use MIME::Lite;
   85: use MIME::Types;
   86: 
   87: # ---------------------------------------------- Designs
   88: use vars qw(%defaultdesign);
   89: 
   90: my $readit;
   91: 
   92: 
   93: ##
   94: ## Global Variables
   95: ##
   96: 
   97: 
   98: # ----------------------------------------------- SSI with retries:
   99: #
  100: 
  101: =pod
  102: 
  103: =head1 Server Side include with retries:
  104: 
  105: =over 4
  106: 
  107: =item * &ssi_with_retries(resource,retries form)
  108: 
  109: Performs an ssi with some number of retries.  Retries continue either
  110: until the result is ok or until the retry count supplied by the
  111: caller is exhausted.  
  112: 
  113: Inputs:
  114: 
  115: =over 4
  116: 
  117: resource   - Identifies the resource to insert.
  118: 
  119: retries    - Count of the number of retries allowed.
  120: 
  121: form       - Hash that identifies the rendering options.
  122: 
  123: =back
  124: 
  125: Returns:
  126: 
  127: =over 4
  128: 
  129: content    - The content of the response.  If retries were exhausted this is empty.
  130: 
  131: response   - The response from the last attempt (which may or may not have been successful.
  132: 
  133: =back
  134: 
  135: =back
  136: 
  137: =cut
  138: 
  139: sub ssi_with_retries {
  140:     my ($resource, $retries, %form) = @_;
  141: 
  142: 
  143:     my $ok = 0;			# True if we got a good response.
  144:     my $content;
  145:     my $response;
  146: 
  147:     # Try to get the ssi done. within the retries count:
  148: 
  149:     do {
  150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  151: 	$ok      = $response->is_success;
  152:         if (!$ok) {
  153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  154:         }
  155: 	$retries--;
  156:     } while (!$ok && ($retries > 0));
  157: 
  158:     if (!$ok) {
  159: 	$content = '';		# On error return an empty content.
  160:     }
  161:     return ($content, $response);
  162: 
  163: }
  164: 
  165: 
  166: 
  167: # ----------------------------------------------- Filetypes/Languages/Copyright
  168: my %language;
  169: my %supported_language;
  170: my %supported_codes;
  171: my %latex_language;		# For choosing hyphenation in <transl..>
  172: my %latex_language_bykey;	# for choosing hyphenation from metadata
  173: my %cprtag;
  174: my %scprtag;
  175: my %fe; my %fd; my %fm;
  176: my %category_extensions;
  177: 
  178: # ---------------------------------------------- Thesaurus variables
  179: #
  180: # %Keywords:
  181: #      A hash used by &keyword to determine if a word is considered a keyword.
  182: # $thesaurus_db_file 
  183: #      Scalar containing the full path to the thesaurus database.
  184: 
  185: my %Keywords;
  186: my $thesaurus_db_file;
  187: 
  188: #
  189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  190: # thesaurus.tab, and filecategories.tab.
  191: #
  192: BEGIN {
  193:     # Variable initialization
  194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  195:     #
  196:     unless ($readit) {
  197: # ------------------------------------------------------------------- languages
  198:     {
  199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  200:                                    '/language.tab';
  201:         if ( open(my $fh,"<$langtabfile") ) {
  202:             while (my $line = <$fh>) {
  203:                 next if ($line=~/^\#/);
  204:                 chomp($line);
  205:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  206:                 $language{$key}=$val.' - '.$enc;
  207:                 if ($sup) {
  208:                     $supported_language{$key}=$sup;
  209: 		    $supported_codes{$key}   = $code;
  210:                 }
  211: 		if ($latex) {
  212: 		    $latex_language_bykey{$key} = $latex;
  213: 		    $latex_language{$code} = $latex;
  214: 		}
  215:             }
  216:             close($fh);
  217:         }
  218:     }
  219: # ------------------------------------------------------------------ copyrights
  220:     {
  221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  222:                                   '/copyright.tab';
  223:         if ( open (my $fh,"<$copyrightfile") ) {
  224:             while (my $line = <$fh>) {
  225:                 next if ($line=~/^\#/);
  226:                 chomp($line);
  227:                 my ($key,$val)=(split(/\s+/,$line,2));
  228:                 $cprtag{$key}=$val;
  229:             }
  230:             close($fh);
  231:         }
  232:     }
  233: # ----------------------------------------------------------- source copyrights
  234:     {
  235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  236:                                   '/source_copyright.tab';
  237:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  238:             while (my $line = <$fh>) {
  239:                 next if ($line =~ /^\#/);
  240:                 chomp($line);
  241:                 my ($key,$val)=(split(/\s+/,$line,2));
  242:                 $scprtag{$key}=$val;
  243:             }
  244:             close($fh);
  245:         }
  246:     }
  247: 
  248: # -------------------------------------------------------------- default domain designs
  249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  250:     my $designfile = $designdir.'/default.tab';
  251:     if ( open (my $fh,"<$designfile") ) {
  252:         while (my $line = <$fh>) {
  253:             next if ($line =~ /^\#/);
  254:             chomp($line);
  255:             my ($key,$val)=(split(/\=/,$line));
  256:             if ($val) { $defaultdesign{$key}=$val; }
  257:         }
  258:         close($fh);
  259:     }
  260: 
  261: # ------------------------------------------------------------- file categories
  262:     {
  263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                                   '/filecategories.tab';
  265:         if ( open (my $fh,"<$categoryfile") ) {
  266: 	    while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($extension,$category)=(split(/\s+/,$line,2));
  270:                 push(@{$category_extensions{lc($category)}},$extension);
  271:             }
  272:             close($fh);
  273:         }
  274: 
  275:     }
  276: # ------------------------------------------------------------------ file types
  277:     {
  278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  279:                '/filetypes.tab';
  280:         if ( open (my $fh,"<$typesfile") ) {
  281:             while (my $line = <$fh>) {
  282: 		next if ($line =~ /^\#/);
  283: 		chomp($line);
  284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  285:                 if ($descr ne '') {
  286:                     $fe{$ending}=lc($emb);
  287:                     $fd{$ending}=$descr;
  288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  289:                 }
  290:             }
  291:             close($fh);
  292:         }
  293:     }
  294:     &Apache::lonnet::logthis(
  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
  296:     $readit=1;
  297:     }  # end of unless($readit) 
  298:     
  299: }
  300: 
  301: ###############################################################
  302: ##           HTML and Javascript Helper Functions            ##
  303: ###############################################################
  304: 
  305: =pod 
  306: 
  307: =head1 HTML and Javascript Functions
  308: 
  309: =over 4
  310: 
  311: =item * &browser_and_searcher_javascript()
  312: 
  313: X<browsing, javascript>X<searching, javascript>Returns a string
  314: containing javascript with two functions, C<openbrowser> and
  315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  316: tags.
  317: 
  318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  319: 
  320: inputs: formname, elementname, only, omit
  321: 
  322: formname and elementname indicate the name of the html form and name of
  323: the element that the results of the browsing selection are to be placed in. 
  324: 
  325: Specifying 'only' will restrict the browser to displaying only files
  326: with the given extension.  Can be a comma separated list.
  327: 
  328: Specifying 'omit' will restrict the browser to NOT displaying files
  329: with the given extension.  Can be a comma separated list.
  330: 
  331: =item * &opensearcher(formname,elementname) [javascript]
  332: 
  333: Inputs: formname, elementname
  334: 
  335: formname and elementname specify the name of the html form and the name
  336: of the element the selection from the search results will be placed in.
  337: 
  338: =cut
  339: 
  340: sub browser_and_searcher_javascript {
  341:     my ($mode)=@_;
  342:     if (!defined($mode)) { $mode='edit'; }
  343:     my $resurl=&escape_single(&lastresurl());
  344:     return <<END;
  345: // <!-- BEGIN LON-CAPA Internal
  346:     var editbrowser = null;
  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
  348:         var url = '$resurl/?';
  349:         if (editbrowser == null) {
  350:             url += 'launch=1&';
  351:         }
  352:         url += 'catalogmode=interactive&';
  353:         url += 'mode=$mode&';
  354:         url += 'inhibitmenu=yes&';
  355:         url += 'form=' + formname + '&';
  356:         if (only != null) {
  357:             url += 'only=' + only + '&';
  358:         } else {
  359:             url += 'only=&';
  360: 	}
  361:         if (omit != null) {
  362:             url += 'omit=' + omit + '&';
  363:         } else {
  364:             url += 'omit=&';
  365: 	}
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Browser';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editbrowser = open(url,title,options,'1');
  376:         editbrowser.focus();
  377:     }
  378:     var editsearcher;
  379:     function opensearcher(formname,elementname,titleelement) {
  380:         var url = '/adm/searchcat?';
  381:         if (editsearcher == null) {
  382:             url += 'launch=1&';
  383:         }
  384:         url += 'catalogmode=interactive&';
  385:         url += 'mode=$mode&';
  386:         url += 'form=' + formname + '&';
  387:         if (titleelement != null) {
  388:             url += 'titleelement=' + titleelement + '&';
  389:         } else {
  390: 	    url += 'titleelement=&';
  391: 	}
  392:         url += 'element=' + elementname + '';
  393:         var title = 'Search';
  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  395:         options += ',width=700,height=600';
  396:         editsearcher = open(url,title,options,'1');
  397:         editsearcher.focus();
  398:     }
  399: // END LON-CAPA Internal -->
  400: END
  401: }
  402: 
  403: sub lastresurl {
  404:     if ($env{'environment.lastresurl'}) {
  405: 	return $env{'environment.lastresurl'}
  406:     } else {
  407: 	return '/res';
  408:     }
  409: }
  410: 
  411: sub storeresurl {
  412:     my $resurl=&Apache::lonnet::clutter(shift);
  413:     unless ($resurl=~/^\/res/) { return 0; }
  414:     $resurl=~s/\/$//;
  415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  417:     return 1;
  418: }
  419: 
  420: sub studentbrowser_javascript {
  421:    unless (
  422:             (($env{'request.course.id'}) && 
  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  425: 					  '/'.$env{'request.course.sec'})
  426: 	      ))
  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
  428:           ) { return ''; }  
  429:    return (<<'ENDSTDBRW');
  430: <script type="text/javascript" language="Javascript">
  431: // <![CDATA[
  432:     var stdeditbrowser;
  433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  434:         var url = '/adm/pickstudent?';
  435:         var filter;
  436: 	if (!ignorefilter) {
  437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  438: 	}
  439:         if (filter != null) {
  440:            if (filter != '') {
  441:                url += 'filter='+filter+'&';
  442: 	   }
  443:         }
  444:         url += 'form=' + formname + '&unameelement='+uname+
  445:                                     '&udomelement='+udom+
  446:                                     '&clicker='+clicker;
  447: 	if (roleflag) { url+="&roles=1"; }
  448:         if (courseadvonly) { url+="&courseadvonly=1"; }
  449:         var title = 'Student_Browser';
  450:         var options = 'scrollbars=1,resizable=1,menubar=0';
  451:         options += ',width=700,height=600';
  452:         stdeditbrowser = open(url,title,options,'1');
  453:         stdeditbrowser.focus();
  454:     }
  455: // ]]>
  456: </script>
  457: ENDSTDBRW
  458: }
  459: 
  460: sub resourcebrowser_javascript {
  461:    unless ($env{'request.course.id'}) { return ''; }
  462:    return (<<'ENDRESBRW');
  463: <script type="text/javascript" language="Javascript">
  464: // <![CDATA[
  465:     var reseditbrowser;
  466:     function openresbrowser(formname,reslink) {
  467:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  468:         var title = 'Resource_Browser';
  469:         var options = 'scrollbars=1,resizable=1,menubar=0';
  470:         options += ',width=700,height=500';
  471:         reseditbrowser = open(url,title,options,'1');
  472:         reseditbrowser.focus();
  473:     }
  474: // ]]>
  475: </script>
  476: ENDRESBRW
  477: }
  478: 
  479: sub selectstudent_link {
  480:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  481:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  482:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  483:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  484:    if ($env{'request.course.id'}) {  
  485:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  486: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  487: 					'/'.$env{'request.course.sec'})) {
  488: 	   return '';
  489:        }
  490:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  491:        if ($courseadvonly)  {
  492:            $callargs .= ",'',1,1";
  493:        }
  494:        return '<span class="LC_nobreak">'.
  495:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  496:               &mt('Select User').'</a></span>';
  497:    }
  498:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  499:        $callargs .= ",'',1"; 
  500:        return '<span class="LC_nobreak">'.
  501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  502:               &mt('Select User').'</a></span>';
  503:    }
  504:    return '';
  505: }
  506: 
  507: sub selectresource_link {
  508:    my ($form,$reslink,$arg)=@_;
  509:    
  510:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  511:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  512:    unless ($env{'request.course.id'}) { return $arg; }
  513:    return '<span class="LC_nobreak">'.
  514:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  515:               $arg.'</a></span>';
  516: }
  517: 
  518: 
  519: 
  520: sub authorbrowser_javascript {
  521:     return <<"ENDAUTHORBRW";
  522: <script type="text/javascript" language="JavaScript">
  523: // <![CDATA[
  524: var stdeditbrowser;
  525: 
  526: function openauthorbrowser(formname,udom) {
  527:     var url = '/adm/pickauthor?';
  528:     url += 'form='+formname+'&roledom='+udom;
  529:     var title = 'Author_Browser';
  530:     var options = 'scrollbars=1,resizable=1,menubar=0';
  531:     options += ',width=700,height=600';
  532:     stdeditbrowser = open(url,title,options,'1');
  533:     stdeditbrowser.focus();
  534: }
  535: 
  536: // ]]>
  537: </script>
  538: ENDAUTHORBRW
  539: }
  540: 
  541: sub coursebrowser_javascript {
  542:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  543:         $credits_element,$instcode) = @_;
  544:     my $wintitle = 'Course_Browser';
  545:     if ($crstype eq 'Community') {
  546:         $wintitle = 'Community_Browser';
  547:     }
  548:     my $id_functions = &javascript_index_functions();
  549:     my $output = '
  550: <script type="text/javascript" language="JavaScript">
  551: // <![CDATA[
  552:     var stdeditbrowser;'."\n";
  553: 
  554:     $output .= <<"ENDSTDBRW";
  555:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  556:         var url = '/adm/pickcourse?';
  557:         var formid = getFormIdByName(formname);
  558:         var domainfilter = getDomainFromSelectbox(formname,udom);
  559:         if (domainfilter != null) {
  560:            if (domainfilter != '') {
  561:                url += 'domainfilter='+domainfilter+'&';
  562: 	   }
  563:         }
  564:         url += 'form=' + formname + '&cnumelement='+uname+
  565: 	                            '&cdomelement='+udom+
  566:                                     '&cnameelement='+desc;
  567:         if (extra_element !=null && extra_element != '') {
  568:             if (formname == 'rolechoice' || formname == 'studentform') {
  569:                 url += '&roleelement='+extra_element;
  570:                 if (domainfilter == null || domainfilter == '') {
  571:                     url += '&domainfilter='+extra_element;
  572:                 }
  573:             }
  574:             else {
  575:                 if (formname == 'portform') {
  576:                     url += '&setroles='+extra_element;
  577:                 } else {
  578:                     if (formname == 'rules') {
  579:                         url += '&fixeddom='+extra_element; 
  580:                     }
  581:                 }
  582:             }     
  583:         }
  584:         if (type != null && type != '') {
  585:             url += '&type='+type;
  586:         }
  587:         if (type_elem != null && type_elem != '') {
  588:             url += '&typeelement='+type_elem;
  589:         }
  590:         if (formname == 'ccrs') {
  591:             var ownername = document.forms[formid].ccuname.value;
  592:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  593:             url += '&cloner='+ownername+':'+ownerdom;
  594:             if (type == 'Course') {
  595:                 url += '&crscode='+document.forms[formid].crscode.value;
  596:             }
  597:         }
  598:         if (formname == 'requestcrs') {
  599:             url += '&crsdom=$domainfilter&crscode=$instcode';
  600:         }
  601:         if (multflag !=null && multflag != '') {
  602:             url += '&multiple='+multflag;
  603:         }
  604:         var title = '$wintitle';
  605:         var options = 'scrollbars=1,resizable=1,menubar=0';
  606:         options += ',width=700,height=600';
  607:         stdeditbrowser = open(url,title,options,'1');
  608:         stdeditbrowser.focus();
  609:     }
  610: $id_functions
  611: ENDSTDBRW
  612:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  613:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  614:                                       $credits_element);
  615:     }
  616:     $output .= '
  617: // ]]>
  618: </script>';
  619:     return $output;
  620: }
  621: 
  622: sub javascript_index_functions {
  623:     return <<"ENDJS";
  624: 
  625: function getFormIdByName(formname) {
  626:     for (var i=0;i<document.forms.length;i++) {
  627:         if (document.forms[i].name == formname) {
  628:             return i;
  629:         }
  630:     }
  631:     return -1;
  632: }
  633: 
  634: function getIndexByName(formid,item) {
  635:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  636:         if (document.forms[formid].elements[i].name == item) {
  637:             return i;
  638:         }
  639:     }
  640:     return -1;
  641: }
  642: 
  643: function getDomainFromSelectbox(formname,udom) {
  644:     var userdom;
  645:     var formid = getFormIdByName(formname);
  646:     if (formid > -1) {
  647:         var domid = getIndexByName(formid,udom);
  648:         if (domid > -1) {
  649:             if (document.forms[formid].elements[domid].type == 'select-one') {
  650:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  651:             }
  652:             if (document.forms[formid].elements[domid].type == 'hidden') {
  653:                 userdom=document.forms[formid].elements[domid].value;
  654:             }
  655:         }
  656:     }
  657:     return userdom;
  658: }
  659: 
  660: ENDJS
  661: 
  662: }
  663: 
  664: sub javascript_array_indexof {
  665:     return <<ENDJS;
  666: <script type="text/javascript" language="JavaScript">
  667: // <![CDATA[
  668: 
  669: if (!Array.prototype.indexOf) {
  670:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  671:         "use strict";
  672:         if (this === void 0 || this === null) {
  673:             throw new TypeError();
  674:         }
  675:         var t = Object(this);
  676:         var len = t.length >>> 0;
  677:         if (len === 0) {
  678:             return -1;
  679:         }
  680:         var n = 0;
  681:         if (arguments.length > 0) {
  682:             n = Number(arguments[1]);
  683:             if (n !== n) { // shortcut for verifying if it is NaN
  684:                 n = 0;
  685:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  686:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  687:             }
  688:         }
  689:         if (n >= len) {
  690:             return -1;
  691:         }
  692:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  693:         for (; k < len; k++) {
  694:             if (k in t && t[k] === searchElement) {
  695:                 return k;
  696:             }
  697:         }
  698:         return -1;
  699:     }
  700: }
  701: 
  702: // ]]>
  703: </script>
  704: 
  705: ENDJS
  706: 
  707: }
  708: 
  709: sub userbrowser_javascript {
  710:     my $id_functions = &javascript_index_functions();
  711:     return <<"ENDUSERBRW";
  712: 
  713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  714:     var url = '/adm/pickuser?';
  715:     var userdom = getDomainFromSelectbox(formname,udom);
  716:     if (userdom != null) {
  717:        if (userdom != '') {
  718:            url += 'srchdom='+userdom+'&';
  719:        }
  720:     }
  721:     url += 'form=' + formname + '&unameelement='+uname+
  722:                                 '&udomelement='+udom+
  723:                                 '&ulastelement='+ulast+
  724:                                 '&ufirstelement='+ufirst+
  725:                                 '&uemailelement='+uemail+
  726:                                 '&hideudomelement='+hideudom+
  727:                                 '&coursedom='+crsdom;
  728:     if ((caller != null) && (caller != undefined)) {
  729:         url += '&caller='+caller;
  730:     }
  731:     var title = 'User_Browser';
  732:     var options = 'scrollbars=1,resizable=1,menubar=0';
  733:     options += ',width=700,height=600';
  734:     var stdeditbrowser = open(url,title,options,'1');
  735:     stdeditbrowser.focus();
  736: }
  737: 
  738: function fix_domain (formname,udom,origdom,uname) {
  739:     var formid = getFormIdByName(formname);
  740:     if (formid > -1) {
  741:         var unameid = getIndexByName(formid,uname);
  742:         var domid = getIndexByName(formid,udom);
  743:         var hidedomid = getIndexByName(formid,origdom);
  744:         if (hidedomid > -1) {
  745:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  746:             var unameval = document.forms[formid].elements[unameid].value;
  747:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  748:                 if (domid > -1) {
  749:                     var slct = document.forms[formid].elements[domid];
  750:                     if (slct.type == 'select-one') {
  751:                         var i;
  752:                         for (i=0;i<slct.length;i++) {
  753:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  754:                         }
  755:                     }
  756:                     if (slct.type == 'hidden') {
  757:                         slct.value = fixeddom;
  758:                     }
  759:                 }
  760:             }
  761:         }
  762:     }
  763:     return;
  764: }
  765: 
  766: $id_functions
  767: ENDUSERBRW
  768: }
  769: 
  770: sub setsec_javascript {
  771:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  772:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  773:         $communityrolestr);
  774:     if ($role_element ne '') {
  775:         my @allroles = ('st','ta','ep','in','ad');
  776:         foreach my $crstype ('Course','Community') {
  777:             if ($crstype eq 'Community') {
  778:                 foreach my $role (@allroles) {
  779:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  780:                 }
  781:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  782:             } else {
  783:                 foreach my $role (@allroles) {
  784:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  785:                 }
  786:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  787:             }
  788:         }
  789:         $rolestr = '"'.join('","',@allroles).'"';
  790:         $courserolestr = '"'.join('","',@courserolenames).'"';
  791:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  792:     }
  793:     my $setsections = qq|
  794: function setSect(sectionlist) {
  795:     var sectionsArray = new Array();
  796:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  797:         sectionsArray = sectionlist.split(",");
  798:     }
  799:     var numSections = sectionsArray.length;
  800:     document.$formname.$sec_element.length = 0;
  801:     if (numSections == 0) {
  802:         document.$formname.$sec_element.multiple=false;
  803:         document.$formname.$sec_element.size=1;
  804:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  805:     } else {
  806:         if (numSections == 1) {
  807:             document.$formname.$sec_element.multiple=false;
  808:             document.$formname.$sec_element.size=1;
  809:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  810:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  811:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  812:         } else {
  813:             for (var i=0; i<numSections; i++) {
  814:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  815:             }
  816:             document.$formname.$sec_element.multiple=true
  817:             if (numSections < 3) {
  818:                 document.$formname.$sec_element.size=numSections;
  819:             } else {
  820:                 document.$formname.$sec_element.size=3;
  821:             }
  822:             document.$formname.$sec_element.options[0].selected = false
  823:         }
  824:     }
  825: }
  826: 
  827: function setRole(crstype) {
  828: |;
  829:     if ($role_element eq '') {
  830:         $setsections .= '    return;
  831: }
  832: ';
  833:     } else {
  834:         $setsections .= qq|
  835:     var elementLength = document.$formname.$role_element.length;
  836:     var allroles = Array($rolestr);
  837:     var courserolenames = Array($courserolestr);
  838:     var communityrolenames = Array($communityrolestr);
  839:     if (elementLength != undefined) {
  840:         if (document.$formname.$role_element.options[5].value == 'cc') {
  841:             if (crstype == 'Course') {
  842:                 return;
  843:             } else {
  844:                 allroles[5] = 'co';
  845:                 for (var i=0; i<6; i++) {
  846:                     document.$formname.$role_element.options[i].value = allroles[i];
  847:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  848:                 }
  849:             }
  850:         } else {
  851:             if (crstype == 'Community') {
  852:                 return;
  853:             } else {
  854:                 allroles[5] = 'cc';
  855:                 for (var i=0; i<6; i++) {
  856:                     document.$formname.$role_element.options[i].value = allroles[i];
  857:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  858:                 }
  859:             }
  860:         }
  861:     }
  862:     return;
  863: }
  864: |;
  865:     }
  866:     if ($credits_element) {
  867:         $setsections .= qq|
  868: function setCredits(defaultcredits) {
  869:     document.$formname.$credits_element.value = defaultcredits;
  870:     return;
  871: }
  872: |;
  873:     }
  874:     return $setsections;
  875: }
  876: 
  877: sub selectcourse_link {
  878:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  879:        $typeelement) = @_;
  880:    my $type = $selecttype;
  881:    my $linktext = &mt('Select Course');
  882:    if ($selecttype eq 'Community') {
  883:        $linktext = &mt('Select Community');
  884:    } elsif ($selecttype eq 'Placement') {
  885:        $linktext = &mt('Select Placement Test'); 
  886:    } elsif ($selecttype eq 'Course/Community') {
  887:        $linktext = &mt('Select Course/Community');
  888:        $type = '';
  889:    } elsif ($selecttype eq 'Select') {
  890:        $linktext = &mt('Select');
  891:        $type = '';
  892:    }
  893:    return '<span class="LC_nobreak">'
  894:          ."<a href='"
  895:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  896:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  897:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  898:          ."'>".$linktext.'</a>'
  899:          .'</span>';
  900: }
  901: 
  902: sub selectauthor_link {
  903:    my ($form,$udom)=@_;
  904:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  905:           &mt('Select Author').'</a>';
  906: }
  907: 
  908: sub selectuser_link {
  909:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  910:         $coursedom,$linktext,$caller) = @_;
  911:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  912:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  913:            ');">'.$linktext.'</a>';
  914: }
  915: 
  916: sub check_uncheck_jscript {
  917:     my $jscript = <<"ENDSCRT";
  918: function checkAll(field) {
  919:     if (field.length > 0) {
  920:         for (i = 0; i < field.length; i++) {
  921:             if (!field[i].disabled) { 
  922:                 field[i].checked = true;
  923:             }
  924:         }
  925:     } else {
  926:         if (!field.disabled) { 
  927:             field.checked = true;
  928:         }
  929:     }
  930: }
  931:  
  932: function uncheckAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             field[i].checked = false ;
  936:         }
  937:     } else {
  938:         field.checked = false ;
  939:     }
  940: }
  941: ENDSCRT
  942:     return $jscript;
  943: }
  944: 
  945: sub select_timezone {
  946:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  947:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  948:    if ($includeempty) {
  949:        $output .= '<option value=""';
  950:        if (($selected eq '') || ($selected eq 'local')) {
  951:            $output .= ' selected="selected" ';
  952:        }
  953:        $output .= '> </option>';
  954:    }
  955:    my @timezones = DateTime::TimeZone->all_names;
  956:    foreach my $tzone (@timezones) {
  957:        $output.= '<option value="'.$tzone.'"';
  958:        if ($tzone eq $selected) {
  959:            $output.=' selected="selected"';
  960:        }
  961:        $output.=">$tzone</option>\n";
  962:    }
  963:    $output.="</select>";
  964:    return $output;
  965: }
  966: 
  967: sub select_datelocale {
  968:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  969:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  970:     if ($includeempty) {
  971:         $output .= '<option value=""';
  972:         if ($selected eq '') {
  973:             $output .= ' selected="selected" ';
  974:         }
  975:         $output .= '> </option>';
  976:     }
  977:     my @languages = &Apache::lonlocal::preferred_languages();
  978:     my (@possibles,%locale_names);
  979:     my @locales = DateTime::Locale->ids();
  980:     foreach my $id (@locales) {
  981:         if ($id ne '') {
  982:             my ($en_terr,$native_terr);
  983:             my $loc = DateTime::Locale->load($id);
  984:             if (ref($loc)) {
  985:                 $en_terr = $loc->name();
  986:                 $native_terr = $loc->native_name();
  987:                 if (grep(/^en$/,@languages) || !@languages) {
  988:                     if ($en_terr ne '') {
  989:                         $locale_names{$id} = '('.$en_terr.')';
  990:                     } elsif ($native_terr ne '') {
  991:                         $locale_names{$id} = $native_terr;
  992:                     }
  993:                 } else {
  994:                     if ($native_terr ne '') {
  995:                         $locale_names{$id} = $native_terr.' ';
  996:                     } elsif ($en_terr ne '') {
  997:                         $locale_names{$id} = '('.$en_terr.')';
  998:                     }
  999:                 }
 1000:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1001:                 push(@possibles,$id);
 1002:             } 
 1003:         }
 1004:     }
 1005:     foreach my $item (sort(@possibles)) {
 1006:         $output.= '<option value="'.$item.'"';
 1007:         if ($item eq $selected) {
 1008:             $output.=' selected="selected"';
 1009:         }
 1010:         $output.=">$item";
 1011:         if ($locale_names{$item} ne '') {
 1012:             $output.='  '.$locale_names{$item};
 1013:         }
 1014:         $output.="</option>\n";
 1015:     }
 1016:     $output.="</select>";
 1017:     return $output;
 1018: }
 1019: 
 1020: sub select_language {
 1021:     my ($name,$selected,$includeempty,$noedit) = @_;
 1022:     my %langchoices;
 1023:     if ($includeempty) {
 1024:         %langchoices = ('' => 'No language preference');
 1025:     }
 1026:     foreach my $id (&languageids()) {
 1027:         my $code = &supportedlanguagecode($id);
 1028:         if ($code) {
 1029:             $langchoices{$code} = &plainlanguagedescription($id);
 1030:         }
 1031:     }
 1032:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1033:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1034: }
 1035: 
 1036: =pod
 1037: 
 1038: 
 1039: =item * &list_languages()
 1040: 
 1041: Returns an array reference that is suitable for use in language prompters.
 1042: Each array element is itself a two element array.  The first element
 1043: is the language code.  The second element a descsriptiuon of the 
 1044: language itself.  This is suitable for use in e.g.
 1045: &Apache::edit::select_arg (once dereferenced that is).
 1046: 
 1047: =cut 
 1048: 
 1049: sub list_languages {
 1050:     my @lang_choices;
 1051: 
 1052:     foreach my $id (&languageids()) {
 1053: 	my $code = &supportedlanguagecode($id);
 1054: 	if ($code) {
 1055: 	    my $selector    = $supported_codes{$id};
 1056: 	    my $description = &plainlanguagedescription($id);
 1057: 	    push(@lang_choices, [$selector, $description]);
 1058: 	}
 1059:     }
 1060:     return \@lang_choices;
 1061: }
 1062: 
 1063: =pod
 1064: 
 1065: =item * &linked_select_forms(...)
 1066: 
 1067: linked_select_forms returns a string containing a <script></script> block
 1068: and html for two <select> menus.  The select menus will be linked in that
 1069: changing the value of the first menu will result in new values being placed
 1070: in the second menu.  The values in the select menu will appear in alphabetical
 1071: order unless a defined order is provided.
 1072: 
 1073: linked_select_forms takes the following ordered inputs:
 1074: 
 1075: =over 4
 1076: 
 1077: =item * $formname, the name of the <form> tag
 1078: 
 1079: =item * $middletext, the text which appears between the <select> tags
 1080: 
 1081: =item * $firstdefault, the default value for the first menu
 1082: 
 1083: =item * $firstselectname, the name of the first <select> tag
 1084: 
 1085: =item * $secondselectname, the name of the second <select> tag
 1086: 
 1087: =item * $hashref, a reference to a hash containing the data for the menus.
 1088: 
 1089: =item * $menuorder, the order of values in the first menu
 1090: 
 1091: =item * $onchangefirst, additional javascript call to execute for an onchange
 1092:         event for the first <select> tag
 1093: 
 1094: =item * $onchangesecond, additional javascript call to execute for an onchange
 1095:         event for the second <select> tag
 1096: 
 1097: =item * $suffix, to differentiate separate uses of select2data javascript
 1098:         objects in a page.
 1099: 
 1100: =back 
 1101: 
 1102: Below is an example of such a hash.  Only the 'text', 'default', and 
 1103: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1104: values for the first select menu.  The text that coincides with the 
 1105: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1106: and text for the second menu are given in the hash pointed to by 
 1107: $menu{$choice1}->{'select2'}.  
 1108: 
 1109:  my %menu = ( A1 => { text =>"Choice A1" ,
 1110:                        default => "B3",
 1111:                        select2 => { 
 1112:                            B1 => "Choice B1",
 1113:                            B2 => "Choice B2",
 1114:                            B3 => "Choice B3",
 1115:                            B4 => "Choice B4"
 1116:                            },
 1117:                        order => ['B4','B3','B1','B2'],
 1118:                    },
 1119:                A2 => { text =>"Choice A2" ,
 1120:                        default => "C2",
 1121:                        select2 => { 
 1122:                            C1 => "Choice C1",
 1123:                            C2 => "Choice C2",
 1124:                            C3 => "Choice C3"
 1125:                            },
 1126:                        order => ['C2','C1','C3'],
 1127:                    },
 1128:                A3 => { text =>"Choice A3" ,
 1129:                        default => "D6",
 1130:                        select2 => { 
 1131:                            D1 => "Choice D1",
 1132:                            D2 => "Choice D2",
 1133:                            D3 => "Choice D3",
 1134:                            D4 => "Choice D4",
 1135:                            D5 => "Choice D5",
 1136:                            D6 => "Choice D6",
 1137:                            D7 => "Choice D7"
 1138:                            },
 1139:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1140:                    }
 1141:                );
 1142: 
 1143: =cut
 1144: 
 1145: sub linked_select_forms {
 1146:     my ($formname,
 1147:         $middletext,
 1148:         $firstdefault,
 1149:         $firstselectname,
 1150:         $secondselectname, 
 1151:         $hashref,
 1152:         $menuorder,
 1153:         $onchangefirst,
 1154:         $onchangesecond,
 1155:         $suffix
 1156:         ) = @_;
 1157:     my $second = "document.$formname.$secondselectname";
 1158:     my $first = "document.$formname.$firstselectname";
 1159:     # output the javascript to do the changing
 1160:     my $result = '';
 1161:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1162:     $result.="// <![CDATA[\n";
 1163:     $result.="var select2data${suffix} = new Object();\n";
 1164:     $" = '","';
 1165:     my $debug = '';
 1166:     foreach my $s1 (sort(keys(%$hashref))) {
 1167:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1168:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1169:             $hashref->{$s1}->{'default'}."');\n";
 1170:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1171:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1172:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1173:             @s2values = @{$hashref->{$s1}->{'order'}};
 1174:         }
 1175:         $result.="\"@s2values\");\n";
 1176:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1177:         my @s2texts;
 1178:         foreach my $value (@s2values) {
 1179:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1180:         }
 1181:         $result.="\"@s2texts\");\n";
 1182:     }
 1183:     $"=' ';
 1184:     $result.= <<"END";
 1185: 
 1186: function select1${suffix}_changed() {
 1187:     // Determine new choice
 1188:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1189:     // update select2
 1190:     var values     = select2data${suffix}[newvalue].values;
 1191:     var texts      = select2data${suffix}[newvalue].texts;
 1192:     var select2def = select2data${suffix}[newvalue].def;
 1193:     var i;
 1194:     // out with the old
 1195:     $second.options.length = 0;
 1196:     // in with the new
 1197:     for (i=0;i<values.length; i++) {
 1198:         $second.options[i] = new Option(values[i]);
 1199:         $second.options[i].value = values[i];
 1200:         $second.options[i].text = texts[i];
 1201:         if (values[i] == select2def) {
 1202:             $second.options[i].selected = true;
 1203:         }
 1204:     }
 1205: }
 1206: // ]]>
 1207: </script>
 1208: END
 1209:     # output the initial values for the selection lists
 1210:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1211:     my @order = sort(keys(%{$hashref}));
 1212:     if (ref($menuorder) eq 'ARRAY') {
 1213:         @order = @{$menuorder};
 1214:     }
 1215:     foreach my $value (@order) {
 1216:         $result.="    <option value=\"$value\" ";
 1217:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1218:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1219:     }
 1220:     $result .= "</select>\n";
 1221:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1222:     $result .= $middletext;
 1223:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1224:     if ($onchangesecond) {
 1225:         $result .= ' onchange="'.$onchangesecond.'"';
 1226:     }
 1227:     $result .= ">\n";
 1228:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1229:     
 1230:     my @secondorder = sort(keys(%select2));
 1231:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1232:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1233:     }
 1234:     foreach my $value (@secondorder) {
 1235:         $result.="    <option value=\"$value\" ";        
 1236:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1237:         $result.=">".&mt($select2{$value})."</option>\n";
 1238:     }
 1239:     $result .= "</select>\n";
 1240:     #    return $debug;
 1241:     return $result;
 1242: }   #  end of sub linked_select_forms {
 1243: 
 1244: =pod
 1245: 
 1246: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1247: 
 1248: Returns a string corresponding to an HTML link to the given help
 1249: $topic, where $topic corresponds to the name of a .tex file in
 1250: /home/httpd/html/adm/help/tex, with underscores replaced by
 1251: spaces. 
 1252: 
 1253: $text will optionally be linked to the same topic, allowing you to
 1254: link text in addition to the graphic. If you do not want to link
 1255: text, but wish to specify one of the later parameters, pass an
 1256: empty string. 
 1257: 
 1258: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1259: the link will not open a new window. If false, the link will open
 1260: a new window using Javascript. (Default is false.) 
 1261: 
 1262: $width and $height are optional numerical parameters that will
 1263: override the width and height of the popped up window, which may
 1264: be useful for certain help topics with big pictures included.
 1265: 
 1266: $imgid is the id of the img tag used for the help icon. This may be
 1267: used in a javascript call to switch the image src.  See 
 1268: lonhtmlcommon::htmlareaselectactive() for an example.
 1269: 
 1270: =cut
 1271: 
 1272: sub help_open_topic {
 1273:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1274:     $text = "" if (not defined $text);
 1275:     $stayOnPage = 0 if (not defined $stayOnPage);
 1276:     $width = 500 if (not defined $width);
 1277:     $height = 400 if (not defined $height);
 1278:     my $filename = $topic;
 1279:     $filename =~ s/ /_/g;
 1280: 
 1281:     my $template = "";
 1282:     my $link;
 1283:     
 1284:     $topic=~s/\W/\_/g;
 1285: 
 1286:     if (!$stayOnPage) {
 1287: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1288:     } elsif ($stayOnPage eq 'popup') {
 1289:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1290:     } else {
 1291: 	$link = "/adm/help/${filename}.hlp";
 1292:     }
 1293: 
 1294:     # Add the text
 1295:     if ($text ne "") {	
 1296: 	$template.='<span class="LC_help_open_topic">'
 1297:                   .'<a target="_top" href="'.$link.'">'
 1298:                   .$text.'</a>';
 1299:     }
 1300: 
 1301:     # (Always) Add the graphic
 1302:     my $title = &mt('Online Help');
 1303:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1304:     if ($imgid ne '') {
 1305:         $imgid = ' id="'.$imgid.'"';
 1306:     }
 1307:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1308:               .'<img src="'.$helpicon.'" border="0"'
 1309:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1310:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1311:               .' /></a>';
 1312:     if ($text ne "") {	
 1313:         $template.='</span>';
 1314:     }
 1315:     return $template;
 1316: 
 1317: }
 1318: 
 1319: # This is a quicky function for Latex cheatsheet editing, since it 
 1320: # appears in at least four places
 1321: sub helpLatexCheatsheet {
 1322:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1323:     my $out;
 1324:     my $addOther = '';
 1325:     if ($topic) {
 1326: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1327:     }
 1328:     $out = '<span>' # Start cheatsheet
 1329: 	  .$addOther
 1330:           .'<span>'
 1331: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1332: 	  .'</span> <span>'
 1333: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1334: 	  .'</span>';
 1335:     unless ($not_author) {
 1336:         $out .= '<span>'
 1337:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1338:                .'</span> <span>'
 1339:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1340: 	       .'</span>';
 1341:     }
 1342:     $out .= '</span>'; # End cheatsheet
 1343:     return $out;
 1344: }
 1345: 
 1346: sub general_help {
 1347:     my $helptopic='Student_Intro';
 1348:     if ($env{'request.role'}=~/^(ca|au)/) {
 1349: 	$helptopic='Authoring_Intro';
 1350:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1351: 	$helptopic='Course_Coordination_Intro';
 1352:     } elsif ($env{'request.role'}=~/^dc/) {
 1353:         $helptopic='Domain_Coordination_Intro';
 1354:     }
 1355:     return $helptopic;
 1356: }
 1357: 
 1358: sub update_help_link {
 1359:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1360:     my $origurl = $ENV{'REQUEST_URI'};
 1361:     $origurl=~s|^/~|/priv/|;
 1362:     my $timestamp = time;
 1363:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1364:         $$datum = &escape($$datum);
 1365:     }
 1366: 
 1367:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
 1368:     my $output .= <<"ENDOUTPUT";
 1369: <script type="text/javascript">
 1370: // <![CDATA[
 1371: banner_link = '$banner_link';
 1372: // ]]>
 1373: </script>
 1374: ENDOUTPUT
 1375:     return $output;
 1376: }
 1377: 
 1378: # now just updates the help link and generates a blue icon
 1379: sub help_open_menu {
 1380:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1381: 	= @_;    
 1382:     $stayOnPage = 1;
 1383:     my $output;
 1384:     if ($component_help) {
 1385: 	if (!$text) {
 1386: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1387: 				       $width,$height);
 1388: 	} else {
 1389: 	    my $help_text;
 1390: 	    $help_text=&unescape($topic);
 1391: 	    $output='<table><tr><td>'.
 1392: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1393: 				 $width,$height).'</td></tr></table>';
 1394: 	}
 1395:     }
 1396:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1397:     return $output.$banner_link;
 1398: }
 1399: 
 1400: sub top_nav_help {
 1401:     my ($text) = @_;
 1402:     $text = &mt($text);
 1403:     my $stay_on_page = 1;
 1404: 
 1405:     my ($link,$banner_link);
 1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1408: 	                         : "javascript:helpMenu('open')";
 1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1410:     }
 1411:     my $title = &mt('Get help');
 1412:     if ($link) {
 1413:         return <<"END";
 1414: $banner_link
 1415: <a href="$link" title="$title">$text</a>
 1416: END
 1417:     } else {
 1418:         return '&nbsp;'.$text.'&nbsp;';
 1419:     }
 1420: }
 1421: 
 1422: sub help_menu_js {
 1423:     my ($httphost) = @_;
 1424:     my $stayOnPage = 1;
 1425:     my $width = 620;
 1426:     my $height = 600;
 1427:     my $helptopic=&general_help();
 1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1430:     my $start_page =
 1431:         &Apache::loncommon::start_page('Help Menu', undef,
 1432: 				       {'frameset'    => 1,
 1433: 					'js_ready'    => 1,
 1434:                                         'use_absolute' => $httphost,
 1435: 					'add_entries' => {
 1436: 					    'border' => '0', 
 1437: 					    'rows'   => "110,*",},});
 1438:     my $end_page =
 1439:         &Apache::loncommon::end_page({'frameset' => 1,
 1440: 				      'js_ready' => 1,});
 1441: 
 1442:     my $template .= <<"ENDTEMPLATE";
 1443: <script type="text/javascript">
 1444: // <![CDATA[
 1445: // <!-- BEGIN LON-CAPA Internal
 1446: var banner_link = '';
 1447: function helpMenu(target) {
 1448:     var caller = this;
 1449:     if (target == 'open') {
 1450:         var newWindow = null;
 1451:         try {
 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1453:         }
 1454:         catch(error) {
 1455:             writeHelp(caller);
 1456:             return;
 1457:         }
 1458:         if (newWindow) {
 1459:             caller = newWindow;
 1460:         }
 1461:     }
 1462:     writeHelp(caller);
 1463:     return;
 1464: }
 1465: function writeHelp(caller) {
 1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1468:     caller.document.close();
 1469:     caller.focus();
 1470: }
 1471: // END LON-CAPA Internal -->
 1472: // ]]>
 1473: </script>
 1474: ENDTEMPLATE
 1475:     return $template;
 1476: }
 1477: 
 1478: sub help_open_bug {
 1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1480:     unless ($env{'user.adv'}) { return ''; }
 1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1482:     $text = "" if (not defined $text);
 1483: 	$stayOnPage=1;
 1484:     $width = 600 if (not defined $width);
 1485:     $height = 600 if (not defined $height);
 1486: 
 1487:     $topic=~s/\W+/\+/g;
 1488:     my $link='';
 1489:     my $template='';
 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1492:     if (!$stayOnPage)
 1493:     {
 1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1495:     }
 1496:     else
 1497:     {
 1498: 	$link = $url;
 1499:     }
 1500:     # Add the text
 1501:     if ($text ne "")
 1502:     {
 1503: 	$template .= 
 1504:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1505:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1506:     }
 1507: 
 1508:     # Add the graphic
 1509:     my $title = &mt('Report a Bug');
 1510:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1511:     $template .= <<"ENDTEMPLATE";
 1512:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1513: ENDTEMPLATE
 1514:     if ($text ne '') { $template.='</td></tr></table>' };
 1515:     return $template;
 1516: 
 1517: }
 1518: 
 1519: sub help_open_faq {
 1520:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1521:     unless ($env{'user.adv'}) { return ''; }
 1522:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1523:     $text = "" if (not defined $text);
 1524: 	$stayOnPage=1;
 1525:     $width = 350 if (not defined $width);
 1526:     $height = 400 if (not defined $height);
 1527: 
 1528:     $topic=~s/\W+/\+/g;
 1529:     my $link='';
 1530:     my $template='';
 1531:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1532:     if (!$stayOnPage)
 1533:     {
 1534: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1535:     }
 1536:     else
 1537:     {
 1538: 	$link = $url;
 1539:     }
 1540: 
 1541:     # Add the text
 1542:     if ($text ne "")
 1543:     {
 1544: 	$template .= 
 1545:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1546:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1547:     }
 1548: 
 1549:     # Add the graphic
 1550:     my $title = &mt('View the FAQ');
 1551:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1552:     $template .= <<"ENDTEMPLATE";
 1553:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1554: ENDTEMPLATE
 1555:     if ($text ne '') { $template.='</td></tr></table>' };
 1556:     return $template;
 1557: 
 1558: }
 1559: 
 1560: ###############################################################
 1561: ###############################################################
 1562: 
 1563: =pod
 1564: 
 1565: =item * &change_content_javascript():
 1566: 
 1567: This and the next function allow you to create small sections of an
 1568: otherwise static HTML page that you can update on the fly with
 1569: Javascript, even in Netscape 4.
 1570: 
 1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1572: must be written to the HTML page once. It will prove the Javascript
 1573: function "change(name, content)". Calling the change function with the
 1574: name of the section 
 1575: you want to update, matching the name passed to C<changable_area>, and
 1576: the new content you want to put in there, will put the content into
 1577: that area.
 1578: 
 1579: B<Note>: Netscape 4 only reserves enough space for the changable area
 1580: to contain room for the original contents. You need to "make space"
 1581: for whatever changes you wish to make, and be B<sure> to check your
 1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1583: it's adequate for updating a one-line status display, but little more.
 1584: This script will set the space to 100% width, so you only need to
 1585: worry about height in Netscape 4.
 1586: 
 1587: Modern browsers are much less limiting, and if you can commit to the
 1588: user not using Netscape 4, this feature may be used freely with
 1589: pretty much any HTML.
 1590: 
 1591: =cut
 1592: 
 1593: sub change_content_javascript {
 1594:     # If we're on Netscape 4, we need to use Layer-based code
 1595:     if ($env{'browser.type'} eq 'netscape' &&
 1596: 	$env{'browser.version'} =~ /^4\./) {
 1597: 	return (<<NETSCAPE4);
 1598: 	function change(name, content) {
 1599: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1600: 	    doc.open();
 1601: 	    doc.write(content);
 1602: 	    doc.close();
 1603: 	}
 1604: NETSCAPE4
 1605:     } else {
 1606: 	# Otherwise, we need to use semi-standards-compliant code
 1607: 	# (technically, "innerHTML" isn't standard but the equivalent
 1608: 	# is really scary, and every useful browser supports it
 1609: 	return (<<DOMBASED);
 1610: 	function change(name, content) {
 1611: 	    element = document.getElementById(name);
 1612: 	    element.innerHTML = content;
 1613: 	}
 1614: DOMBASED
 1615:     }
 1616: }
 1617: 
 1618: =pod
 1619: 
 1620: =item * &changable_area($name,$origContent):
 1621: 
 1622: This provides a "changable area" that can be modified on the fly via
 1623: the Javascript code provided in C<change_content_javascript>. $name is
 1624: the name you will use to reference the area later; do not repeat the
 1625: same name on a given HTML page more then once. $origContent is what
 1626: the area will originally contain, which can be left blank.
 1627: 
 1628: =cut
 1629: 
 1630: sub changable_area {
 1631:     my ($name, $origContent) = @_;
 1632: 
 1633:     if ($env{'browser.type'} eq 'netscape' &&
 1634: 	$env{'browser.version'} =~ /^4\./) {
 1635: 	# If this is netscape 4, we need to use the Layer tag
 1636: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1637:     } else {
 1638: 	return "<span id='$name'>$origContent</span>";
 1639:     }
 1640: }
 1641: 
 1642: =pod
 1643: 
 1644: =item * &viewport_geometry_js 
 1645: 
 1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1647: 
 1648: =cut
 1649: 
 1650: 
 1651: sub viewport_geometry_js { 
 1652:     return <<"GEOMETRY";
 1653: var Geometry = {};
 1654: function init_geometry() {
 1655:     if (Geometry.init) { return };
 1656:     Geometry.init=1;
 1657:     if (window.innerHeight) {
 1658:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1659:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1660:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1661:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1662:     }
 1663:     else if (document.documentElement && document.documentElement.clientHeight) {
 1664:         Geometry.getViewportHeight =
 1665:             function() { return document.documentElement.clientHeight; };
 1666:         Geometry.getViewportWidth =
 1667:             function() { return document.documentElement.clientWidth; };
 1668: 
 1669:         Geometry.getHorizontalScroll =
 1670:             function() { return document.documentElement.scrollLeft; };
 1671:         Geometry.getVerticalScroll =
 1672:             function() { return document.documentElement.scrollTop; };
 1673:     }
 1674:     else if (document.body.clientHeight) {
 1675:         Geometry.getViewportHeight =
 1676:             function() { return document.body.clientHeight; };
 1677:         Geometry.getViewportWidth =
 1678:             function() { return document.body.clientWidth; };
 1679:         Geometry.getHorizontalScroll =
 1680:             function() { return document.body.scrollLeft; };
 1681:         Geometry.getVerticalScroll =
 1682:             function() { return document.body.scrollTop; };
 1683:     }
 1684: }
 1685: 
 1686: GEOMETRY
 1687: }
 1688: 
 1689: =pod
 1690: 
 1691: =item * &viewport_size_js()
 1692: 
 1693: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1694: 
 1695: =cut
 1696: 
 1697: sub viewport_size_js {
 1698:     my $geometry = &viewport_geometry_js();
 1699:     return <<"DIMS";
 1700: 
 1701: $geometry
 1702: 
 1703: function getViewportDims(width,height) {
 1704:     init_geometry();
 1705:     width.value = Geometry.getViewportWidth();
 1706:     height.value = Geometry.getViewportHeight();
 1707:     return;
 1708: }
 1709: 
 1710: DIMS
 1711: }
 1712: 
 1713: =pod
 1714: 
 1715: =item * &resize_textarea_js()
 1716: 
 1717: emits the needed javascript to resize a textarea to be as big as possible
 1718: 
 1719: creates a function resize_textrea that takes two IDs first should be
 1720: the id of the element to resize, second should be the id of a div that
 1721: surrounds everything that comes after the textarea, this routine needs
 1722: to be attached to the <body> for the onload and onresize events.
 1723: 
 1724: =back
 1725: 
 1726: =cut
 1727: 
 1728: sub resize_textarea_js {
 1729:     my $geometry = &viewport_geometry_js();
 1730:     return <<"RESIZE";
 1731:     <script type="text/javascript">
 1732: // <![CDATA[
 1733: $geometry
 1734: 
 1735: function getX(element) {
 1736:     var x = 0;
 1737:     while (element) {
 1738: 	x += element.offsetLeft;
 1739: 	element = element.offsetParent;
 1740:     }
 1741:     return x;
 1742: }
 1743: function getY(element) {
 1744:     var y = 0;
 1745:     while (element) {
 1746: 	y += element.offsetTop;
 1747: 	element = element.offsetParent;
 1748:     }
 1749:     return y;
 1750: }
 1751: 
 1752: 
 1753: function resize_textarea(textarea_id,bottom_id) {
 1754:     init_geometry();
 1755:     var textarea        = document.getElementById(textarea_id);
 1756:     //alert(textarea);
 1757: 
 1758:     var textarea_top    = getY(textarea);
 1759:     var textarea_height = textarea.offsetHeight;
 1760:     var bottom          = document.getElementById(bottom_id);
 1761:     var bottom_top      = getY(bottom);
 1762:     var bottom_height   = bottom.offsetHeight;
 1763:     var window_height   = Geometry.getViewportHeight();
 1764:     var fudge           = 23;
 1765:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1766:     if (new_height < 300) {
 1767: 	new_height = 300;
 1768:     }
 1769:     textarea.style.height=new_height+'px';
 1770: }
 1771: // ]]>
 1772: </script>
 1773: RESIZE
 1774: 
 1775: }
 1776: 
 1777: sub colorfuleditor_js {
 1778:     my $browse_or_search;
 1779:     my $respath;
 1780:     my ($cnum,$cdom) = &crsauthor_url();
 1781:     if ($cnum) {
 1782:         $respath = "/res/$cdom/$cnum/";
 1783:         my %js_lt = &Apache::lonlocal::texthash(
 1784:             sunm => 'Sub-directory name',
 1785:             save => 'Save page to make this permanent',
 1786:         );
 1787:         &js_escape(\%js_lt);
 1788:         $browse_or_search = <<"END";
 1789: 
 1790:     function toggleChooser(form,element,titleid,only,search) {
 1791:         var disp = 'none';
 1792:         if (document.getElementById('chooser_'+element)) {
 1793:             var curr = document.getElementById('chooser_'+element).style.display;
 1794:             if (curr == 'none') {
 1795:                 disp='inline';
 1796:                 if (form.elements['chooser_'+element].length) {
 1797:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1798:                         form.elements['chooser_'+element][i].checked = false;
 1799:                     }
 1800:                 }
 1801:                 toggleResImport(form,element);
 1802:             }
 1803:             document.getElementById('chooser_'+element).style.display = disp;
 1804:         }
 1805:     }
 1806: 
 1807:     function toggleCrsFile(form,element,numdirs) {
 1808:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1809:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1810:             if (curr == 'none') {
 1811:                 if (numdirs) {
 1812:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1813:                     if (numdirs > 1) {
 1814:                         window['select1'+element+'_changed']();
 1815:                     }
 1816:                 }
 1817:             } 
 1818:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1819:             
 1820:         }
 1821:         if (document.getElementById('chooser_'+element+'_upload')) {
 1822:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1823:             if (document.getElementById('uploadcrsres_'+element)) {
 1824:                 document.getElementById('uploadcrsres_'+element).value = '';
 1825:             }
 1826:         }
 1827:         return;
 1828:     }
 1829: 
 1830:     function toggleCrsUpload(form,element,numcrsdirs) {
 1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1832:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1833:         }
 1834:         if (document.getElementById('chooser_'+element+'_upload')) {
 1835:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1836:             if (curr == 'none') {
 1837:                 if (numcrsdirs) {
 1838:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1839:                    form.elements['newsubdir_'+element][0].checked = true;
 1840:                    toggleNewsubdir(form,element);
 1841:                 }
 1842:             }
 1843:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1844:         }
 1845:         return;
 1846:     }
 1847: 
 1848:     function toggleResImport(form,element) {
 1849:         var choices = new Array('crsres','upload');
 1850:         for (var i=0; i<choices.length; i++) {
 1851:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1852:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1853:             }
 1854:         }
 1855:     }
 1856: 
 1857:     function toggleNewsubdir(form,element) {
 1858:         var newsub = form.elements['newsubdir_'+element];
 1859:         if (newsub) {
 1860:             if (newsub.length) {
 1861:                 for (var j=0; j<newsub.length; j++) {
 1862:                     if (newsub[j].checked) {
 1863:                         if (document.getElementById('newsubdirname_'+element)) {
 1864:                             if (newsub[j].value == '1') {
 1865:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1866:                                 if (document.getElementById('newsubdir_'+element)) {
 1867:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1868:                                 }
 1869:                             } else {
 1870:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1871:                                 document.getElementById('newsubdirname_'+element).value = "";
 1872:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1873:                             }
 1874:                         }
 1875:                         break; 
 1876:                     }
 1877:                 }
 1878:             }
 1879:         }
 1880:     }
 1881: 
 1882:     function updateCrsFile(form,element) {
 1883:         var directory = form.elements['coursepath_'+element];
 1884:         var filename = form.elements['coursefile_'+element];
 1885:         var path = directory.options[directory.selectedIndex].value;
 1886:         var file = filename.options[filename.selectedIndex].value;
 1887:         form.elements[element].value = '$respath';
 1888:         if (path == '/') {
 1889:             form.elements[element].value += file;
 1890:         } else {
 1891:             form.elements[element].value += path+'/'+file;
 1892:         }
 1893:         unClean();
 1894:         if (document.getElementById('previewimg_'+element)) {
 1895:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1896:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1897:         }
 1898:         if (document.getElementById('showimg_'+element)) {
 1899:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1900:         }
 1901:         toggleChooser(form,element);
 1902:         return;
 1903:     }
 1904: 
 1905:     function uploadDone(suffix,name) {
 1906:         if (name) {
 1907: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1908:             unClean();
 1909:             toggleChooser(document.forms["lonhomework"],suffix);
 1910:         }
 1911:     }
 1912: 
 1913: \$(document).ready(function(){
 1914: 
 1915:     \$(document).delegate('form :submit', 'click', function( event ) {
 1916:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1917:             var buttonId = this.id;
 1918:             var suffix = buttonId.toString();
 1919:             suffix = suffix.replace(/^crsupload_/,'');
 1920:             event.preventDefault();
 1921:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1922:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1923:             \$(this.form).submit();
 1924:             document.lonhomework.target = '';
 1925:             if (document.getElementById('crsuploadto_'+suffix)) {
 1926:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1927:             }
 1928:             return false;
 1929:         }
 1930:     });
 1931: });
 1932: END
 1933:     }
 1934:     return <<"COLORFULEDIT"
 1935: <script type="text/javascript">
 1936: // <![CDATA[>
 1937:     function fold_box(curDepth, lastresource){
 1938: 
 1939:     // we need a list because there can be several blocks you need to fold in one tag
 1940:         var block = document.getElementsByName('foldblock_'+curDepth);
 1941:     // but there is only one folding button per tag
 1942:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1943: 
 1944:         if(block.item(0).style.display == 'none'){
 1945: 
 1946:             foldbutton.value = '@{[&mt("Hide")]}';
 1947:             for (i = 0; i < block.length; i++){
 1948:                 block.item(i).style.display = '';
 1949:             }
 1950:         }else{
 1951: 
 1952:             foldbutton.value = '@{[&mt("Show")]}';
 1953:             for (i = 0; i < block.length; i++){
 1954:                 // block.item(i).style.visibility = 'collapse';
 1955:                 block.item(i).style.display = 'none';
 1956:             }
 1957:         };
 1958:         saveState(lastresource);
 1959:     }
 1960: 
 1961:     function saveState (lastresource) {
 1962: 
 1963:         var tag_list = getTagList();
 1964:         if(tag_list != null){
 1965:             var timestamp = new Date().getTime();
 1966:             var key = lastresource;
 1967: 
 1968:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1969:             // starting with timestamp
 1970:             var value = timestamp+';';
 1971: 
 1972:             // building the list of key-value pairs
 1973:             for(var i = 0; i < tag_list.length; i++){
 1974:                 value += tag_list[i]+',';
 1975:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1976:             }
 1977: 
 1978:             // only iterate whole storage if nothing to override
 1979:             if(localStorage.getItem(key) == null){        
 1980: 
 1981:                 // prevent storage from growing large
 1982:                 if(localStorage.length > 50){
 1983:                     var regex_getTimestamp = /^(?:\d)+;/;
 1984:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1985:                     var oldest_key;
 1986:                     
 1987:                     for(var i = 1; i < localStorage.length; i++){
 1988:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1989:                             oldest_key = localStorage.key(i);
 1990:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1991:                         }
 1992:                     }
 1993:                     localStorage.removeItem(oldest_key);
 1994:                 }
 1995:             }
 1996:             localStorage.setItem(key,value);
 1997:         }
 1998:     }
 1999: 
 2000:     // restore folding status of blocks (on page load)
 2001:     function restoreState (lastresource) {
 2002:         if(localStorage.getItem(lastresource) != null){
 2003:             var key = lastresource;
 2004:             var value = localStorage.getItem(key);
 2005:             var regex_delTimestamp = /^\d+;/;
 2006: 
 2007:             value.replace(regex_delTimestamp, '');
 2008: 
 2009:             var valueArr = value.split(';');
 2010:             var pairs;
 2011:             var elements;
 2012:             for (var i = 0; i < valueArr.length; i++){
 2013:                 pairs = valueArr[i].split(',');
 2014:                 elements = document.getElementsByName(pairs[0]);
 2015: 
 2016:                 for (var j = 0; j < elements.length; j++){  
 2017:                     elements[j].style.display = pairs[1];
 2018:                     if (pairs[1] == "none"){
 2019:                         var regex_id = /([_\\d]+)\$/;
 2020:                         regex_id.exec(pairs[0]);
 2021:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2022:                     }
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027: 
 2028:     function getTagList () {
 2029:         
 2030:         var stringToSearch = document.lonhomework.innerHTML;
 2031: 
 2032:         var ret = new Array();
 2033:         var regex_findBlock = /(foldblock_.*?)"/g;
 2034:         var tag_list = stringToSearch.match(regex_findBlock);
 2035: 
 2036:         if(tag_list != null){
 2037:             for(var i = 0; i < tag_list.length; i++){            
 2038:                 ret.push(tag_list[i].replace(/"/, ''));
 2039:             }
 2040:         }
 2041:         return ret;
 2042:     }
 2043: 
 2044:     function saveScrollPosition (resource) {
 2045:         var tag_list = getTagList();
 2046: 
 2047:         // we dont always want to jump to the first block
 2048:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2049:         if(\$(window).scrollTop() > 170){
 2050:             if(tag_list != null){
 2051:                 var result;
 2052:                 for(var i = 0; i < tag_list.length; i++){
 2053:                     if(isElementInViewport(tag_list[i])){
 2054:                         result += tag_list[i]+';';
 2055:                     }
 2056:                 }
 2057:                 sessionStorage.setItem('anchor_'+resource, result);
 2058:             }
 2059:         } else {
 2060:             // we dont need to save zero, just delete the item to leave everything tidy
 2061:             sessionStorage.removeItem('anchor_'+resource);
 2062:         }
 2063:     }
 2064: 
 2065:     function restoreScrollPosition(resource){
 2066: 
 2067:         var elem = sessionStorage.getItem('anchor_'+resource);
 2068:         if(elem != null){
 2069:             var tag_list = elem.split(';');
 2070:             var elem_list;
 2071: 
 2072:             for(var i = 0; i < tag_list.length; i++){
 2073:                 elem_list = document.getElementsByName(tag_list[i]);
 2074:                 
 2075:                 if(elem_list.length > 0){
 2076:                     elem = elem_list[0];
 2077:                     break;
 2078:                 }
 2079:             }
 2080:             elem.scrollIntoView();
 2081:         }
 2082:     }
 2083: 
 2084:     function isElementInViewport(el) {
 2085: 
 2086:         // change to last element instead of first
 2087:         var elem = document.getElementsByName(el);
 2088:         var rect = elem[0].getBoundingClientRect();
 2089: 
 2090:         return (
 2091:             rect.top >= 0 &&
 2092:             rect.left >= 0 &&
 2093:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2094:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2095:         );
 2096:     }
 2097:     
 2098:     function autosize(depth){
 2099:         var cmInst = window['cm'+depth];
 2100:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2101: 
 2102:         // is fixed size, switching to dynamic
 2103:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2104:             cmInst.setSize("","auto");
 2105:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2106:             sessionStorage.setItem("autosized_"+depth, "yes");
 2107: 
 2108:         // is dynamic size, switching to fixed
 2109:         } else {
 2110:             cmInst.setSize("","300px");
 2111:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2112:             sessionStorage.removeItem("autosized_"+depth);
 2113:         }
 2114:     }
 2115: 
 2116: $browse_or_search
 2117: 
 2118: // ]]>
 2119: </script>
 2120: COLORFULEDIT
 2121: }
 2122: 
 2123: sub xmleditor_js {
 2124:     return <<XMLEDIT
 2125: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2126: <script type="text/javascript">
 2127: // <![CDATA[>
 2128: 
 2129:     function saveScrollPosition (resource) {
 2130: 
 2131:         var scrollPos = \$(window).scrollTop();
 2132:         sessionStorage.setItem(resource,scrollPos);
 2133:     }
 2134: 
 2135:     function restoreScrollPosition(resource){
 2136: 
 2137:         var scrollPos = sessionStorage.getItem(resource);
 2138:         \$(window).scrollTop(scrollPos);
 2139:     }
 2140: 
 2141:     // unless internet explorer
 2142:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2143: 
 2144:         \$(document).ready(function() {
 2145:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2146:         });
 2147:     }
 2148: 
 2149:     // inserts text at cursor position into codemirror (xml editor only)
 2150:     function insertText(text){
 2151:         cm.focus();
 2152:         var curPos = cm.getCursor();
 2153:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2154:     }
 2155: // ]]>
 2156: </script>
 2157: XMLEDIT
 2158: }
 2159: 
 2160: sub insert_folding_button {
 2161:     my $curDepth = $Apache::lonxml::curdepth;
 2162:     my $lastresource = $env{'request.ambiguous'};
 2163: 
 2164:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2165:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2166: }
 2167: 
 2168: sub crsauthor_url {
 2169:     my ($url) = @_;
 2170:     if ($url eq '') {
 2171:         $url = $ENV{'REQUEST_URI'};
 2172:     }
 2173:     my ($cnum,$cdom);
 2174:     if ($env{'request.course.id'}) {
 2175:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2176:         if ($audom ne '' && $auname ne '') {
 2177:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2178:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2179:                 $cnum = $auname;
 2180:                 $cdom = $audom;
 2181:             }
 2182:         }
 2183:     }
 2184:     return ($cnum,$cdom);
 2185: }
 2186: 
 2187: sub import_crsauthor_form {
 2188:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2189:     return (0) unless ($env{'request.course.id'});
 2190:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2191:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2192:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2193:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2194:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2195:     my @ids=&Apache::lonnet::current_machine_ids();
 2196:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2197:     
 2198:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2199:         $is_home = 1;
 2200:     }
 2201:     $relpath = "/priv/$cdom/$cnum";
 2202:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2203:     my %lt = &Apache::lonlocal::texthash (
 2204:         fnam => 'Filename',
 2205:         dire => 'Directory',
 2206:     );
 2207:     my $numdirs = scalar(keys(%files));
 2208:     my (%possexts,$singledir,@singledirfiles);
 2209:     if ($only) {
 2210:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2211:     }
 2212:     my (%nonemptydirs,$possdirs);
 2213:     if ($numdirs > 1) {
 2214:         my @order;
 2215:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2216:             if (ref($files{$key}) eq 'HASH') {
 2217:                 my $shown = $key;
 2218:                 if ($key eq '') {
 2219:                     $shown = '/';
 2220:                 }
 2221:                 my @ordered = ();
 2222:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2223:                     if ($only) {
 2224:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2225:                         unless ($possexts{lc($ext)}) {
 2226:                             next;
 2227:                         }
 2228:                     }
 2229:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2230:                     push(@ordered,$file);
 2231:                 }
 2232:                 if (@ordered) {
 2233:                     push(@order,$key);
 2234:                     $nonemptydirs{$key} = 1;
 2235:                     $selimport_menus{$key}->{'text'} = $shown;
 2236:                     $selimport_menus{$key}->{'default'} = '';
 2237:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2238:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2239:                 }
 2240:             }
 2241:         }
 2242:         $possdirs = scalar(keys(%nonemptydirs));
 2243:         if ($possdirs > 1) {
 2244:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2245:             $output = $lt{'dire'}.
 2246:                       &linked_select_forms($form,'<br />'.
 2247:                                            $lt{'fnam'},'',
 2248:                                            $firstselectname,$secondselectname,
 2249:                                            \%selimport_menus,\@order,
 2250:                                            $onchangefirst,'',$suffix).'<br />';
 2251:         } elsif ($possdirs == 1) {
 2252:             $singledir = (keys(%nonemptydirs))[0];
 2253:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2254:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2255:             }
 2256:             delete($selimport_menus{$singledir});
 2257:         }
 2258:     } elsif ($numdirs == 1) {
 2259:         $singledir = (keys(%files))[0];
 2260:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2261:             if ($only) {
 2262:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2263:                 unless ($possexts{lc($ext)}) {
 2264:                     next;
 2265:                 }
 2266:             }
 2267:             push(@singledirfiles,$file);
 2268:         }
 2269:         if (@singledirfiles) {
 2270:             $possdirs == 1;
 2271:         }
 2272:     }
 2273:     if (($possdirs == 1) && (@singledirfiles)) {
 2274:         my $showdir = $singledir;
 2275:         if ($singledir eq '') {
 2276:             $showdir = '/';
 2277:         }
 2278:         $output = $lt{'dire'}.
 2279:                   '<select name="'.$firstselectname.'">'.
 2280:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2281:                   '</select><br />'.
 2282:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2283:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2284:         foreach my $file (@singledirfiles) {
 2285:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2286:         }
 2287:         $output .= '</select><br />'."\n";
 2288:     }
 2289:     return ($possdirs,$output);
 2290: }
 2291: 
 2292: =pod
 2293: 
 2294: =head1 Excel and CSV file utility routines
 2295: 
 2296: =cut
 2297: 
 2298: ###############################################################
 2299: ###############################################################
 2300: 
 2301: =pod
 2302: 
 2303: =over 4
 2304: 
 2305: =item * &csv_translate($text) 
 2306: 
 2307: Translate $text to allow it to be output as a 'comma separated values' 
 2308: format.
 2309: 
 2310: =cut
 2311: 
 2312: ###############################################################
 2313: ###############################################################
 2314: sub csv_translate {
 2315:     my $text = shift;
 2316:     $text =~ s/\"/\"\"/g;
 2317:     $text =~ s/\n/ /g;
 2318:     return $text;
 2319: }
 2320: 
 2321: ###############################################################
 2322: ###############################################################
 2323: 
 2324: =pod
 2325: 
 2326: =item * &define_excel_formats()
 2327: 
 2328: Define some commonly used Excel cell formats.
 2329: 
 2330: Currently supported formats:
 2331: 
 2332: =over 4
 2333: 
 2334: =item header
 2335: 
 2336: =item bold
 2337: 
 2338: =item h1
 2339: 
 2340: =item h2
 2341: 
 2342: =item h3
 2343: 
 2344: =item h4
 2345: 
 2346: =item i
 2347: 
 2348: =item date
 2349: 
 2350: =back
 2351: 
 2352: Inputs: $workbook
 2353: 
 2354: Returns: $format, a hash reference.
 2355: 
 2356: 
 2357: =cut
 2358: 
 2359: ###############################################################
 2360: ###############################################################
 2361: sub define_excel_formats {
 2362:     my ($workbook) = @_;
 2363:     my $format;
 2364:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2365:                                                 bottom    => 1,
 2366:                                                 align     => 'center');
 2367:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2368:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2369:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2370:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2371:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2372:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2373:     $format->{'date'} = $workbook->add_format(num_format=>
 2374:                                             'mm/dd/yyyy hh:mm:ss');
 2375:     return $format;
 2376: }
 2377: 
 2378: ###############################################################
 2379: ###############################################################
 2380: 
 2381: =pod
 2382: 
 2383: =item * &create_workbook()
 2384: 
 2385: Create an Excel worksheet.  If it fails, output message on the
 2386: request object and return undefs.
 2387: 
 2388: Inputs: Apache request object
 2389: 
 2390: Returns (undef) on failure, 
 2391:     Excel worksheet object, scalar with filename, and formats 
 2392:     from &Apache::loncommon::define_excel_formats on success
 2393: 
 2394: =cut
 2395: 
 2396: ###############################################################
 2397: ###############################################################
 2398: sub create_workbook {
 2399:     my ($r) = @_;
 2400:         #
 2401:     # Create the excel spreadsheet
 2402:     my $filename = '/prtspool/'.
 2403:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2404:         time.'_'.rand(1000000000).'.xls';
 2405:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2406:     if (! defined($workbook)) {
 2407:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2408:         $r->print(
 2409:             '<p class="LC_error">'
 2410:            .&mt('Problems occurred in creating the new Excel file.')
 2411:            .' '.&mt('This error has been logged.')
 2412:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2413:            .'</p>'
 2414:         );
 2415:         return (undef);
 2416:     }
 2417:     #
 2418:     $workbook->set_tempdir(LONCAPA::tempdir());
 2419:     #
 2420:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2421:     return ($workbook,$filename,$format);
 2422: }
 2423: 
 2424: ###############################################################
 2425: ###############################################################
 2426: 
 2427: =pod
 2428: 
 2429: =item * &create_text_file()
 2430: 
 2431: Create a file to write to and eventually make available to the user.
 2432: If file creation fails, outputs an error message on the request object and 
 2433: return undefs.
 2434: 
 2435: Inputs: Apache request object, and file suffix
 2436: 
 2437: Returns (undef) on failure, 
 2438:     Filehandle and filename on success.
 2439: 
 2440: =cut
 2441: 
 2442: ###############################################################
 2443: ###############################################################
 2444: sub create_text_file {
 2445:     my ($r,$suffix) = @_;
 2446:     if (! defined($suffix)) { $suffix = 'txt'; };
 2447:     my $fh;
 2448:     my $filename = '/prtspool/'.
 2449:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2450:         time.'_'.rand(1000000000).'.'.$suffix;
 2451:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2452:     if (! defined($fh)) {
 2453:         $r->log_error("Couldn't open $filename for output $!");
 2454:         $r->print(
 2455:             '<p class="LC_error">'
 2456:            .&mt('Problems occurred in creating the output file.')
 2457:            .' '.&mt('This error has been logged.')
 2458:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2459:            .'</p>'
 2460:         );
 2461:     }
 2462:     return ($fh,$filename)
 2463: }
 2464: 
 2465: 
 2466: =pod 
 2467: 
 2468: =back
 2469: 
 2470: =cut
 2471: 
 2472: ###############################################################
 2473: ##        Home server <option> list generating code          ##
 2474: ###############################################################
 2475: 
 2476: # ------------------------------------------
 2477: 
 2478: sub domain_select {
 2479:     my ($name,$value,$multiple)=@_;
 2480:     my %domains=map { 
 2481: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2482:     } &Apache::lonnet::all_domains();
 2483:     if ($multiple) {
 2484: 	$domains{''}=&mt('Any domain');
 2485: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2486: 	return &multiple_select_form($name,$value,4,\%domains);
 2487:     } else {
 2488: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2489: 	return &select_form($name,$value,\%domains);
 2490:     }
 2491: }
 2492: 
 2493: #-------------------------------------------
 2494: 
 2495: =pod
 2496: 
 2497: =head1 Routines for form select boxes
 2498: 
 2499: =over 4
 2500: 
 2501: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2502: 
 2503: Returns a string containing a <select> element int multiple mode
 2504: 
 2505: 
 2506: Args:
 2507:   $name - name of the <select> element
 2508:   $value - scalar or array ref of values that should already be selected
 2509:   $size - number of rows long the select element is
 2510:   $hash - the elements should be 'option' => 'shown text'
 2511:           (shown text should already have been &mt())
 2512:   $order - (optional) array ref of the order to show the elements in
 2513: 
 2514: =cut
 2515: 
 2516: #-------------------------------------------
 2517: sub multiple_select_form {
 2518:     my ($name,$value,$size,$hash,$order)=@_;
 2519:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2520:     my $output='';
 2521:     if (! defined($size)) {
 2522:         $size = 4;
 2523:         if (scalar(keys(%$hash))<4) {
 2524:             $size = scalar(keys(%$hash));
 2525:         }
 2526:     }
 2527:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2528:     my @order;
 2529:     if (ref($order) eq 'ARRAY')  {
 2530:         @order = @{$order};
 2531:     } else {
 2532:         @order = sort(keys(%$hash));
 2533:     }
 2534:     if (exists($$hash{'select_form_order'})) {
 2535:         @order = @{$$hash{'select_form_order'}};
 2536:     }
 2537:         
 2538:     foreach my $key (@order) {
 2539:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2540:         $output.='selected="selected" ' if ($selected{$key});
 2541:         $output.='>'.$hash->{$key}."</option>\n";
 2542:     }
 2543:     $output.="</select>\n";
 2544:     return $output;
 2545: }
 2546: 
 2547: #-------------------------------------------
 2548: 
 2549: =pod
 2550: 
 2551: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2552: 
 2553: Returns a string containing a <select name='$name' size='1'> form to 
 2554: allow a user to select options from a ref to a hash containing:
 2555: option_name => displayed text. An optional $onchange can include
 2556: a javascript onchange item, e.g., onchange="this.form.submit();".
 2557: An optional arg -- $readonly -- if true will cause the select form
 2558: to be disabled, e.g., for the case where an instructor has a section-
 2559: specific role, and is viewing/modifying parameters. 
 2560: 
 2561: See lonrights.pm for an example invocation and use.
 2562: 
 2563: =cut
 2564: 
 2565: #-------------------------------------------
 2566: sub select_form {
 2567:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2568:     return unless (ref($hashref) eq 'HASH');
 2569:     if ($onchange) {
 2570:         $onchange = ' onchange="'.$onchange.'"';
 2571:     }
 2572:     my $disabled;
 2573:     if ($readonly) {
 2574:         $disabled = ' disabled="disabled"';
 2575:     }
 2576:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2577:     my @keys;
 2578:     if (exists($hashref->{'select_form_order'})) {
 2579: 	@keys=@{$hashref->{'select_form_order'}};
 2580:     } else {
 2581: 	@keys=sort(keys(%{$hashref}));
 2582:     }
 2583:     foreach my $key (@keys) {
 2584:         $selectform.=
 2585: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2586:             ($key eq $def ? 'selected="selected" ' : '').
 2587:                 ">".$hashref->{$key}."</option>\n";
 2588:     }
 2589:     $selectform.="</select>";
 2590:     return $selectform;
 2591: }
 2592: 
 2593: # For display filters
 2594: 
 2595: sub display_filter {
 2596:     my ($context) = @_;
 2597:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2598:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2599:     my $phraseinput = 'hidden';
 2600:     my $includeinput = 'hidden';
 2601:     my ($checked,$includetypestext);
 2602:     if ($env{'form.displayfilter'} eq 'containing') {
 2603:         $phraseinput = 'text'; 
 2604:         if ($context eq 'parmslog') {
 2605:             $includeinput = 'checkbox';
 2606:             if ($env{'form.includetypes'}) {
 2607:                 $checked = ' checked="checked"';
 2608:             }
 2609:             $includetypestext = &mt('Include parameter types');
 2610:         }
 2611:     } else {
 2612:         $includetypestext = '&nbsp;';
 2613:     }
 2614:     my ($additional,$secondid,$thirdid);
 2615:     if ($context eq 'parmslog') {
 2616:         $additional = 
 2617:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2618:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2619:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2620:             '</label>';
 2621:         $secondid = 'includetypes';
 2622:         $thirdid = 'includetypestext';
 2623:     }
 2624:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2625:                                                     '$secondid','$thirdid')";
 2626:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2627: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2628: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2629: 	   '</label></span> <span class="LC_nobreak">'.
 2630:            &mt('Filter: [_1]',
 2631: 	   &select_form($env{'form.displayfilter'},
 2632: 			'displayfilter',
 2633: 			{'currentfolder' => 'Current folder/page',
 2634: 			 'containing' => 'Containing phrase',
 2635: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2636: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2637:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2638:                          '" />'.$additional;
 2639: }
 2640: 
 2641: sub display_filter_js {
 2642:     my $includetext = &mt('Include parameter types');
 2643:     return <<"ENDJS";
 2644:   
 2645: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2646:     var firstType = 'hidden';
 2647:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2648:         firstType = 'text';
 2649:     }
 2650:     firstObject = document.getElementById(firstid);
 2651:     if (typeof(firstObject) == 'object') {
 2652:         if (firstObject.type != firstType) {
 2653:             changeInputType(firstObject,firstType);
 2654:         }
 2655:     }
 2656:     if (context == 'parmslog') {
 2657:         var secondType = 'hidden';
 2658:         if (firstType == 'text') {
 2659:             secondType = 'checkbox';
 2660:         }
 2661:         secondObject = document.getElementById(secondid);  
 2662:         if (typeof(secondObject) == 'object') {
 2663:             if (secondObject.type != secondType) {
 2664:                 changeInputType(secondObject,secondType);
 2665:             }
 2666:         }
 2667:         var textItem = document.getElementById(thirdid);
 2668:         var currtext = textItem.innerHTML;
 2669:         var newtext;
 2670:         if (firstType == 'text') {
 2671:             newtext = '$includetext';
 2672:         } else {
 2673:             newtext = '&nbsp;';
 2674:         }
 2675:         if (currtext != newtext) {
 2676:             textItem.innerHTML = newtext;
 2677:         }
 2678:     }
 2679:     return;
 2680: }
 2681: 
 2682: function changeInputType(oldObject,newType) {
 2683:     var newObject = document.createElement('input');
 2684:     newObject.type = newType;
 2685:     if (oldObject.size) {
 2686:         newObject.size = oldObject.size;
 2687:     }
 2688:     if (oldObject.value) {
 2689:         newObject.value = oldObject.value;
 2690:     }
 2691:     if (oldObject.name) {
 2692:         newObject.name = oldObject.name;
 2693:     }
 2694:     if (oldObject.id) {
 2695:         newObject.id = oldObject.id;
 2696:     }
 2697:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2698:     return;
 2699: }
 2700: 
 2701: ENDJS
 2702: }
 2703: 
 2704: sub gradeleveldescription {
 2705:     my $gradelevel=shift;
 2706:     my %gradelevels=(0 => 'Not specified',
 2707: 		     1 => 'Grade 1',
 2708: 		     2 => 'Grade 2',
 2709: 		     3 => 'Grade 3',
 2710: 		     4 => 'Grade 4',
 2711: 		     5 => 'Grade 5',
 2712: 		     6 => 'Grade 6',
 2713: 		     7 => 'Grade 7',
 2714: 		     8 => 'Grade 8',
 2715: 		     9 => 'Grade 9',
 2716: 		     10 => 'Grade 10',
 2717: 		     11 => 'Grade 11',
 2718: 		     12 => 'Grade 12',
 2719: 		     13 => 'Grade 13',
 2720: 		     14 => '100 Level',
 2721: 		     15 => '200 Level',
 2722: 		     16 => '300 Level',
 2723: 		     17 => '400 Level',
 2724: 		     18 => 'Graduate Level');
 2725:     return &mt($gradelevels{$gradelevel});
 2726: }
 2727: 
 2728: sub select_level_form {
 2729:     my ($deflevel,$name)=@_;
 2730:     unless ($deflevel) { $deflevel=0; }
 2731:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2732:     for (my $i=0; $i<=18; $i++) {
 2733:         $selectform.="<option value=\"$i\" ".
 2734:             ($i==$deflevel ? 'selected="selected" ' : '').
 2735:                 ">".&gradeleveldescription($i)."</option>\n";
 2736:     }
 2737:     $selectform.="</select>";
 2738:     return $selectform;
 2739: }
 2740: 
 2741: #-------------------------------------------
 2742: 
 2743: =pod
 2744: 
 2745: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2746: 
 2747: Returns a string containing a <select name='$name' size='1'> form to 
 2748: allow a user to select the domain to preform an operation in.  
 2749: See loncreateuser.pm for an example invocation and use.
 2750: 
 2751: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2752: selected");
 2753: 
 2754: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2755: 
 2756: 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.
 2757: 
 2758: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2759: 
 2760: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2761: 
 2762: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2763: 
 2764: =cut
 2765: 
 2766: #-------------------------------------------
 2767: sub select_dom_form {
 2768:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2769:     if ($onchange) {
 2770:         $onchange = ' onchange="'.$onchange.'"';
 2771:     }
 2772:     if ($disabled) {
 2773:         $disabled = ' disabled="disabled"';
 2774:     }
 2775:     my (@domains,%exclude);
 2776:     if (ref($incdoms) eq 'ARRAY') {
 2777:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2778:     } else {
 2779:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2780:     }
 2781:     if ($includeempty) { @domains=('',@domains); }
 2782:     if (ref($excdoms) eq 'ARRAY') {
 2783:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2784:     }
 2785:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2786:     foreach my $dom (@domains) {
 2787:         next if ($exclude{$dom});
 2788:         $selectdomain.="<option value=\"$dom\" ".
 2789:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2790:         if ($showdomdesc) {
 2791:             if ($dom ne '') {
 2792:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2793:                 if ($domdesc ne '') {
 2794:                     $selectdomain .= ' ('.$domdesc.')';
 2795:                 }
 2796:             } 
 2797:         }
 2798:         $selectdomain .= "</option>\n";
 2799:     }
 2800:     $selectdomain.="</select>";
 2801:     return $selectdomain;
 2802: }
 2803: 
 2804: #-------------------------------------------
 2805: 
 2806: =pod
 2807: 
 2808: =item * &home_server_form_item($domain,$name,$defaultflag)
 2809: 
 2810: input: 4 arguments (two required, two optional) - 
 2811:     $domain - domain of new user
 2812:     $name - name of form element
 2813:     $default - Value of 'default' causes a default item to be first 
 2814:                             option, and selected by default. 
 2815:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2816:                             if 1 server found, or default, if 0 found.
 2817: output: returns 2 items: 
 2818: (a) form element which contains either:
 2819:    (i) <select name="$name">
 2820:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2821:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2822:        </select>
 2823:        form item if there are multiple library servers in $domain, or
 2824:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2825:        if there is only one library server in $domain.
 2826: 
 2827: (b) number of library servers found.
 2828: 
 2829: See loncreateuser.pm for example of use.
 2830: 
 2831: =cut
 2832: 
 2833: #-------------------------------------------
 2834: sub home_server_form_item {
 2835:     my ($domain,$name,$default,$hide) = @_;
 2836:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2837:     my $result;
 2838:     my $numlib = keys(%servers);
 2839:     if ($numlib > 1) {
 2840:         $result .= '<select name="'.$name.'" />'."\n";
 2841:         if ($default) {
 2842:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2843:                        '</option>'."\n";
 2844:         }
 2845:         foreach my $hostid (sort(keys(%servers))) {
 2846:             $result.= '<option value="'.$hostid.'">'.
 2847: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2848:         }
 2849:         $result .= '</select>'."\n";
 2850:     } elsif ($numlib == 1) {
 2851:         my $hostid;
 2852:         foreach my $item (keys(%servers)) {
 2853:             $hostid = $item;
 2854:         }
 2855:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2856:                    $hostid.'" />';
 2857:                    if (!$hide) {
 2858:                        $result .= $hostid.' '.$servers{$hostid};
 2859:                    }
 2860:                    $result .= "\n";
 2861:     } elsif ($default) {
 2862:         $result .= '<input type="hidden" name="'.$name.
 2863:                    '" value="default" />';
 2864:                    if (!$hide) {
 2865:                        $result .= &mt('default');
 2866:                    }
 2867:                    $result .= "\n";
 2868:     }
 2869:     return ($result,$numlib);
 2870: }
 2871: 
 2872: =pod
 2873: 
 2874: =back 
 2875: 
 2876: =cut
 2877: 
 2878: ###############################################################
 2879: ##                  Decoding User Agent                      ##
 2880: ###############################################################
 2881: 
 2882: =pod
 2883: 
 2884: =head1 Decoding the User Agent
 2885: 
 2886: =over 4
 2887: 
 2888: =item * &decode_user_agent()
 2889: 
 2890: Inputs: $r
 2891: 
 2892: Outputs:
 2893: 
 2894: =over 4
 2895: 
 2896: =item * $httpbrowser
 2897: 
 2898: =item * $clientbrowser
 2899: 
 2900: =item * $clientversion
 2901: 
 2902: =item * $clientmathml
 2903: 
 2904: =item * $clientunicode
 2905: 
 2906: =item * $clientos
 2907: 
 2908: =item * $clientmobile
 2909: 
 2910: =item * $clientinfo
 2911: 
 2912: =item * $clientosversion
 2913: 
 2914: =back
 2915: 
 2916: =back 
 2917: 
 2918: =cut
 2919: 
 2920: ###############################################################
 2921: ###############################################################
 2922: sub decode_user_agent {
 2923:     my ($r)=@_;
 2924:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2925:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2926:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2927:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2928:     my $clientbrowser='unknown';
 2929:     my $clientversion='0';
 2930:     my $clientmathml='';
 2931:     my $clientunicode='0';
 2932:     my $clientmobile=0;
 2933:     my $clientosversion='';
 2934:     for (my $i=0;$i<=$#browsertype;$i++) {
 2935:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2936: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2937: 	    $clientbrowser=$bname;
 2938:             $httpbrowser=~/$vreg/i;
 2939: 	    $clientversion=$1;
 2940:             $clientmathml=($clientversion>=$minv);
 2941:             $clientunicode=($clientversion>=$univ);
 2942: 	}
 2943:     }
 2944:     my $clientos='unknown';
 2945:     my $clientinfo;
 2946:     if (($httpbrowser=~/linux/i) ||
 2947:         ($httpbrowser=~/unix/i) ||
 2948:         ($httpbrowser=~/ux/i) ||
 2949:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2950:     if (($httpbrowser=~/vax/i) ||
 2951:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2952:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2953:     if (($httpbrowser=~/mac/i) ||
 2954:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2955:     if ($httpbrowser=~/win/i) {
 2956:         $clientos='win';
 2957:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2958:             $clientosversion = $1;
 2959:         }
 2960:     }
 2961:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2962:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2963:         $clientmobile=lc($1);
 2964:     }
 2965:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2966:         $clientinfo = 'firefox-'.$1;
 2967:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2968:         $clientinfo = 'chromeframe-'.$1;
 2969:     }
 2970:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2971:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2972:             $clientosversion);
 2973: }
 2974: 
 2975: ###############################################################
 2976: ##    Authentication changing form generation subroutines    ##
 2977: ###############################################################
 2978: ##
 2979: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2980: ## hash, and have reasonable default values.
 2981: ##
 2982: ##    formname = the name given in the <form> tag.
 2983: #-------------------------------------------
 2984: 
 2985: =pod
 2986: 
 2987: =head1 Authentication Routines
 2988: 
 2989: =over 4
 2990: 
 2991: =item * &authform_xxxxxx()
 2992: 
 2993: The authform_xxxxxx subroutines provide javascript and html forms which 
 2994: handle some of the conveniences required for authentication forms.  
 2995: This is not an optimal method, but it works.  
 2996: 
 2997: =over 4
 2998: 
 2999: =item * authform_header
 3000: 
 3001: =item * authform_authorwarning
 3002: 
 3003: =item * authform_nochange
 3004: 
 3005: =item * authform_kerberos
 3006: 
 3007: =item * authform_internal
 3008: 
 3009: =item * authform_filesystem
 3010: 
 3011: =back
 3012: 
 3013: See loncreateuser.pm for invocation and use examples.
 3014: 
 3015: =cut
 3016: 
 3017: #-------------------------------------------
 3018: sub authform_header{  
 3019:     my %in = (
 3020:         formname => 'cu',
 3021:         kerb_def_dom => '',
 3022:         @_,
 3023:     );
 3024:     $in{'formname'} = 'document.' . $in{'formname'};
 3025:     my $result='';
 3026: 
 3027: #---------------------------------------------- Code for upper case translation
 3028:     my $Javascript_toUpperCase;
 3029:     unless ($in{kerb_def_dom}) {
 3030:         $Javascript_toUpperCase =<<"END";
 3031:         switch (choice) {
 3032:            case 'krb': currentform.elements[choicearg].value =
 3033:                currentform.elements[choicearg].value.toUpperCase();
 3034:                break;
 3035:            default:
 3036:         }
 3037: END
 3038:     } else {
 3039:         $Javascript_toUpperCase = "";
 3040:     }
 3041: 
 3042:     my $radioval = "'nochange'";
 3043:     if (defined($in{'curr_authtype'})) {
 3044:         if ($in{'curr_authtype'} ne '') {
 3045:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3046:         }
 3047:     }
 3048:     my $argfield = 'null';
 3049:     if (defined($in{'mode'})) {
 3050:         if ($in{'mode'} eq 'modifycourse')  {
 3051:             if (defined($in{'curr_autharg'})) {
 3052:                 if ($in{'curr_autharg'} ne '') {
 3053:                     $argfield = "'$in{'curr_autharg'}'";
 3054:                 }
 3055:             }
 3056:         }
 3057:     }
 3058: 
 3059:     $result.=<<"END";
 3060: var current = new Object();
 3061: current.radiovalue = $radioval;
 3062: current.argfield = $argfield;
 3063: 
 3064: function changed_radio(choice,currentform) {
 3065:     var choicearg = choice + 'arg';
 3066:     // If a radio button in changed, we need to change the argfield
 3067:     if (current.radiovalue != choice) {
 3068:         current.radiovalue = choice;
 3069:         if (current.argfield != null) {
 3070:             currentform.elements[current.argfield].value = '';
 3071:         }
 3072:         if (choice == 'nochange') {
 3073:             current.argfield = null;
 3074:         } else {
 3075:             current.argfield = choicearg;
 3076:             switch(choice) {
 3077:                 case 'krb': 
 3078:                     currentform.elements[current.argfield].value = 
 3079:                         "$in{'kerb_def_dom'}";
 3080:                 break;
 3081:               default:
 3082:                 break;
 3083:             }
 3084:         }
 3085:     }
 3086:     return;
 3087: }
 3088: 
 3089: function changed_text(choice,currentform) {
 3090:     var choicearg = choice + 'arg';
 3091:     if (currentform.elements[choicearg].value !='') {
 3092:         $Javascript_toUpperCase
 3093:         // clear old field
 3094:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3095:             currentform.elements[current.argfield].value = '';
 3096:         }
 3097:         current.argfield = choicearg;
 3098:     }
 3099:     set_auth_radio_buttons(choice,currentform);
 3100:     return;
 3101: }
 3102: 
 3103: function set_auth_radio_buttons(newvalue,currentform) {
 3104:     var numauthchoices = currentform.login.length;
 3105:     if (typeof numauthchoices  == "undefined") {
 3106:         return;
 3107:     } 
 3108:     var i=0;
 3109:     while (i < numauthchoices) {
 3110:         if (currentform.login[i].value == newvalue) { break; }
 3111:         i++;
 3112:     }
 3113:     if (i == numauthchoices) {
 3114:         return;
 3115:     }
 3116:     current.radiovalue = newvalue;
 3117:     currentform.login[i].checked = true;
 3118:     return;
 3119: }
 3120: END
 3121:     return $result;
 3122: }
 3123: 
 3124: sub authform_authorwarning {
 3125:     my $result='';
 3126:     $result='<i>'.
 3127:         &mt('As a general rule, only authors or co-authors should be '.
 3128:             'filesystem authenticated '.
 3129:             '(which allows access to the server filesystem).')."</i>\n";
 3130:     return $result;
 3131: }
 3132: 
 3133: sub authform_nochange {
 3134:     my %in = (
 3135:               formname => 'document.cu',
 3136:               kerb_def_dom => 'MSU.EDU',
 3137:               @_,
 3138:           );
 3139:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3140:     my $result;
 3141:     if (!$authnum) {
 3142:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3143:     } else {
 3144:         $result = '<label>'.&mt('[_1] Do not change login data',
 3145:                   '<input type="radio" name="login" value="nochange" '.
 3146:                   'checked="checked" onclick="'.
 3147:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3148: 	    '</label>';
 3149:     }
 3150:     return $result;
 3151: }
 3152: 
 3153: sub authform_kerberos {
 3154:     my %in = (
 3155:               formname => 'document.cu',
 3156:               kerb_def_dom => 'MSU.EDU',
 3157:               kerb_def_auth => 'krb4',
 3158:               @_,
 3159:               );
 3160:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3161:         $autharg,$jscall,$disabled);
 3162:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3163:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3164:        $check5 = ' checked="checked"';
 3165:     } else {
 3166:        $check4 = ' checked="checked"';
 3167:     }
 3168:     if ($in{'readonly'}) {
 3169:         $disabled = ' disabled="disabled"';
 3170:     }
 3171:     $krbarg = $in{'kerb_def_dom'};
 3172:     if (defined($in{'curr_authtype'})) {
 3173:         if ($in{'curr_authtype'} eq 'krb') {
 3174:             $krbcheck = ' checked="checked"';
 3175:             if (defined($in{'mode'})) {
 3176:                 if ($in{'mode'} eq 'modifyuser') {
 3177:                     $krbcheck = '';
 3178:                 }
 3179:             }
 3180:             if (defined($in{'curr_kerb_ver'})) {
 3181:                 if ($in{'curr_krb_ver'} eq '5') {
 3182:                     $check5 = ' checked="checked"';
 3183:                     $check4 = '';
 3184:                 } else {
 3185:                     $check4 = ' checked="checked"';
 3186:                     $check5 = '';
 3187:                 }
 3188:             }
 3189:             if (defined($in{'curr_autharg'})) {
 3190:                 $krbarg = $in{'curr_autharg'};
 3191:             }
 3192:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3193:                 if (defined($in{'curr_autharg'})) {
 3194:                     $result = 
 3195:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3196:         $in{'curr_autharg'},$krbver);
 3197:                 } else {
 3198:                     $result =
 3199:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3200:                 }
 3201:                 return $result; 
 3202:             }
 3203:         }
 3204:     } else {
 3205:         if ($authnum == 1) {
 3206:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3207:         }
 3208:     }
 3209:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3210:         return;
 3211:     } elsif ($authtype eq '') {
 3212:         if (defined($in{'mode'})) {
 3213:             if ($in{'mode'} eq 'modifycourse') {
 3214:                 if ($authnum == 1) {
 3215:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3216:                 }
 3217:             }
 3218:         }
 3219:     }
 3220:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3221:     if ($authtype eq '') {
 3222:         $authtype = '<input type="radio" name="login" value="krb" '.
 3223:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3224:                     $krbcheck.$disabled.' />';
 3225:     }
 3226:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3227:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3228:          $in{'curr_authtype'} eq 'krb5') ||
 3229:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3230:          $in{'curr_authtype'} eq 'krb4')) {
 3231:         $result .= &mt
 3232:         ('[_1] Kerberos authenticated with domain [_2] '.
 3233:          '[_3] Version 4 [_4] Version 5 [_5]',
 3234:          '<label>'.$authtype,
 3235:          '</label><input type="text" size="10" name="krbarg" '.
 3236:              'value="'.$krbarg.'" '.
 3237:              'onchange="'.$jscall.'"'.$disabled.' />',
 3238:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3239:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3240: 	 '</label>');
 3241:     } elsif ($can_assign{'krb4'}) {
 3242:         $result .= &mt
 3243:         ('[_1] Kerberos authenticated with domain [_2] '.
 3244:          '[_3] Version 4 [_4]',
 3245:          '<label>'.$authtype,
 3246:          '</label><input type="text" size="10" name="krbarg" '.
 3247:              'value="'.$krbarg.'" '.
 3248:              'onchange="'.$jscall.'"'.$disabled.' />',
 3249:          '<label><input type="hidden" name="krbver" value="4" />',
 3250:          '</label>');
 3251:     } elsif ($can_assign{'krb5'}) {
 3252:         $result .= &mt
 3253:         ('[_1] Kerberos authenticated with domain [_2] '.
 3254:          '[_3] Version 5 [_4]',
 3255:          '<label>'.$authtype,
 3256:          '</label><input type="text" size="10" name="krbarg" '.
 3257:              'value="'.$krbarg.'" '.
 3258:              'onchange="'.$jscall.'"'.$disabled.' />',
 3259:          '<label><input type="hidden" name="krbver" value="5" />',
 3260:          '</label>');
 3261:     }
 3262:     return $result;
 3263: }
 3264: 
 3265: sub authform_internal {
 3266:     my %in = (
 3267:                 formname => 'document.cu',
 3268:                 kerb_def_dom => 'MSU.EDU',
 3269:                 @_,
 3270:                 );
 3271:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3272:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3273:     if ($in{'readonly'}) {
 3274:         $disabled = ' disabled="disabled"';
 3275:     }
 3276:     if (defined($in{'curr_authtype'})) {
 3277:         if ($in{'curr_authtype'} eq 'int') {
 3278:             if ($can_assign{'int'}) {
 3279:                 $intcheck = 'checked="checked" ';
 3280:                 if (defined($in{'mode'})) {
 3281:                     if ($in{'mode'} eq 'modifyuser') {
 3282:                         $intcheck = '';
 3283:                     }
 3284:                 }
 3285:                 if (defined($in{'curr_autharg'})) {
 3286:                     $intarg = $in{'curr_autharg'};
 3287:                 }
 3288:             } else {
 3289:                 $result = &mt('Currently internally authenticated.');
 3290:                 return $result;
 3291:             }
 3292:         }
 3293:     } else {
 3294:         if ($authnum == 1) {
 3295:             $authtype = '<input type="hidden" name="login" value="int" />';
 3296:         }
 3297:     }
 3298:     if (!$can_assign{'int'}) {
 3299:         return;
 3300:     } elsif ($authtype eq '') {
 3301:         if (defined($in{'mode'})) {
 3302:             if ($in{'mode'} eq 'modifycourse') {
 3303:                 if ($authnum == 1) {
 3304:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3305:                 }
 3306:             }
 3307:         }
 3308:     }
 3309:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3310:     if ($authtype eq '') {
 3311:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3312:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3313:     }
 3314:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3315:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3316:     $result = &mt
 3317:         ('[_1] Internally authenticated (with initial password [_2])',
 3318:          '<label>'.$authtype,'</label>'.$autharg);
 3319:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
 3320:     return $result;
 3321: }
 3322: 
 3323: sub authform_local {
 3324:     my %in = (
 3325:               formname => 'document.cu',
 3326:               kerb_def_dom => 'MSU.EDU',
 3327:               @_,
 3328:               );
 3329:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3330:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3331:     if ($in{'readonly'}) {
 3332:         $disabled = ' disabled="disabled"';
 3333:     } 
 3334:     if (defined($in{'curr_authtype'})) {
 3335:         if ($in{'curr_authtype'} eq 'loc') {
 3336:             if ($can_assign{'loc'}) {
 3337:                 $loccheck = 'checked="checked" ';
 3338:                 if (defined($in{'mode'})) {
 3339:                     if ($in{'mode'} eq 'modifyuser') {
 3340:                         $loccheck = '';
 3341:                     }
 3342:                 }
 3343:                 if (defined($in{'curr_autharg'})) {
 3344:                     $locarg = $in{'curr_autharg'};
 3345:                 }
 3346:             } else {
 3347:                 $result = &mt('Currently using local (institutional) authentication.');
 3348:                 return $result;
 3349:             }
 3350:         }
 3351:     } else {
 3352:         if ($authnum == 1) {
 3353:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3354:         }
 3355:     }
 3356:     if (!$can_assign{'loc'}) {
 3357:         return;
 3358:     } elsif ($authtype eq '') {
 3359:         if (defined($in{'mode'})) {
 3360:             if ($in{'mode'} eq 'modifycourse') {
 3361:                 if ($authnum == 1) {
 3362:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3363:                 }
 3364:             }
 3365:         }
 3366:     }
 3367:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3368:     if ($authtype eq '') {
 3369:         $authtype = '<input type="radio" name="login" value="loc" '.
 3370:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3371:                     $jscall.'"'.$disabled.' />';
 3372:     }
 3373:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3374:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3375:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3376:                   '<label>'.$authtype,'</label>'.$autharg);
 3377:     return $result;
 3378: }
 3379: 
 3380: sub authform_filesystem {
 3381:     my %in = (
 3382:               formname => 'document.cu',
 3383:               kerb_def_dom => 'MSU.EDU',
 3384:               @_,
 3385:               );
 3386:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3387:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3388:     if ($in{'readonly'}) {
 3389:         $disabled = ' disabled="disabled"';
 3390:     }
 3391:     if (defined($in{'curr_authtype'})) {
 3392:         if ($in{'curr_authtype'} eq 'fsys') {
 3393:             if ($can_assign{'fsys'}) {
 3394:                 $fsyscheck = 'checked="checked" ';
 3395:                 if (defined($in{'mode'})) {
 3396:                     if ($in{'mode'} eq 'modifyuser') {
 3397:                         $fsyscheck = '';
 3398:                     }
 3399:                 }
 3400:             } else {
 3401:                 $result = &mt('Currently Filesystem Authenticated.');
 3402:                 return $result;
 3403:             }
 3404:         }
 3405:     } else {
 3406:         if ($authnum == 1) {
 3407:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3408:         }
 3409:     }
 3410:     if (!$can_assign{'fsys'}) {
 3411:         return;
 3412:     } elsif ($authtype eq '') {
 3413:         if (defined($in{'mode'})) {
 3414:             if ($in{'mode'} eq 'modifycourse') {
 3415:                 if ($authnum == 1) {
 3416:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3417:                 }
 3418:             }
 3419:         }
 3420:     }
 3421:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3422:     if ($authtype eq '') {
 3423:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3424:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3425:                     $jscall.'"'.$disabled.' />';
 3426:     }
 3427:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3428:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3429:     $result = &mt
 3430:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3431:          '<label><input type="radio" name="login" value="fsys" '.
 3432:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3433:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3434:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3435:     return $result;
 3436: }
 3437: 
 3438: sub get_assignable_auth {
 3439:     my ($dom) = @_;
 3440:     if ($dom eq '') {
 3441:         $dom = $env{'request.role.domain'};
 3442:     }
 3443:     my %can_assign = (
 3444:                           krb4 => 1,
 3445:                           krb5 => 1,
 3446:                           int  => 1,
 3447:                           loc  => 1,
 3448:                      );
 3449:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3450:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3451:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3452:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3453:             my $context;
 3454:             if ($env{'request.role'} =~ /^au/) {
 3455:                 $context = 'author';
 3456:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3457:                 $context = 'domain';
 3458:             } elsif ($env{'request.course.id'}) {
 3459:                 $context = 'course';
 3460:             }
 3461:             if ($context) {
 3462:                 if (ref($authhash->{$context}) eq 'HASH') {
 3463:                    %can_assign = %{$authhash->{$context}}; 
 3464:                 }
 3465:             }
 3466:         }
 3467:     }
 3468:     my $authnum = 0;
 3469:     foreach my $key (keys(%can_assign)) {
 3470:         if ($can_assign{$key}) {
 3471:             $authnum ++;
 3472:         }
 3473:     }
 3474:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3475:         $authnum --;
 3476:     }
 3477:     return ($authnum,%can_assign);
 3478: }
 3479: 
 3480: ###############################################################
 3481: ##    Get Kerberos Defaults for Domain                 ##
 3482: ###############################################################
 3483: ##
 3484: ## Returns default kerberos version and an associated argument
 3485: ## as listed in file domain.tab. If not listed, provides
 3486: ## appropriate default domain and kerberos version.
 3487: ##
 3488: #-------------------------------------------
 3489: 
 3490: =pod
 3491: 
 3492: =item * &get_kerberos_defaults()
 3493: 
 3494: get_kerberos_defaults($target_domain) returns the default kerberos
 3495: version and domain. If not found, it defaults to version 4 and the 
 3496: domain of the server.
 3497: 
 3498: =over 4
 3499: 
 3500: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3501: 
 3502: =back
 3503: 
 3504: =back
 3505: 
 3506: =cut
 3507: 
 3508: #-------------------------------------------
 3509: sub get_kerberos_defaults {
 3510:     my $domain=shift;
 3511:     my ($krbdef,$krbdefdom);
 3512:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3513:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3514:         $krbdef = $domdefaults{'auth_def'};
 3515:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3516:     } else {
 3517:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3518:         my $krbdefdom=$1;
 3519:         $krbdefdom=~tr/a-z/A-Z/;
 3520:         $krbdef = "krb4";
 3521:     }
 3522:     return ($krbdef,$krbdefdom);
 3523: }
 3524: 
 3525: 
 3526: ###############################################################
 3527: ##                Thesaurus Functions                        ##
 3528: ###############################################################
 3529: 
 3530: =pod
 3531: 
 3532: =head1 Thesaurus Functions
 3533: 
 3534: =over 4
 3535: 
 3536: =item * &initialize_keywords()
 3537: 
 3538: Initializes the package variable %Keywords if it is empty.  Uses the
 3539: package variable $thesaurus_db_file.
 3540: 
 3541: =cut
 3542: 
 3543: ###################################################
 3544: 
 3545: sub initialize_keywords {
 3546:     return 1 if (scalar keys(%Keywords));
 3547:     # If we are here, %Keywords is empty, so fill it up
 3548:     #   Make sure the file we need exists...
 3549:     if (! -e $thesaurus_db_file) {
 3550:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3551:                                  " failed because it does not exist");
 3552:         return 0;
 3553:     }
 3554:     #   Set up the hash as a database
 3555:     my %thesaurus_db;
 3556:     if (! tie(%thesaurus_db,'GDBM_File',
 3557:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3558:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3559:                                  $thesaurus_db_file);
 3560:         return 0;
 3561:     } 
 3562:     #  Get the average number of appearances of a word.
 3563:     my $avecount = $thesaurus_db{'average.count'};
 3564:     #  Put keywords (those that appear > average) into %Keywords
 3565:     while (my ($word,$data)=each (%thesaurus_db)) {
 3566:         my ($count,undef) = split /:/,$data;
 3567:         $Keywords{$word}++ if ($count > $avecount);
 3568:     }
 3569:     untie %thesaurus_db;
 3570:     # Remove special values from %Keywords.
 3571:     foreach my $value ('total.count','average.count') {
 3572:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3573:   }
 3574:     return 1;
 3575: }
 3576: 
 3577: ###################################################
 3578: 
 3579: =pod
 3580: 
 3581: =item * &keyword($word)
 3582: 
 3583: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3584: than the average number of times in the thesaurus database.  Calls 
 3585: &initialize_keywords
 3586: 
 3587: =cut
 3588: 
 3589: ###################################################
 3590: 
 3591: sub keyword {
 3592:     return if (!&initialize_keywords());
 3593:     my $word=lc(shift());
 3594:     $word=~s/\W//g;
 3595:     return exists($Keywords{$word});
 3596: }
 3597: 
 3598: ###############################################################
 3599: 
 3600: =pod 
 3601: 
 3602: =item * &get_related_words()
 3603: 
 3604: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3605: an array of words.  If the keyword is not in the thesaurus, an empty array
 3606: will be returned.  The order of the words returned is determined by the
 3607: database which holds them.
 3608: 
 3609: Uses global $thesaurus_db_file.
 3610: 
 3611: 
 3612: =cut
 3613: 
 3614: ###############################################################
 3615: sub get_related_words {
 3616:     my $keyword = shift;
 3617:     my %thesaurus_db;
 3618:     if (! -e $thesaurus_db_file) {
 3619:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3620:                                  "failed because the file does not exist");
 3621:         return ();
 3622:     }
 3623:     if (! tie(%thesaurus_db,'GDBM_File',
 3624:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3625:         return ();
 3626:     } 
 3627:     my @Words=();
 3628:     my $count=0;
 3629:     if (exists($thesaurus_db{$keyword})) {
 3630: 	# The first element is the number of times
 3631: 	# the word appears.  We do not need it now.
 3632: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3633: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3634: 	my $threshold=$mostfrequentcount/10;
 3635:         foreach my $possibleword (@RelatedWords) {
 3636:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3637:             if ($wordcount>$threshold) {
 3638: 		push(@Words,$word);
 3639:                 $count++;
 3640:                 if ($count>10) { last; }
 3641: 	    }
 3642:         }
 3643:     }
 3644:     untie %thesaurus_db;
 3645:     return @Words;
 3646: }
 3647: ###############################################################
 3648: #
 3649: #  Spell checking
 3650: #
 3651: 
 3652: =pod
 3653: 
 3654: =back
 3655: 
 3656: =head1 Spell checking
 3657: 
 3658: =over 4
 3659: 
 3660: =item * &check_spelling($wordlist $language)
 3661: 
 3662: Takes a string containing words and feeds it to an external
 3663: spellcheck program via a pipeline. Returns a string containing
 3664: them mis-spelled words.
 3665: 
 3666: Parameters:
 3667: 
 3668: =over 4
 3669: 
 3670: =item - $wordlist
 3671: 
 3672: String that will be fed into the spellcheck program.
 3673: 
 3674: =item - $language
 3675: 
 3676: Language string that specifies the language for which the spell
 3677: check will be performed.
 3678: 
 3679: =back
 3680: 
 3681: =back
 3682: 
 3683: Note: This sub assumes that aspell is installed.
 3684: 
 3685: 
 3686: =cut
 3687: 
 3688: 
 3689: sub check_spelling {
 3690:     my ($wordlist, $language) = @_;
 3691:     my @misspellings;
 3692:     
 3693:     # Generate the speller and set the langauge.
 3694:     # if explicitly selected:
 3695: 
 3696:     my $speller = Text::Aspell->new;
 3697:     if ($language) {
 3698: 	$speller->set_option('lang', $language);
 3699:     }
 3700: 
 3701:     # Turn the word list into an array of words by splittingon whitespace
 3702: 
 3703:     my @words = split(/\s+/, $wordlist);
 3704: 
 3705:     foreach my $word (@words) {
 3706: 	if(! $speller->check($word)) {
 3707: 	    push(@misspellings, $word);
 3708: 	}
 3709:     }
 3710:     return join(' ', @misspellings);
 3711:     
 3712: }
 3713: 
 3714: # -------------------------------------------------------------- Plaintext name
 3715: =pod
 3716: 
 3717: =head1 User Name Functions
 3718: 
 3719: =over 4
 3720: 
 3721: =item * &plainname($uname,$udom,$first)
 3722: 
 3723: Takes a users logon name and returns it as a string in
 3724: "first middle last generation" form 
 3725: if $first is set to 'lastname' then it returns it as
 3726: 'lastname generation, firstname middlename' if their is a lastname
 3727: 
 3728: =cut
 3729: 
 3730: 
 3731: ###############################################################
 3732: sub plainname {
 3733:     my ($uname,$udom,$first)=@_;
 3734:     return if (!defined($uname) || !defined($udom));
 3735:     my %names=&getnames($uname,$udom);
 3736:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3737: 					  $names{'middlename'},
 3738: 					  $names{'lastname'},
 3739: 					  $names{'generation'},$first);
 3740:     $name=~s/^\s+//;
 3741:     $name=~s/\s+$//;
 3742:     $name=~s/\s+/ /g;
 3743:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3744:     return $name;
 3745: }
 3746: 
 3747: # -------------------------------------------------------------------- Nickname
 3748: =pod
 3749: 
 3750: =item * &nickname($uname,$udom)
 3751: 
 3752: Gets a users name and returns it as a string as
 3753: 
 3754: "&quot;nickname&quot;"
 3755: 
 3756: if the user has a nickname or
 3757: 
 3758: "first middle last generation"
 3759: 
 3760: if the user does not
 3761: 
 3762: =cut
 3763: 
 3764: sub nickname {
 3765:     my ($uname,$udom)=@_;
 3766:     return if (!defined($uname) || !defined($udom));
 3767:     my %names=&getnames($uname,$udom);
 3768:     my $name=$names{'nickname'};
 3769:     if ($name) {
 3770:        $name='&quot;'.$name.'&quot;'; 
 3771:     } else {
 3772:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3773: 	     $names{'lastname'}.' '.$names{'generation'};
 3774:        $name=~s/\s+$//;
 3775:        $name=~s/\s+/ /g;
 3776:     }
 3777:     return $name;
 3778: }
 3779: 
 3780: sub getnames {
 3781:     my ($uname,$udom)=@_;
 3782:     return if (!defined($uname) || !defined($udom));
 3783:     if ($udom eq 'public' && $uname eq 'public') {
 3784: 	return ('lastname' => &mt('Public'));
 3785:     }
 3786:     my $id=$uname.':'.$udom;
 3787:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3788:     if ($cached) {
 3789: 	return %{$names};
 3790:     } else {
 3791: 	my %loadnames=&Apache::lonnet::get('environment',
 3792:                     ['firstname','middlename','lastname','generation','nickname'],
 3793: 					 $udom,$uname);
 3794: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3795: 	return %loadnames;
 3796:     }
 3797: }
 3798: 
 3799: # -------------------------------------------------------------------- getemails
 3800: 
 3801: =pod
 3802: 
 3803: =item * &getemails($uname,$udom)
 3804: 
 3805: Gets a user's email information and returns it as a hash with keys:
 3806: notification, critnotification, permanentemail
 3807: 
 3808: For notification and critnotification, values are comma-separated lists 
 3809: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3810:  
 3811: 
 3812: =cut
 3813: 
 3814: 
 3815: sub getemails {
 3816:     my ($uname,$udom)=@_;
 3817:     if ($udom eq 'public' && $uname eq 'public') {
 3818: 	return;
 3819:     }
 3820:     if (!$udom) { $udom=$env{'user.domain'}; }
 3821:     if (!$uname) { $uname=$env{'user.name'}; }
 3822:     my $id=$uname.':'.$udom;
 3823:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3824:     if ($cached) {
 3825: 	return %{$names};
 3826:     } else {
 3827: 	my %loadnames=&Apache::lonnet::get('environment',
 3828:                     			   ['notification','critnotification',
 3829: 					    'permanentemail'],
 3830: 					   $udom,$uname);
 3831: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3832: 	return %loadnames;
 3833:     }
 3834: }
 3835: 
 3836: sub flush_email_cache {
 3837:     my ($uname,$udom)=@_;
 3838:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3839:     if (!$uname) { $uname=$env{'user.name'};   }
 3840:     return if ($udom eq 'public' && $uname eq 'public');
 3841:     my $id=$uname.':'.$udom;
 3842:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3843: }
 3844: 
 3845: # -------------------------------------------------------------------- getlangs
 3846: 
 3847: =pod
 3848: 
 3849: =item * &getlangs($uname,$udom)
 3850: 
 3851: Gets a user's language preference and returns it as a hash with key:
 3852: language.
 3853: 
 3854: =cut
 3855: 
 3856: 
 3857: sub getlangs {
 3858:     my ($uname,$udom) = @_;
 3859:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3860:     if (!$uname) { $uname=$env{'user.name'};   }
 3861:     my $id=$uname.':'.$udom;
 3862:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3863:     if ($cached) {
 3864:         return %{$langs};
 3865:     } else {
 3866:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3867:                                            $udom,$uname);
 3868:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3869:         return %loadlangs;
 3870:     }
 3871: }
 3872: 
 3873: sub flush_langs_cache {
 3874:     my ($uname,$udom)=@_;
 3875:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3876:     if (!$uname) { $uname=$env{'user.name'};   }
 3877:     return if ($udom eq 'public' && $uname eq 'public');
 3878:     my $id=$uname.':'.$udom;
 3879:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3880: }
 3881: 
 3882: # ------------------------------------------------------------------ Screenname
 3883: 
 3884: =pod
 3885: 
 3886: =item * &screenname($uname,$udom)
 3887: 
 3888: Gets a users screenname and returns it as a string
 3889: 
 3890: =cut
 3891: 
 3892: sub screenname {
 3893:     my ($uname,$udom)=@_;
 3894:     if ($uname eq $env{'user.name'} &&
 3895: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3896:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3897:     return $names{'screenname'};
 3898: }
 3899: 
 3900: 
 3901: # ------------------------------------------------------------- Confirm Wrapper
 3902: =pod
 3903: 
 3904: =item * &confirmwrapper($message)
 3905: 
 3906: Wrap messages about completion of operation in box
 3907: 
 3908: =cut
 3909: 
 3910: sub confirmwrapper {
 3911:     my ($message)=@_;
 3912:     if ($message) {
 3913:         return "\n".'<div class="LC_confirm_box">'."\n"
 3914:                .$message."\n"
 3915:                .'</div>'."\n";
 3916:     } else {
 3917:         return $message;
 3918:     }
 3919: }
 3920: 
 3921: # ------------------------------------------------------------- Message Wrapper
 3922: 
 3923: sub messagewrapper {
 3924:     my ($link,$username,$domain,$subject,$text)=@_;
 3925:     return 
 3926:         '<a href="/adm/email?compose=individual&amp;'.
 3927:         'recname='.$username.'&amp;recdom='.$domain.
 3928: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3929:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3930: }
 3931: 
 3932: # --------------------------------------------------------------- Notes Wrapper
 3933: 
 3934: sub noteswrapper {
 3935:     my ($link,$un,$do)=@_;
 3936:     return 
 3937: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3938: }
 3939: 
 3940: # ------------------------------------------------------------- Aboutme Wrapper
 3941: 
 3942: sub aboutmewrapper {
 3943:     my ($link,$username,$domain,$target,$class)=@_;
 3944:     if (!defined($username)  && !defined($domain)) {
 3945:         return;
 3946:     }
 3947:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3948: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3949: }
 3950: 
 3951: # ------------------------------------------------------------ Syllabus Wrapper
 3952: 
 3953: sub syllabuswrapper {
 3954:     my ($linktext,$coursedir,$domain)=@_;
 3955:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3956: }
 3957: 
 3958: # -----------------------------------------------------------------------------
 3959: 
 3960: sub track_student_link {
 3961:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3962:     my $link ="/adm/trackstudent?";
 3963:     my $title = 'View recent activity';
 3964:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3965:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3966:         $link .= "selected_student=$sname:$sdom";
 3967:         $title .= ' of this student';
 3968:     } 
 3969:     if (defined($target) && $target !~ /^\s*$/) {
 3970:         $target = qq{target="$target"};
 3971:     } else {
 3972:         $target = '';
 3973:     }
 3974:     if ($start) { $link.='&amp;start='.$start; }
 3975:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3976:     $title = &mt($title);
 3977:     $linktext = &mt($linktext);
 3978:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3979: 	&help_open_topic('View_recent_activity');
 3980: }
 3981: 
 3982: sub slot_reservations_link {
 3983:     my ($linktext,$sname,$sdom,$target) = @_;
 3984:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3985:     my $title = 'View slot reservation history';
 3986:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3987:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3988:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3989:         $title .= ' of this student';
 3990:     }
 3991:     if (defined($target) && $target !~ /^\s*$/) {
 3992:         $target = qq{target="$target"};
 3993:     } else {
 3994:         $target = '';
 3995:     }
 3996:     $title = &mt($title);
 3997:     $linktext = &mt($linktext);
 3998:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3999: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4000: 
 4001: }
 4002: 
 4003: # ===================================================== Display a student photo
 4004: 
 4005: 
 4006: sub student_image_tag {
 4007:     my ($domain,$user)=@_;
 4008:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4009:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4010: 	return '<img src="'.$imgsrc.'" align="right" />';
 4011:     } else {
 4012: 	return '';
 4013:     }
 4014: }
 4015: 
 4016: =pod
 4017: 
 4018: =back
 4019: 
 4020: =head1 Access .tab File Data
 4021: 
 4022: =over 4
 4023: 
 4024: =item * &languageids() 
 4025: 
 4026: returns list of all language ids
 4027: 
 4028: =cut
 4029: 
 4030: sub languageids {
 4031:     return sort(keys(%language));
 4032: }
 4033: 
 4034: =pod
 4035: 
 4036: =item * &languagedescription() 
 4037: 
 4038: returns description of a specified language id
 4039: 
 4040: =cut
 4041: 
 4042: sub languagedescription {
 4043:     my $code=shift;
 4044:     return  ($supported_language{$code}?'* ':'').
 4045:             $language{$code}.
 4046: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4047: }
 4048: 
 4049: =pod
 4050: 
 4051: =item * &plainlanguagedescription
 4052: 
 4053: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4054: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4055: 
 4056: =cut
 4057: 
 4058: sub plainlanguagedescription {
 4059:     my $code=shift;
 4060:     return $language{$code};
 4061: }
 4062: 
 4063: =pod
 4064: 
 4065: =item * &supportedlanguagecode
 4066: 
 4067: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4068: code.
 4069: 
 4070: =cut
 4071: 
 4072: sub supportedlanguagecode {
 4073:     my $code=shift;
 4074:     return $supported_language{$code};
 4075: }
 4076: 
 4077: =pod
 4078: 
 4079: =item * &latexlanguage()
 4080: 
 4081: Given a language key code returns the correspondnig language to use
 4082: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4083: is no supported hyphenation for the language code.
 4084: 
 4085: =cut
 4086: 
 4087: sub latexlanguage {
 4088:     my $code = shift;
 4089:     return $latex_language{$code};
 4090: }
 4091: 
 4092: =pod
 4093: 
 4094: =item * &latexhyphenation()
 4095: 
 4096: Same as above but what's supplied is the language as it might be stored
 4097: in the metadata.
 4098: 
 4099: =cut
 4100: 
 4101: sub latexhyphenation {
 4102:     my $key = shift;
 4103:     return $latex_language_bykey{$key};
 4104: }
 4105: 
 4106: =pod
 4107: 
 4108: =item * &copyrightids() 
 4109: 
 4110: returns list of all copyrights
 4111: 
 4112: =cut
 4113: 
 4114: sub copyrightids {
 4115:     return sort(keys(%cprtag));
 4116: }
 4117: 
 4118: =pod
 4119: 
 4120: =item * &copyrightdescription() 
 4121: 
 4122: returns description of a specified copyright id
 4123: 
 4124: =cut
 4125: 
 4126: sub copyrightdescription {
 4127:     return &mt($cprtag{shift(@_)});
 4128: }
 4129: 
 4130: =pod
 4131: 
 4132: =item * &source_copyrightids() 
 4133: 
 4134: returns list of all source copyrights
 4135: 
 4136: =cut
 4137: 
 4138: sub source_copyrightids {
 4139:     return sort(keys(%scprtag));
 4140: }
 4141: 
 4142: =pod
 4143: 
 4144: =item * &source_copyrightdescription() 
 4145: 
 4146: returns description of a specified source copyright id
 4147: 
 4148: =cut
 4149: 
 4150: sub source_copyrightdescription {
 4151:     return &mt($scprtag{shift(@_)});
 4152: }
 4153: 
 4154: =pod
 4155: 
 4156: =item * &filecategories() 
 4157: 
 4158: returns list of all file categories
 4159: 
 4160: =cut
 4161: 
 4162: sub filecategories {
 4163:     return sort(keys(%category_extensions));
 4164: }
 4165: 
 4166: =pod
 4167: 
 4168: =item * &filecategorytypes() 
 4169: 
 4170: returns list of file types belonging to a given file
 4171: category
 4172: 
 4173: =cut
 4174: 
 4175: sub filecategorytypes {
 4176:     my ($cat) = @_;
 4177:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4178:         return @{$category_extensions{lc($cat)}};
 4179:     } else {
 4180:         return ();
 4181:     }
 4182: }
 4183: 
 4184: =pod
 4185: 
 4186: =item * &fileembstyle() 
 4187: 
 4188: returns embedding style for a specified file type
 4189: 
 4190: =cut
 4191: 
 4192: sub fileembstyle {
 4193:     return $fe{lc(shift(@_))};
 4194: }
 4195: 
 4196: sub filemimetype {
 4197:     return $fm{lc(shift(@_))};
 4198: }
 4199: 
 4200: 
 4201: sub filecategoryselect {
 4202:     my ($name,$value)=@_;
 4203:     return &select_form($value,$name,
 4204:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4205: }
 4206: 
 4207: =pod
 4208: 
 4209: =item * &filedescription() 
 4210: 
 4211: returns description for a specified file type
 4212: 
 4213: =cut
 4214: 
 4215: sub filedescription {
 4216:     my $file_description = $fd{lc(shift())};
 4217:     $file_description =~ s:([\[\]]):~$1:g;
 4218:     return &mt($file_description);
 4219: }
 4220: 
 4221: =pod
 4222: 
 4223: =item * &filedescriptionex() 
 4224: 
 4225: returns description for a specified file type with
 4226: extra formatting
 4227: 
 4228: =cut
 4229: 
 4230: sub filedescriptionex {
 4231:     my $ex=shift;
 4232:     my $file_description = $fd{lc($ex)};
 4233:     $file_description =~ s:([\[\]]):~$1:g;
 4234:     return '.'.$ex.' '.&mt($file_description);
 4235: }
 4236: 
 4237: # End of .tab access
 4238: =pod
 4239: 
 4240: =back
 4241: 
 4242: =cut
 4243: 
 4244: # ------------------------------------------------------------------ File Types
 4245: sub fileextensions {
 4246:     return sort(keys(%fe));
 4247: }
 4248: 
 4249: # ----------------------------------------------------------- Display Languages
 4250: # returns a hash with all desired display languages
 4251: #
 4252: 
 4253: sub display_languages {
 4254:     my %languages=();
 4255:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4256: 	$languages{$lang}=1;
 4257:     }
 4258:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4259:     if ($env{'form.displaylanguage'}) {
 4260: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4261: 	    $languages{$lang}=1;
 4262:         }
 4263:     }
 4264:     return %languages;
 4265: }
 4266: 
 4267: sub languages {
 4268:     my ($possible_langs) = @_;
 4269:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4270:     if (!ref($possible_langs)) {
 4271: 	if( wantarray ) {
 4272: 	    return @preferred_langs;
 4273: 	} else {
 4274: 	    return $preferred_langs[0];
 4275: 	}
 4276:     }
 4277:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4278:     my @preferred_possibilities;
 4279:     foreach my $preferred_lang (@preferred_langs) {
 4280: 	if (exists($possibilities{$preferred_lang})) {
 4281: 	    push(@preferred_possibilities, $preferred_lang);
 4282: 	}
 4283:     }
 4284:     if( wantarray ) {
 4285: 	return @preferred_possibilities;
 4286:     }
 4287:     return $preferred_possibilities[0];
 4288: }
 4289: 
 4290: sub user_lang {
 4291:     my ($touname,$toudom,$fromcid) = @_;
 4292:     my @userlangs;
 4293:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4294:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4295:                     $env{'course.'.$fromcid.'.languages'}));
 4296:     } else {
 4297:         my %langhash = &getlangs($touname,$toudom);
 4298:         if ($langhash{'languages'} ne '') {
 4299:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4300:         } else {
 4301:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4302:             if ($domdefs{'lang_def'} ne '') {
 4303:                 @userlangs = ($domdefs{'lang_def'});
 4304:             }
 4305:         }
 4306:     }
 4307:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4308:     my $user_lh = Apache::localize->get_handle(@languages);
 4309:     return $user_lh;
 4310: }
 4311: 
 4312: 
 4313: ###############################################################
 4314: ##               Student Answer Attempts                     ##
 4315: ###############################################################
 4316: 
 4317: =pod
 4318: 
 4319: =head1 Alternate Problem Views
 4320: 
 4321: =over 4
 4322: 
 4323: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4324:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4325: 
 4326: Return string with previous attempt on problem. Arguments:
 4327: 
 4328: =over 4
 4329: 
 4330: =item * $symb: Problem, including path
 4331: 
 4332: =item * $username: username of the desired student
 4333: 
 4334: =item * $domain: domain of the desired student
 4335: 
 4336: =item * $course: Course ID
 4337: 
 4338: =item * $getattempt: Leave blank for all attempts, otherwise put
 4339:     something
 4340: 
 4341: =item * $regexp: if string matches this regexp, the string will be
 4342:     sent to $gradesub
 4343: 
 4344: =item * $gradesub: routine that processes the string if it matches $regexp
 4345: 
 4346: =item * $usec: section of the desired student
 4347: 
 4348: =item * $identifier: counter for student (multiple students one problem) or 
 4349:     problem (one student; whole sequence).
 4350: 
 4351: =back
 4352: 
 4353: The output string is a table containing all desired attempts, if any.
 4354: 
 4355: =cut
 4356: 
 4357: sub get_previous_attempt {
 4358:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4359:   my $prevattempts='';
 4360:   no strict 'refs';
 4361:   if ($symb) {
 4362:     my (%returnhash)=
 4363:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4364:     if ($returnhash{'version'}) {
 4365:       my %lasthash=();
 4366:       my $version;
 4367:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4368:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4369:             if ($key =~ /\.rawrndseed$/) {
 4370:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4371:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4372:             } else {
 4373:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4374:             }
 4375:         }
 4376:       }
 4377:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4378:       $prevattempts.='<th>'.&mt('History').'</th>';
 4379:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4380:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4381:       foreach my $key (sort(keys(%lasthash))) {
 4382: 	my ($ign,@parts) = split(/\./,$key);
 4383: 	if ($#parts > 0) {
 4384: 	  my $data=$parts[-1];
 4385:           next if ($data eq 'foilorder');
 4386: 	  pop(@parts);
 4387:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4388:           if ($data eq 'type') {
 4389:               unless ($showsurv) {
 4390:                   my $id = join(',',@parts);
 4391:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4392:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4393:                       $lasthidden{$ign.'.'.$id} = 1;
 4394:                   }
 4395:               }
 4396:               if ($identifier ne '') {
 4397:                   my $id = join(',',@parts);
 4398:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4399:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4400:                       $hidestatus{$ign.'.'.$id} = 1;
 4401:                   }
 4402:               }
 4403:           } elsif ($data eq 'regrader') {
 4404:               if (($identifier ne '') && (@parts)) {
 4405:                   my $id = join(',',@parts);
 4406:                   $regraded{$ign.'.'.$id} = 1;
 4407:               }
 4408:           } 
 4409: 	} else {
 4410: 	  if ($#parts == 0) {
 4411: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4412: 	  } else {
 4413: 	    $prevattempts.='<th>'.$ign.'</th>';
 4414: 	  }
 4415: 	}
 4416:       }
 4417:       $prevattempts.=&end_data_table_header_row();
 4418:       if ($getattempt eq '') {
 4419:         my (%solved,%resets,%probstatus);
 4420:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4421:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4422:                 foreach my $id (keys(%regraded)) {
 4423:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4424:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4425:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4426:                         push(@{$resets{$id}},$version);
 4427:                     }
 4428:                 }
 4429:             }
 4430:         }
 4431: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4432:             my (@hidden,@unsolved);
 4433:             if (%typeparts) {
 4434:                 foreach my $id (keys(%typeparts)) {
 4435:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4436:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4437:                         push(@hidden,$id);
 4438:                     } elsif ($identifier ne '') {
 4439:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4440:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4441:                                 ($hidestatus{$id})) {
 4442:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4443:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4444:                                 push(@{$solved{$id}},$version);
 4445:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4446:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4447:                                 my $skip;
 4448:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4449:                                     foreach my $reset (@{$resets{$id}}) {
 4450:                                         if ($reset > $solved{$id}[-1]) {
 4451:                                             $skip=1;
 4452:                                             last;
 4453:                                         }
 4454:                                     }
 4455:                                 }
 4456:                                 unless ($skip) {
 4457:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4458:                                     push(@unsolved,$partslist);
 4459:                                 }
 4460:                             }
 4461:                         }
 4462:                     }
 4463:                 }
 4464:             }
 4465:             $prevattempts.=&start_data_table_row().
 4466:                            '<td>'.&mt('Transaction [_1]',$version);
 4467:             if (@unsolved) {
 4468:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4469:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4470:                                  &mt('Hide').'</label></span>';
 4471:             }
 4472:             $prevattempts .= '</td>';
 4473:             if (@hidden) {
 4474:                 foreach my $key (sort(keys(%lasthash))) {
 4475:                     next if ($key =~ /\.foilorder$/);
 4476:                     my $hide;
 4477:                     foreach my $id (@hidden) {
 4478:                         if ($key =~ /^\Q$id\E/) {
 4479:                             $hide = 1;
 4480:                             last;
 4481:                         }
 4482:                     }
 4483:                     if ($hide) {
 4484:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4485:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4486:                             my $value = &format_previous_attempt_value($key,
 4487:                                              $returnhash{$version.':'.$key});
 4488:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4489:                         } else {
 4490:                             $prevattempts.='<td>&nbsp;</td>';
 4491:                         }
 4492:                     } else {
 4493:                         if ($key =~ /\./) {
 4494:                             my $value = $returnhash{$version.':'.$key};
 4495:                             if ($key =~ /\.rndseed$/) {
 4496:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4497:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4498:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4499:                                 }
 4500:                             }
 4501:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4502:                                            '&nbsp;</td>';
 4503:                         } else {
 4504:                             $prevattempts.='<td>&nbsp;</td>';
 4505:                         }
 4506:                     }
 4507:                 }
 4508:             } else {
 4509: 	        foreach my $key (sort(keys(%lasthash))) {
 4510:                     next if ($key =~ /\.foilorder$/);
 4511:                     my $value = $returnhash{$version.':'.$key};
 4512:                     if ($key =~ /\.rndseed$/) {
 4513:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4514:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4515:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4516:                         }
 4517:                     }
 4518:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4519:                                    '&nbsp;</td>';
 4520: 	        }
 4521:             }
 4522: 	    $prevattempts.=&end_data_table_row();
 4523: 	 }
 4524:       }
 4525:       my @currhidden = keys(%lasthidden);
 4526:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4527:       foreach my $key (sort(keys(%lasthash))) {
 4528:           next if ($key =~ /\.foilorder$/);
 4529:           if (%typeparts) {
 4530:               my $hidden;
 4531:               foreach my $id (@currhidden) {
 4532:                   if ($key =~ /^\Q$id\E/) {
 4533:                       $hidden = 1;
 4534:                       last;
 4535:                   }
 4536:               }
 4537:               if ($hidden) {
 4538:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4539:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4540:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4541:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4542:                           $value = &$gradesub($value);
 4543:                       }
 4544:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4545:                   } else {
 4546:                       $prevattempts.='<td>&nbsp;</td>';
 4547:                   }
 4548:               } else {
 4549:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4550:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4551:                       $value = &$gradesub($value);
 4552:                   }
 4553:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4554:               }
 4555:           } else {
 4556: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4557: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4558:                   $value = &$gradesub($value);
 4559:               }
 4560: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4561:           }
 4562:       }
 4563:       $prevattempts.= &end_data_table_row().&end_data_table();
 4564:     } else {
 4565:       $prevattempts=
 4566: 	  &start_data_table().&start_data_table_row().
 4567: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4568: 	  &end_data_table_row().&end_data_table();
 4569:     }
 4570:   } else {
 4571:     $prevattempts=
 4572: 	  &start_data_table().&start_data_table_row().
 4573: 	  '<td>'.&mt('No data.').'</td>'.
 4574: 	  &end_data_table_row().&end_data_table();
 4575:   }
 4576: }
 4577: 
 4578: sub format_previous_attempt_value {
 4579:     my ($key,$value) = @_;
 4580:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4581:         $value = &Apache::lonlocal::locallocaltime($value);
 4582:     } elsif (ref($value) eq 'ARRAY') {
 4583:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4584:     } elsif ($key =~ /answerstring$/) {
 4585:         my %answers = &Apache::lonnet::str2hash($value);
 4586:         my @answer = %answers;
 4587:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4588:         my @anskeys = sort(keys(%answers));
 4589:         if (@anskeys == 1) {
 4590:             my $answer = $answers{$anskeys[0]};
 4591:             if ($answer =~ m{\0}) {
 4592:                 $answer =~ s{\0}{,}g;
 4593:             }
 4594:             my $tag_internal_answer_name = 'INTERNAL';
 4595:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4596:                 $value = $answer; 
 4597:             } else {
 4598:                 $value = $anskeys[0].'='.$answer;
 4599:             }
 4600:         } else {
 4601:             foreach my $ans (@anskeys) {
 4602:                 my $answer = $answers{$ans};
 4603:                 if ($answer =~ m{\0}) {
 4604:                     $answer =~ s{\0}{,}g;
 4605:                 }
 4606:                 $value .=  $ans.'='.$answer.'<br />';;
 4607:             } 
 4608:         }
 4609:     } else {
 4610:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4611:     }
 4612:     return $value;
 4613: }
 4614: 
 4615: 
 4616: sub relative_to_absolute {
 4617:     my ($url,$output)=@_;
 4618:     my $parser=HTML::TokeParser->new(\$output);
 4619:     my $token;
 4620:     my $thisdir=$url;
 4621:     my @rlinks=();
 4622:     while ($token=$parser->get_token) {
 4623: 	if ($token->[0] eq 'S') {
 4624: 	    if ($token->[1] eq 'a') {
 4625: 		if ($token->[2]->{'href'}) {
 4626: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4627: 		}
 4628: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4629: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4630: 	    } elsif ($token->[1] eq 'base') {
 4631: 		$thisdir=$token->[2]->{'href'};
 4632: 	    }
 4633: 	}
 4634:     }
 4635:     $thisdir=~s-/[^/]*$--;
 4636:     foreach my $link (@rlinks) {
 4637: 	unless (($link=~/^https?\:\/\//i) ||
 4638: 		($link=~/^\//) ||
 4639: 		($link=~/^javascript:/i) ||
 4640: 		($link=~/^mailto:/i) ||
 4641: 		($link=~/^\#/)) {
 4642: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4643: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4644: 	}
 4645:     }
 4646: # -------------------------------------------------- Deal with Applet codebases
 4647:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4648:     return $output;
 4649: }
 4650: 
 4651: =pod
 4652: 
 4653: =item * &get_student_view()
 4654: 
 4655: show a snapshot of what student was looking at
 4656: 
 4657: =cut
 4658: 
 4659: sub get_student_view {
 4660:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4661:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4662:   my (%form);
 4663:   my @elements=('symb','courseid','domain','username');
 4664:   foreach my $element (@elements) {
 4665:       $form{'grade_'.$element}=eval '$'.$element #'
 4666:   }
 4667:   if (defined($moreenv)) {
 4668:       %form=(%form,%{$moreenv});
 4669:   }
 4670:   if (defined($target)) { $form{'grade_target'} = $target; }
 4671:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4672:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4673:   $userview=~s/\<body[^\>]*\>//gi;
 4674:   $userview=~s/\<\/body\>//gi;
 4675:   $userview=~s/\<html\>//gi;
 4676:   $userview=~s/\<\/html\>//gi;
 4677:   $userview=~s/\<head\>//gi;
 4678:   $userview=~s/\<\/head\>//gi;
 4679:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4680:   $userview=&relative_to_absolute($feedurl,$userview);
 4681:   if (wantarray) {
 4682:      return ($userview,$response);
 4683:   } else {
 4684:      return $userview;
 4685:   }
 4686: }
 4687: 
 4688: sub get_student_view_with_retries {
 4689:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4690: 
 4691:     my $ok = 0;                 # True if we got a good response.
 4692:     my $content;
 4693:     my $response;
 4694: 
 4695:     # Try to get the student_view done. within the retries count:
 4696:     
 4697:     do {
 4698:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4699:          $ok      = $response->is_success;
 4700:          if (!$ok) {
 4701:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4702:          }
 4703:          $retries--;
 4704:     } while (!$ok && ($retries > 0));
 4705:     
 4706:     if (!$ok) {
 4707:        $content = '';          # On error return an empty content.
 4708:     }
 4709:     if (wantarray) {
 4710:        return ($content, $response);
 4711:     } else {
 4712:        return $content;
 4713:     }
 4714: }
 4715: 
 4716: =pod
 4717: 
 4718: =item * &get_student_answers() 
 4719: 
 4720: show a snapshot of how student was answering problem
 4721: 
 4722: =cut
 4723: 
 4724: sub get_student_answers {
 4725:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4726:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4727:   my (%moreenv);
 4728:   my @elements=('symb','courseid','domain','username');
 4729:   foreach my $element (@elements) {
 4730:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4731:   }
 4732:   $moreenv{'grade_target'}='answer';
 4733:   %moreenv=(%form,%moreenv);
 4734:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4735:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4736:   return $userview;
 4737: }
 4738: 
 4739: =pod
 4740: 
 4741: =item * &submlink()
 4742: 
 4743: Inputs: $text $uname $udom $symb $target
 4744: 
 4745: Returns: A link to grades.pm such as to see the SUBM view of a student
 4746: 
 4747: =cut
 4748: 
 4749: ###############################################
 4750: sub submlink {
 4751:     my ($text,$uname,$udom,$symb,$target)=@_;
 4752:     if (!($uname && $udom)) {
 4753: 	(my $cursymb, my $courseid,$udom,$uname)=
 4754: 	    &Apache::lonnet::whichuser($symb);
 4755: 	if (!$symb) { $symb=$cursymb; }
 4756:     }
 4757:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4758:     $symb=&escape($symb);
 4759:     if ($target) { $target=" target=\"$target\""; }
 4760:     return
 4761:         '<a href="/adm/grades?command=submission'.
 4762:         '&amp;symb='.$symb.
 4763:         '&amp;student='.$uname.
 4764:         '&amp;userdom='.$udom.'"'.
 4765:         $target.'>'.$text.'</a>';
 4766: }
 4767: ##############################################
 4768: 
 4769: =pod
 4770: 
 4771: =item * &pgrdlink()
 4772: 
 4773: Inputs: $text $uname $udom $symb $target
 4774: 
 4775: Returns: A link to grades.pm such as to see the PGRD view of a student
 4776: 
 4777: =cut
 4778: 
 4779: ###############################################
 4780: sub pgrdlink {
 4781:     my $link=&submlink(@_);
 4782:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4783:     return $link;
 4784: }
 4785: ##############################################
 4786: 
 4787: =pod
 4788: 
 4789: =item * &pprmlink()
 4790: 
 4791: Inputs: $text $uname $udom $symb $target
 4792: 
 4793: Returns: A link to parmset.pm such as to see the PPRM view of a
 4794: student and a specific resource
 4795: 
 4796: =cut
 4797: 
 4798: ###############################################
 4799: sub pprmlink {
 4800:     my ($text,$uname,$udom,$symb,$target)=@_;
 4801:     if (!($uname && $udom)) {
 4802: 	(my $cursymb, my $courseid,$udom,$uname)=
 4803: 	    &Apache::lonnet::whichuser($symb);
 4804: 	if (!$symb) { $symb=$cursymb; }
 4805:     }
 4806:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4807:     $symb=&escape($symb);
 4808:     if ($target) { $target="target=\"$target\""; }
 4809:     return '<a href="/adm/parmset?command=set&amp;'.
 4810: 	'symb='.$symb.'&amp;uname='.$uname.
 4811: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4812: }
 4813: ##############################################
 4814: 
 4815: =pod
 4816: 
 4817: =back
 4818: 
 4819: =cut
 4820: 
 4821: ###############################################
 4822: 
 4823: 
 4824: sub timehash {
 4825:     my ($thistime) = @_;
 4826:     my $timezone = &Apache::lonlocal::gettimezone();
 4827:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4828:                      ->set_time_zone($timezone);
 4829:     my $wday = $dt->day_of_week();
 4830:     if ($wday == 7) { $wday = 0; }
 4831:     return ( 'second' => $dt->second(),
 4832:              'minute' => $dt->minute(),
 4833:              'hour'   => $dt->hour(),
 4834:              'day'     => $dt->day_of_month(),
 4835:              'month'   => $dt->month(),
 4836:              'year'    => $dt->year(),
 4837:              'weekday' => $wday,
 4838:              'dayyear' => $dt->day_of_year(),
 4839:              'dlsav'   => $dt->is_dst() );
 4840: }
 4841: 
 4842: sub utc_string {
 4843:     my ($date)=@_;
 4844:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4845: }
 4846: 
 4847: sub maketime {
 4848:     my %th=@_;
 4849:     my ($epoch_time,$timezone,$dt);
 4850:     $timezone = &Apache::lonlocal::gettimezone();
 4851:     eval {
 4852:         $dt = DateTime->new( year   => $th{'year'},
 4853:                              month  => $th{'month'},
 4854:                              day    => $th{'day'},
 4855:                              hour   => $th{'hour'},
 4856:                              minute => $th{'minute'},
 4857:                              second => $th{'second'},
 4858:                              time_zone => $timezone,
 4859:                          );
 4860:     };
 4861:     if (!$@) {
 4862:         $epoch_time = $dt->epoch;
 4863:         if ($epoch_time) {
 4864:             return $epoch_time;
 4865:         }
 4866:     }
 4867:     return POSIX::mktime(
 4868:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4869:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4870: }
 4871: 
 4872: #########################################
 4873: 
 4874: sub findallcourses {
 4875:     my ($roles,$uname,$udom) = @_;
 4876:     my %roles;
 4877:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4878:     my %courses;
 4879:     my $now=time;
 4880:     if (!defined($uname)) {
 4881:         $uname = $env{'user.name'};
 4882:     }
 4883:     if (!defined($udom)) {
 4884:         $udom = $env{'user.domain'};
 4885:     }
 4886:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4887:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4888:         if (!%roles) {
 4889:             %roles = (
 4890:                        cc => 1,
 4891:                        co => 1,
 4892:                        in => 1,
 4893:                        ep => 1,
 4894:                        ta => 1,
 4895:                        cr => 1,
 4896:                        st => 1,
 4897:              );
 4898:         }
 4899:         foreach my $entry (keys(%roleshash)) {
 4900:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4901:             if ($trole =~ /^cr/) { 
 4902:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4903:             } else {
 4904:                 next if (!exists($roles{$trole}));
 4905:             }
 4906:             if ($tend) {
 4907:                 next if ($tend < $now);
 4908:             }
 4909:             if ($tstart) {
 4910:                 next if ($tstart > $now);
 4911:             }
 4912:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4913:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4914:             my $value = $trole.'/'.$cdom.'/';
 4915:             if ($secpart eq '') {
 4916:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4917:                 $sec = 'none';
 4918:                 $value .= $cnum.'/';
 4919:             } else {
 4920:                 $cnum = $cnumpart;
 4921:                 ($sec,$role) = split(/_/,$secpart);
 4922:                 $value .= $cnum.'/'.$sec;
 4923:             }
 4924:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4925:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4926:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4927:                 }
 4928:             } else {
 4929:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4930:             }
 4931:         }
 4932:     } else {
 4933:         foreach my $key (keys(%env)) {
 4934: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4935:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4936: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4937: 	        next if ($role eq 'ca' || $role eq 'aa');
 4938: 	        next if (%roles && !exists($roles{$role}));
 4939: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4940:                 my $active=1;
 4941:                 if ($starttime) {
 4942: 		    if ($now<$starttime) { $active=0; }
 4943:                 }
 4944:                 if ($endtime) {
 4945:                     if ($now>$endtime) { $active=0; }
 4946:                 }
 4947:                 if ($active) {
 4948:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4949:                     if ($sec eq '') {
 4950:                         $sec = 'none';
 4951:                     } else {
 4952:                         $value .= $sec;
 4953:                     }
 4954:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4955:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4956:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4957:                         }
 4958:                     } else {
 4959:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4960:                     }
 4961:                 }
 4962:             }
 4963:         }
 4964:     }
 4965:     return %courses;
 4966: }
 4967: 
 4968: ###############################################
 4969: 
 4970: sub blockcheck {
 4971:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4972: 
 4973:     if (defined($udom) && defined($uname)) {
 4974:         # If uname and udom are for a course, check for blocks in the course.
 4975:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4976:             my ($startblock,$endblock,$triggerblock) =
 4977:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4978:             return ($startblock,$endblock,$triggerblock);
 4979:         }
 4980:     } else {
 4981:         $udom = $env{'user.domain'};
 4982:         $uname = $env{'user.name'};
 4983:     }
 4984: 
 4985:     my $startblock = 0;
 4986:     my $endblock = 0;
 4987:     my $triggerblock = '';
 4988:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4989: 
 4990:     # If uname is for a user, and activity is course-specific, i.e.,
 4991:     # boards, chat or groups, check for blocking in current course only.
 4992: 
 4993:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4994:          $activity eq 'groups' || $activity eq 'printout') &&
 4995:         ($env{'request.course.id'})) {
 4996:         foreach my $key (keys(%live_courses)) {
 4997:             if ($key ne $env{'request.course.id'}) {
 4998:                 delete($live_courses{$key});
 4999:             }
 5000:         }
 5001:     }
 5002: 
 5003:     my $otheruser = 0;
 5004:     my %own_courses;
 5005:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5006:         # Resource belongs to user other than current user.
 5007:         $otheruser = 1;
 5008:         # Gather courses for current user
 5009:         %own_courses = 
 5010:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5011:     }
 5012: 
 5013:     # Gather active course roles - course coordinator, instructor, 
 5014:     # exam proctor, ta, student, or custom role.
 5015: 
 5016:     foreach my $course (keys(%live_courses)) {
 5017:         my ($cdom,$cnum);
 5018:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5019:             $cdom = $env{'course.'.$course.'.domain'};
 5020:             $cnum = $env{'course.'.$course.'.num'};
 5021:         } else {
 5022:             ($cdom,$cnum) = split(/_/,$course); 
 5023:         }
 5024:         my $no_ownblock = 0;
 5025:         my $no_userblock = 0;
 5026:         if ($otheruser && $activity ne 'com') {
 5027:             # Check if current user has 'evb' priv for this
 5028:             if (defined($own_courses{$course})) {
 5029:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5030:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5031:                     if ($sec ne 'none') {
 5032:                         $checkrole .= '/'.$sec;
 5033:                     }
 5034:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5035:                         $no_ownblock = 1;
 5036:                         last;
 5037:                     }
 5038:                 }
 5039:             }
 5040:             # if they have 'evb' priv and are currently not playing student
 5041:             next if (($no_ownblock) &&
 5042:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5043:         }
 5044:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5045:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5046:             if ($sec ne 'none') {
 5047:                 $checkrole .= '/'.$sec;
 5048:             }
 5049:             if ($otheruser) {
 5050:                 # Resource belongs to user other than current user.
 5051:                 # Assemble privs for that user, and check for 'evb' priv.
 5052:                 my (%allroles,%userroles);
 5053:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5054:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5055:                         my ($trole,$tdom,$tnum,$tsec);
 5056:                         if ($entry =~ /^cr/) {
 5057:                             ($trole,$tdom,$tnum,$tsec) = 
 5058:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5059:                         } else {
 5060:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5061:                         }
 5062:                         my ($spec,$area,$trest);
 5063:                         $area = '/'.$tdom.'/'.$tnum;
 5064:                         $trest = $tnum;
 5065:                         if ($tsec ne '') {
 5066:                             $area .= '/'.$tsec;
 5067:                             $trest .= '/'.$tsec;
 5068:                         }
 5069:                         $spec = $trole.'.'.$area;
 5070:                         if ($trole =~ /^cr/) {
 5071:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5072:                                                               $tdom,$spec,$trest,$area);
 5073:                         } else {
 5074:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5075:                                                                 $tdom,$spec,$trest,$area);
 5076:                         }
 5077:                     }
 5078:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5079:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5080:                         if ($1) {
 5081:                             $no_userblock = 1;
 5082:                             last;
 5083:                         }
 5084:                     }
 5085:                 }
 5086:             } else {
 5087:                 # Resource belongs to current user
 5088:                 # Check for 'evb' priv via lonnet::allowed().
 5089:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5090:                     $no_ownblock = 1;
 5091:                     last;
 5092:                 }
 5093:             }
 5094:         }
 5095:         # if they have the evb priv and are currently not playing student
 5096:         next if (($no_ownblock) &&
 5097:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5098:         next if ($no_userblock);
 5099: 
 5100:         # Retrieve blocking times and identity of locker for course
 5101:         # of specified user, unless user has 'evb' privilege.
 5102:         
 5103:         my ($start,$end,$trigger) = 
 5104:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 5105:         if (($start != 0) && 
 5106:             (($startblock == 0) || ($startblock > $start))) {
 5107:             $startblock = $start;
 5108:             if ($trigger ne '') {
 5109:                 $triggerblock = $trigger;
 5110:             }
 5111:         }
 5112:         if (($end != 0)  &&
 5113:             (($endblock == 0) || ($endblock < $end))) {
 5114:             $endblock = $end;
 5115:             if ($trigger ne '') {
 5116:                 $triggerblock = $trigger;
 5117:             }
 5118:         }
 5119:     }
 5120:     return ($startblock,$endblock,$triggerblock);
 5121: }
 5122: 
 5123: sub get_blocks {
 5124:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 5125:     my $startblock = 0;
 5126:     my $endblock = 0;
 5127:     my $triggerblock = '';
 5128:     my $course = $cdom.'_'.$cnum;
 5129:     $setters->{$course} = {};
 5130:     $setters->{$course}{'staff'} = [];
 5131:     $setters->{$course}{'times'} = [];
 5132:     $setters->{$course}{'triggers'} = [];
 5133:     my (@blockers,%triggered);
 5134:     my $now = time;
 5135:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5136:     if ($activity eq 'docs') {
 5137:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 5138:         foreach my $block (@blockers) {
 5139:             if ($block =~ /^firstaccess____(.+)$/) {
 5140:                 my $item = $1;
 5141:                 my $type = 'map';
 5142:                 my $timersymb = $item;
 5143:                 if ($item eq 'course') {
 5144:                     $type = 'course';
 5145:                 } elsif ($item =~ /___\d+___/) {
 5146:                     $type = 'resource';
 5147:                 } else {
 5148:                     $timersymb = &Apache::lonnet::symbread($item);
 5149:                 }
 5150:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5151:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5152:                 $triggered{$block} = {
 5153:                                        start => $start,
 5154:                                        end   => $end,
 5155:                                        type  => $type,
 5156:                                      };
 5157:             }
 5158:         }
 5159:     } else {
 5160:         foreach my $block (keys(%commblocks)) {
 5161:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5162:                 my ($start,$end) = ($1,$2);
 5163:                 if ($start <= time && $end >= time) {
 5164:                     if (ref($commblocks{$block}) eq 'HASH') {
 5165:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5166:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5167:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5168:                                     push(@blockers,$block);
 5169:                                 }
 5170:                             }
 5171:                         }
 5172:                     }
 5173:                 }
 5174:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5175:                 my $item = $1;
 5176:                 my $timersymb = $item; 
 5177:                 my $type = 'map';
 5178:                 if ($item eq 'course') {
 5179:                     $type = 'course';
 5180:                 } elsif ($item =~ /___\d+___/) {
 5181:                     $type = 'resource';
 5182:                 } else {
 5183:                     $timersymb = &Apache::lonnet::symbread($item);
 5184:                 }
 5185:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5186:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5187:                 if ($start && $end) {
 5188:                     if (($start <= time) && ($end >= time)) {
 5189:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 5190:                             push(@blockers,$block);
 5191:                             $triggered{$block} = {
 5192:                                                    start => $start,
 5193:                                                    end   => $end,
 5194:                                                    type  => $type,
 5195:                                                  };
 5196:                         }
 5197:                     }
 5198:                 }
 5199:             }
 5200:         }
 5201:     }
 5202:     foreach my $blocker (@blockers) {
 5203:         my ($staff_name,$staff_dom,$title,$blocks) =
 5204:             &parse_block_record($commblocks{$blocker});
 5205:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5206:         my ($start,$end,$triggertype);
 5207:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5208:             ($start,$end) = ($1,$2);
 5209:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5210:             $start = $triggered{$blocker}{'start'};
 5211:             $end = $triggered{$blocker}{'end'};
 5212:             $triggertype = $triggered{$blocker}{'type'};
 5213:         }
 5214:         if ($start) {
 5215:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5216:             if ($triggertype) {
 5217:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5218:             } else {
 5219:                 push(@{$$setters{$course}{'triggers'}},0);
 5220:             }
 5221:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5222:                 $startblock = $start;
 5223:                 if ($triggertype) {
 5224:                     $triggerblock = $blocker;
 5225:                 }
 5226:             }
 5227:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5228:                $endblock = $end;
 5229:                if ($triggertype) {
 5230:                    $triggerblock = $blocker;
 5231:                }
 5232:             }
 5233:         }
 5234:     }
 5235:     return ($startblock,$endblock,$triggerblock);
 5236: }
 5237: 
 5238: sub parse_block_record {
 5239:     my ($record) = @_;
 5240:     my ($setuname,$setudom,$title,$blocks);
 5241:     if (ref($record) eq 'HASH') {
 5242:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5243:         $title = &unescape($record->{'event'});
 5244:         $blocks = $record->{'blocks'};
 5245:     } else {
 5246:         my @data = split(/:/,$record,3);
 5247:         if (scalar(@data) eq 2) {
 5248:             $title = $data[1];
 5249:             ($setuname,$setudom) = split(/@/,$data[0]);
 5250:         } else {
 5251:             ($setuname,$setudom,$title) = @data;
 5252:         }
 5253:         $blocks = { 'com' => 'on' };
 5254:     }
 5255:     return ($setuname,$setudom,$title,$blocks);
 5256: }
 5257: 
 5258: sub blocking_status {
 5259:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 5260:     my %setters;
 5261: 
 5262: # check for active blocking
 5263:     my ($startblock,$endblock,$triggerblock) = 
 5264:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 5265:     my $blocked = 0;
 5266:     if ($startblock && $endblock) {
 5267:         $blocked = 1;
 5268:     }
 5269: 
 5270: # caller just wants to know whether a block is active
 5271:     if (!wantarray) { return $blocked; }
 5272: 
 5273: # build a link to a popup window containing the details
 5274:     my $querystring  = "?activity=$activity";
 5275: # $uname and $udom decide whose portfolio the user is trying to look at
 5276:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5277:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5278:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5279:     } elsif ($activity eq 'docs') {
 5280:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 5281:     }
 5282: 
 5283:     my $output .= <<'END_MYBLOCK';
 5284: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5285:     var options = "width=" + w + ",height=" + h + ",";
 5286:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5287:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5288:     var newWin = window.open(url, wdwName, options);
 5289:     newWin.focus();
 5290: }
 5291: END_MYBLOCK
 5292: 
 5293:     $output = Apache::lonhtmlcommon::scripttag($output);
 5294:   
 5295:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5296:     my $text = &mt('Communication Blocked');
 5297:     my $class = 'LC_comblock';
 5298:     if ($activity eq 'docs') {
 5299:         $text = &mt('Content Access Blocked');
 5300:         $class = '';
 5301:     } elsif ($activity eq 'printout') {
 5302:         $text = &mt('Printing Blocked');
 5303:     } elsif ($activity eq 'passwd') {
 5304:         $text = &mt('Password Changing Blocked');
 5305:     }
 5306:     $output .= <<"END_BLOCK";
 5307: <div class='$class'>
 5308:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5309:   title='$text'>
 5310:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5311:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5312:   title='$text'>$text</a>
 5313: </div>
 5314: 
 5315: END_BLOCK
 5316: 
 5317:     return ($blocked, $output);
 5318: }
 5319: 
 5320: ###############################################
 5321: 
 5322: sub check_ip_acc {
 5323:     my ($acc,$clientip)=@_;
 5324:     &Apache::lonxml::debug("acc is $acc");
 5325:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5326:         return 1;
 5327:     }
 5328:     my $allowed;
 5329:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5330: 
 5331:     my $name;
 5332:     my %access = (
 5333:                      allowfrom => 1,
 5334:                      denyfrom  => 0,
 5335:                  );
 5336:     my @allows;
 5337:     my @denies;
 5338:     foreach my $item (split(',',$acc)) {
 5339:         $item =~ s/^\s*//;
 5340:         $item =~ s/\s*$//;
 5341:         my $pattern;
 5342:         if ($item =~ /^\!(.+)$/) {
 5343:             push(@denies,$1);
 5344:         } else {
 5345:             push(@allows,$item);
 5346:         }
 5347:    }
 5348:    my $numdenies = scalar(@denies);
 5349:    my $numallows = scalar(@allows);
 5350:    my $count = 0;
 5351:    foreach my $pattern (@denies,@allows) {
 5352:         $count ++; 
 5353:         my $acctype = 'allowfrom';
 5354:         if ($count <= $numdenies) {
 5355:             $acctype = 'denyfrom';
 5356:         }
 5357:         if ($pattern =~ /\*$/) {
 5358:             #35.8.*
 5359:             $pattern=~s/\*//;
 5360:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5361:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5362:             #35.8.3.[34-56]
 5363:             my $low=$2;
 5364:             my $high=$3;
 5365:             $pattern=$1;
 5366:             if ($ip =~ /^\Q$pattern\E/) {
 5367:                 my $last=(split(/\./,$ip))[3];
 5368:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5369:             }
 5370:         } elsif ($pattern =~ /^\*/) {
 5371:             #*.msu.edu
 5372:             $pattern=~s/\*//;
 5373:             if (!defined($name)) {
 5374:                 use Socket;
 5375:                 my $netaddr=inet_aton($ip);
 5376:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5377:             }
 5378:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5379:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5380:             #127.0.0.1
 5381:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5382:         } else {
 5383:             #some.name.com
 5384:             if (!defined($name)) {
 5385:                 use Socket;
 5386:                 my $netaddr=inet_aton($ip);
 5387:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5388:             }
 5389:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5390:         }
 5391:         if ($allowed =~ /^(0|1)$/) { last; }
 5392:     }
 5393:     if ($allowed eq '') {
 5394:         if ($numdenies && !$numallows) {
 5395:             $allowed = 1;
 5396:         } else {
 5397:             $allowed = 0;
 5398:         }
 5399:     }
 5400:     return $allowed;
 5401: }
 5402: 
 5403: ###############################################
 5404: 
 5405: =pod
 5406: 
 5407: =head1 Domain Template Functions
 5408: 
 5409: =over 4
 5410: 
 5411: =item * &determinedomain()
 5412: 
 5413: Inputs: $domain (usually will be undef)
 5414: 
 5415: Returns: Determines which domain should be used for designs
 5416: 
 5417: =cut
 5418: 
 5419: ###############################################
 5420: sub determinedomain {
 5421:     my $domain=shift;
 5422:     if (! $domain) {
 5423:         # Determine domain if we have not been given one
 5424:         $domain = &Apache::lonnet::default_login_domain();
 5425:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5426:         if ($env{'request.role.domain'}) { 
 5427:             $domain=$env{'request.role.domain'}; 
 5428:         }
 5429:     }
 5430:     return $domain;
 5431: }
 5432: ###############################################
 5433: 
 5434: sub devalidate_domconfig_cache {
 5435:     my ($udom)=@_;
 5436:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5437: }
 5438: 
 5439: # ---------------------- Get domain configuration for a domain
 5440: sub get_domainconf {
 5441:     my ($udom) = @_;
 5442:     my $cachetime=1800;
 5443:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5444:     if (defined($cached)) { return %{$result}; }
 5445: 
 5446:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5447: 					     ['login','rolecolors','autoenroll'],$udom);
 5448:     my (%designhash,%legacy);
 5449:     if (keys(%domconfig) > 0) {
 5450:         if (ref($domconfig{'login'}) eq 'HASH') {
 5451:             if (keys(%{$domconfig{'login'}})) {
 5452:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5453:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5454:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5455:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5456:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5457:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5458:                                         if ($key eq 'loginvia') {
 5459:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5460:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5461:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5462:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5463: 
 5464:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5465:                                                 } else {
 5466:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5467:                                                 }
 5468:                                             }
 5469:                                         } elsif ($key eq 'headtag') {
 5470:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5471:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5472:                                             }
 5473:                                         }
 5474:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5475:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5476:                                         }
 5477:                                     }
 5478:                                 }
 5479:                             }
 5480:                         } else {
 5481:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5482:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5483:                                     $domconfig{'login'}{$key}{$img};
 5484:                             }
 5485:                         }
 5486:                     } else {
 5487:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5488:                     }
 5489:                 }
 5490:             } else {
 5491:                 $legacy{'login'} = 1;
 5492:             }
 5493:         } else {
 5494:             $legacy{'login'} = 1;
 5495:         }
 5496:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5497:             if (keys(%{$domconfig{'rolecolors'}})) {
 5498:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5499:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5500:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5501:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5502:                         }
 5503:                     }
 5504:                 }
 5505:             } else {
 5506:                 $legacy{'rolecolors'} = 1;
 5507:             }
 5508:         } else {
 5509:             $legacy{'rolecolors'} = 1;
 5510:         }
 5511:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5512:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5513:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5514:             }
 5515:         }
 5516:         if (keys(%legacy) > 0) {
 5517:             my %legacyhash = &get_legacy_domconf($udom);
 5518:             foreach my $item (keys(%legacyhash)) {
 5519:                 if ($item =~ /^\Q$udom\E\.login/) {
 5520:                     if ($legacy{'login'}) { 
 5521:                         $designhash{$item} = $legacyhash{$item};
 5522:                     }
 5523:                 } else {
 5524:                     if ($legacy{'rolecolors'}) {
 5525:                         $designhash{$item} = $legacyhash{$item};
 5526:                     }
 5527:                 }
 5528:             }
 5529:         }
 5530:     } else {
 5531:         %designhash = &get_legacy_domconf($udom); 
 5532:     }
 5533:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5534: 				  $cachetime);
 5535:     return %designhash;
 5536: }
 5537: 
 5538: sub get_legacy_domconf {
 5539:     my ($udom) = @_;
 5540:     my %legacyhash;
 5541:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5542:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5543:     if (-e $designfile) {
 5544:         if ( open (my $fh,"<$designfile") ) {
 5545:             while (my $line = <$fh>) {
 5546:                 next if ($line =~ /^\#/);
 5547:                 chomp($line);
 5548:                 my ($key,$val)=(split(/\=/,$line));
 5549:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5550:             }
 5551:             close($fh);
 5552:         }
 5553:     }
 5554:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5555:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5556:     }
 5557:     return %legacyhash;
 5558: }
 5559: 
 5560: =pod
 5561: 
 5562: =item * &domainlogo()
 5563: 
 5564: Inputs: $domain (usually will be undef)
 5565: 
 5566: Returns: A link to a domain logo, if the domain logo exists.
 5567: If the domain logo does not exist, a description of the domain.
 5568: 
 5569: =cut
 5570: 
 5571: ###############################################
 5572: sub domainlogo {
 5573:     my $domain = &determinedomain(shift);
 5574:     my %designhash = &get_domainconf($domain);    
 5575:     # See if there is a logo
 5576:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5577:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5578:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5579: 	    if ($imgsrc =~ m{^/res/}) {
 5580: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5581: 		&Apache::lonnet::repcopy($local_name);
 5582: 	    }
 5583: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5584:         } 
 5585:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5586:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5587:         return &Apache::lonnet::domain($domain,'description');
 5588:     } else {
 5589:         return '';
 5590:     }
 5591: }
 5592: ##############################################
 5593: 
 5594: =pod
 5595: 
 5596: =item * &designparm()
 5597: 
 5598: Inputs: $which parameter; $domain (usually will be undef)
 5599: 
 5600: Returns: value of designparamter $which
 5601: 
 5602: =cut
 5603: 
 5604: 
 5605: ##############################################
 5606: sub designparm {
 5607:     my ($which,$domain)=@_;
 5608:     if (exists($env{'environment.color.'.$which})) {
 5609:         return $env{'environment.color.'.$which};
 5610:     }
 5611:     $domain=&determinedomain($domain);
 5612:     my %domdesign;
 5613:     unless ($domain eq 'public') {
 5614:         %domdesign = &get_domainconf($domain);
 5615:     }
 5616:     my $output;
 5617:     if ($domdesign{$domain.'.'.$which} ne '') {
 5618:         $output = $domdesign{$domain.'.'.$which};
 5619:     } else {
 5620:         $output = $defaultdesign{$which};
 5621:     }
 5622:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5623:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5624:         if ($output =~ m{^/(adm|res)/}) {
 5625:             if ($output =~ m{^/res/}) {
 5626:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5627:                 &Apache::lonnet::repcopy($local_name);
 5628:             }
 5629:             $output = &lonhttpdurl($output);
 5630:         }
 5631:     }
 5632:     return $output;
 5633: }
 5634: 
 5635: ##############################################
 5636: =pod
 5637: 
 5638: =item * &authorspace()
 5639: 
 5640: Inputs: $url (usually will be undef).
 5641: 
 5642: Returns: Path to Authoring Space containing the resource or 
 5643:          directory being viewed (or for which action is being taken). 
 5644:          If $url is provided, and begins /priv/<domain>/<uname>
 5645:          the path will be that portion of the $context argument.
 5646:          Otherwise the path will be for the author space of the current
 5647:          user when the current role is author, or for that of the 
 5648:          co-author/assistant co-author space when the current role 
 5649:          is co-author or assistant co-author.
 5650: 
 5651: =cut
 5652: 
 5653: sub authorspace {
 5654:     my ($url) = @_;
 5655:     if ($url ne '') {
 5656:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5657:            return $1;
 5658:         }
 5659:     }
 5660:     my $caname = '';
 5661:     my $cadom = '';
 5662:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5663:         ($cadom,$caname) =
 5664:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5665:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5666:         $caname = $env{'user.name'};
 5667:         $cadom = $env{'user.domain'};
 5668:     }
 5669:     if (($caname ne '') && ($cadom ne '')) {
 5670:         return "/priv/$cadom/$caname/";
 5671:     }
 5672:     return;
 5673: }
 5674: 
 5675: ##############################################
 5676: =pod
 5677: 
 5678: =item * &head_subbox()
 5679: 
 5680: Inputs: $content (contains HTML code with page functions, etc.)
 5681: 
 5682: Returns: HTML div with $content
 5683:          To be included in page header
 5684: 
 5685: =cut
 5686: 
 5687: sub head_subbox {
 5688:     my ($content)=@_;
 5689:     my $output =
 5690:         '<div class="LC_head_subbox">'
 5691:        .$content
 5692:        .'</div>'
 5693: }
 5694: 
 5695: ##############################################
 5696: =pod
 5697: 
 5698: =item * &CSTR_pageheader()
 5699: 
 5700: Input: (optional) filename from which breadcrumb trail is built.
 5701:        In most cases no input as needed, as $env{'request.filename'}
 5702:        is appropriate for use in building the breadcrumb trail.
 5703: 
 5704: Returns: HTML div with CSTR path and recent box
 5705:          To be included on Authoring Space pages
 5706: 
 5707: =cut
 5708: 
 5709: sub CSTR_pageheader {
 5710:     my ($trailfile) = @_;
 5711:     if ($trailfile eq '') {
 5712:         $trailfile = $env{'request.filename'};
 5713:     }
 5714: 
 5715: # this is for resources; directories have customtitle, and crumbs
 5716: # and select recent are created in lonpubdir.pm
 5717: 
 5718:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5719:     my ($udom,$uname,$thisdisfn)=
 5720:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5721:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5722:     $formaction =~ s{/+}{/}g;
 5723: 
 5724:     my $parentpath = '';
 5725:     my $lastitem = '';
 5726:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5727:         $parentpath = $1;
 5728:         $lastitem = $2;
 5729:     } else {
 5730:         $lastitem = $thisdisfn;
 5731:     }
 5732: 
 5733:     my ($crsauthor,$title);
 5734:     if (($env{'request.course.id'}) &&
 5735:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 5736:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 5737:         $crsauthor = 1;
 5738:         $title = &mt('Course Authoring Space');
 5739:     } else {
 5740:         $title = &mt('Authoring Space');
 5741:     }
 5742: 
 5743:     my $output =
 5744:          '<div>'
 5745:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5746:         .'<b>'.$title.'</b> '
 5747:         .'<form name="dirs" method="post" action="'.$formaction
 5748:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5749:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5750: 
 5751:     if ($lastitem) {
 5752:         $output .=
 5753:              '<span class="LC_filename">'
 5754:             .$lastitem
 5755:             .'</span>';
 5756:     }
 5757: 
 5758:     if ($crsauthor) {
 5759:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 5760:     } else {
 5761:         $output .=
 5762:              '<br />'
 5763:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5764:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5765:             .'</form>'
 5766:             .&Apache::lonmenu::constspaceform();
 5767:     }
 5768:     $output .= '</div>';
 5769: 
 5770:     return $output;
 5771: }
 5772: 
 5773: ###############################################
 5774: ###############################################
 5775: 
 5776: =pod
 5777: 
 5778: =back
 5779: 
 5780: =head1 HTML Helpers
 5781: 
 5782: =over 4
 5783: 
 5784: =item * &bodytag()
 5785: 
 5786: Returns a uniform header for LON-CAPA web pages.
 5787: 
 5788: Inputs: 
 5789: 
 5790: =over 4
 5791: 
 5792: =item * $title, A title to be displayed on the page.
 5793: 
 5794: =item * $function, the current role (can be undef).
 5795: 
 5796: =item * $addentries, extra parameters for the <body> tag.
 5797: 
 5798: =item * $bodyonly, if defined, only return the <body> tag.
 5799: 
 5800: =item * $domain, if defined, force a given domain.
 5801: 
 5802: =item * $forcereg, if page should register as content page (relevant for 
 5803:             text interface only)
 5804: 
 5805: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5806:                      navigational links
 5807: 
 5808: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5809: 
 5810: =item * $args, optional argument valid values are
 5811:             no_auto_mt_title -> prevents &mt()ing the title arg
 5812:             use_absolute     -> for external resource or syllabus, this will
 5813:                                 contain https://<hostname> if server uses
 5814:                                 https (as per hosts.tab), but request is for http
 5815:             hostname         -> hostname, from $r->hostname().
 5816: 
 5817: =item * $advtoolsref, optional argument, ref to an array containing
 5818:             inlineremote items to be added in "Functions" menu below
 5819:             breadcrumbs.
 5820: 
 5821: =back
 5822: 
 5823: Returns: A uniform header for LON-CAPA web pages.  
 5824: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5825: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5826: other decorations will be returned.
 5827: 
 5828: =cut
 5829: 
 5830: sub bodytag {
 5831:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5832:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5833: 
 5834:     my $public;
 5835:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5836:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5837:         $public = 1;
 5838:     }
 5839:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5840:     my $httphost = $args->{'use_absolute'};
 5841:     my $hostname = $args->{'hostname'};
 5842: 
 5843:     $function = &get_users_function() if (!$function);
 5844:     my $img =    &designparm($function.'.img',$domain);
 5845:     my $font =   &designparm($function.'.font',$domain);
 5846:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5847: 
 5848:     my %design = ( 'style'   => 'margin-top: 0',
 5849: 		   'bgcolor' => $pgbg,
 5850: 		   'text'    => $font,
 5851:                    'alink'   => &designparm($function.'.alink',$domain),
 5852: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5853: 		   'link'    => &designparm($function.'.link',$domain),);
 5854:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5855: 
 5856:  # role and realm
 5857:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5858:     if ($realm) {
 5859:         $realm = '/'.$realm;
 5860:     }
 5861:     if ($role  eq 'ca') {
 5862:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5863:         $realm = &plainname($rname,$rdom);
 5864:     } 
 5865: # realm
 5866:     if ($env{'request.course.id'}) {
 5867:         if ($env{'request.role'} !~ /^cr/) {
 5868:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5869:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5870:             if ($env{'request.role.desc'}) {
 5871:                 $role = $env{'request.role.desc'};
 5872:             } else {
 5873:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5874:             }
 5875:         } else {
 5876:             $role = (split(/\//,$role,4))[-1]; 
 5877:         }
 5878:         if ($env{'request.course.sec'}) {
 5879:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5880:         }   
 5881: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5882:     } else {
 5883:         $role = &Apache::lonnet::plaintext($role);
 5884:     }
 5885: 
 5886:     if (!$realm) { $realm='&nbsp;'; }
 5887: 
 5888:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5889: 
 5890: # construct main body tag
 5891:     my $bodytag = "<body $extra_body_attr>".
 5892: 	&Apache::lontexconvert::init_math_support();
 5893: 
 5894:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5895: 
 5896:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5897:         return $bodytag;
 5898:     }
 5899: 
 5900:     if ($public) {
 5901: 	undef($role);
 5902:     }
 5903:     
 5904:     my $titleinfo = '<h1>'.$title.'</h1>';
 5905:     #
 5906:     # Extra info if you are the DC
 5907:     my $dc_info = '';
 5908:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5909:                         $env{'course.'.$env{'request.course.id'}.
 5910:                                  '.domain'}.'/'})) {
 5911:         my $cid = $env{'request.course.id'};
 5912:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5913:         $dc_info =~ s/\s+$//;
 5914:     }
 5915: 
 5916:     my $crstype;
 5917:     if ($env{'request.course.id'}) {
 5918:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 5919:     } elsif ($args->{'crstype'}) {
 5920:         $crstype = $args->{'crstype'};
 5921:     }
 5922:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 5923:         undef($role);
 5924:     } else {
 5925:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5926:     }
 5927: 
 5928:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5929: 
 5930:         #    if ($env{'request.state'} eq 'construct') {
 5931:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5932:         #    }
 5933: 
 5934:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5935:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5936: 
 5937:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
 5938: 
 5939:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5940:              if ($dc_info) {
 5941:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5942:              }
 5943:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5944:                 <em>$realm</em> $dc_info</div>|;
 5945:             return $bodytag;
 5946:         }
 5947: 
 5948:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5949:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5950:         }
 5951: 
 5952:         $bodytag .= $right;
 5953: 
 5954:         if ($dc_info) {
 5955:             $dc_info = &dc_courseid_toggle($dc_info);
 5956:         }
 5957:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5958: 
 5959:         #if directed to not display the secondary menu, don't.  
 5960:         if ($args->{'no_secondary_menu'}) {
 5961:             return $bodytag;
 5962:         }
 5963:         #don't show menus for public users
 5964:         if (!$public){
 5965:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5966:             $bodytag .= Apache::lonmenu::serverform();
 5967:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5968:             if ($env{'request.state'} eq 'construct') {
 5969:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5970:                                 $args->{'bread_crumbs'},'','',$hostname);
 5971:             } elsif ($forcereg) {
 5972:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5973:                                                             $args->{'group'},
 5974:                                                             $args->{'hide_buttons'},
 5975:                                                             $hostname);
 5976:             } else {
 5977:                 $bodytag .= 
 5978:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5979:                                                         $forcereg,$args->{'group'},
 5980:                                                         $args->{'bread_crumbs'},
 5981:                                                         $advtoolsref,'',$hostname);
 5982:             }
 5983:         }else{
 5984:             # this is to seperate menu from content when there's no secondary
 5985:             # menu. Especially needed for public accessible ressources.
 5986:             $bodytag .= '<hr style="clear:both" />';
 5987:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5988:         }
 5989: 
 5990:         return $bodytag;
 5991: }
 5992: 
 5993: sub dc_courseid_toggle {
 5994:     my ($dc_info) = @_;
 5995:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5996:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5997:            &mt('(More ...)').'</a></span>'.
 5998:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5999: }
 6000: 
 6001: sub make_attr_string {
 6002:     my ($register,$attr_ref) = @_;
 6003: 
 6004:     if ($attr_ref && !ref($attr_ref)) {
 6005: 	die("addentries Must be a hash ref ".
 6006: 	    join(':',caller(1))." ".
 6007: 	    join(':',caller(0))." ");
 6008:     }
 6009: 
 6010:     if ($register) {
 6011: 	my ($on_load,$on_unload);
 6012: 	foreach my $key (keys(%{$attr_ref})) {
 6013: 	    if      (lc($key) eq 'onload') {
 6014: 		$on_load.=$attr_ref->{$key}.';';
 6015: 		delete($attr_ref->{$key});
 6016: 
 6017: 	    } elsif (lc($key) eq 'onunload') {
 6018: 		$on_unload.=$attr_ref->{$key}.';';
 6019: 		delete($attr_ref->{$key});
 6020: 	    }
 6021: 	}
 6022: 	$attr_ref->{'onload'}  = $on_load;
 6023: 	$attr_ref->{'onunload'}= $on_unload;
 6024:     }
 6025: 
 6026:     my $attr_string;
 6027:     foreach my $attr (sort(keys(%$attr_ref))) {
 6028: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6029:     }
 6030:     return $attr_string;
 6031: }
 6032: 
 6033: 
 6034: ###############################################
 6035: ###############################################
 6036: 
 6037: =pod
 6038: 
 6039: =item * &endbodytag()
 6040: 
 6041: Returns a uniform footer for LON-CAPA web pages.
 6042: 
 6043: Inputs: 1 - optional reference to an args hash
 6044: If in the hash, key for noredirectlink has a value which evaluates to true,
 6045: a 'Continue' link is not displayed if the page contains an
 6046: internal redirect in the <head></head> section,
 6047: i.e., $env{'internal.head.redirect'} exists   
 6048: 
 6049: =cut
 6050: 
 6051: sub endbodytag {
 6052:     my ($args) = @_;
 6053:     my $endbodytag;
 6054:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6055:         $endbodytag='</body>';
 6056:     }
 6057:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6058:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6059: 	    $endbodytag=
 6060: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6061: 	        &mt('Continue').'</a>'.
 6062: 	        $endbodytag;
 6063:         }
 6064:     }
 6065:     return $endbodytag;
 6066: }
 6067: 
 6068: =pod
 6069: 
 6070: =item * &standard_css()
 6071: 
 6072: Returns a style sheet
 6073: 
 6074: Inputs: (all optional)
 6075:             domain         -> force to color decorate a page for a specific
 6076:                                domain
 6077:             function       -> force usage of a specific rolish color scheme
 6078:             bgcolor        -> override the default page bgcolor
 6079: 
 6080: =cut
 6081: 
 6082: sub standard_css {
 6083:     my ($function,$domain,$bgcolor) = @_;
 6084:     $function  = &get_users_function() if (!$function);
 6085:     my $img    = &designparm($function.'.img',   $domain);
 6086:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6087:     my $font   = &designparm($function.'.font',  $domain);
 6088:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6089: #second colour for later usage
 6090:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6091:     my $pgbg_or_bgcolor =
 6092: 	         $bgcolor ||
 6093: 	         &designparm($function.'.pgbg',  $domain);
 6094:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6095:     my $alink  = &designparm($function.'.alink', $domain);
 6096:     my $vlink  = &designparm($function.'.vlink', $domain);
 6097:     my $link   = &designparm($function.'.link',  $domain);
 6098: 
 6099:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6100:     my $mono                 = 'monospace';
 6101:     my $data_table_head      = $sidebg;
 6102:     my $data_table_light     = '#FAFAFA';
 6103:     my $data_table_dark      = '#E0E0E0';
 6104:     my $data_table_darker    = '#CCCCCC';
 6105:     my $data_table_highlight = '#FFFF00';
 6106:     my $mail_new             = '#FFBB77';
 6107:     my $mail_new_hover       = '#DD9955';
 6108:     my $mail_read            = '#BBBB77';
 6109:     my $mail_read_hover      = '#999944';
 6110:     my $mail_replied         = '#AAAA88';
 6111:     my $mail_replied_hover   = '#888855';
 6112:     my $mail_other           = '#99BBBB';
 6113:     my $mail_other_hover     = '#669999';
 6114:     my $table_header         = '#DDDDDD';
 6115:     my $feedback_link_bg     = '#BBBBBB';
 6116:     my $lg_border_color      = '#C8C8C8';
 6117:     my $button_hover         = '#BF2317';
 6118: 
 6119:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6120:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6121:                                              : '0 3px 0 4px';
 6122: 
 6123: 
 6124:     return <<END;
 6125: 
 6126: /* needed for iframe to allow 100% height in FF */
 6127: body, html { 
 6128:     margin: 0;
 6129:     padding: 0 0.5%;
 6130:     height: 99%; /* to avoid scrollbars */
 6131: }
 6132: 
 6133: body {
 6134:   font-family: $sans;
 6135:   line-height:130%;
 6136:   font-size:0.83em;
 6137:   color:$font;
 6138: }
 6139: 
 6140: a:focus,
 6141: a:focus img {
 6142:   color: red;
 6143: }
 6144: 
 6145: form, .inline {
 6146:   display: inline;
 6147: }
 6148: 
 6149: .LC_right {
 6150:   text-align:right;
 6151: }
 6152: 
 6153: .LC_middle {
 6154:   vertical-align:middle;
 6155: }
 6156: 
 6157: .LC_floatleft {
 6158:   float: left;
 6159: }
 6160: 
 6161: .LC_floatright {
 6162:   float: right;
 6163: }
 6164: 
 6165: .LC_400Box {
 6166:   width:400px;
 6167: }
 6168: 
 6169: .LC_iframecontainer {
 6170:     width: 98%;
 6171:     margin: 0;
 6172:     position: fixed;
 6173:     top: 8.5em;
 6174:     bottom: 0;
 6175: }
 6176: 
 6177: .LC_iframecontainer iframe{
 6178:     border: none;
 6179:     width: 100%;
 6180:     height: 100%;
 6181: }
 6182: 
 6183: .LC_filename {
 6184:   font-family: $mono;
 6185:   white-space:pre;
 6186:   font-size: 120%;
 6187: }
 6188: 
 6189: .LC_fileicon {
 6190:   border: none;
 6191:   height: 1.3em;
 6192:   vertical-align: text-bottom;
 6193:   margin-right: 0.3em;
 6194:   text-decoration:none;
 6195: }
 6196: 
 6197: .LC_setting {
 6198:   text-decoration:underline;
 6199: }
 6200: 
 6201: .LC_error {
 6202:   color: red;
 6203: }
 6204: 
 6205: .LC_warning {
 6206:   color: darkorange;
 6207: }
 6208: 
 6209: .LC_diff_removed {
 6210:   color: red;
 6211: }
 6212: 
 6213: .LC_info,
 6214: .LC_success,
 6215: .LC_diff_added {
 6216:   color: green;
 6217: }
 6218: 
 6219: div.LC_confirm_box {
 6220:   background-color: #FAFAFA;
 6221:   border: 1px solid $lg_border_color;
 6222:   margin-right: 0;
 6223:   padding: 5px;
 6224: }
 6225: 
 6226: div.LC_confirm_box .LC_error img,
 6227: div.LC_confirm_box .LC_success img {
 6228:   vertical-align: middle;
 6229: }
 6230: 
 6231: .LC_maxwidth {
 6232:   max-width: 100%;
 6233:   height: auto;
 6234: }
 6235: 
 6236: .LC_textsize_mobile {
 6237:   \@media only screen and (max-device-width: 480px) {
 6238:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6239:   }
 6240: }
 6241: 
 6242: .LC_icon {
 6243:   border: none;
 6244:   vertical-align: middle;
 6245: }
 6246: 
 6247: .LC_docs_spacer {
 6248:   width: 25px;
 6249:   height: 1px;
 6250:   border: none;
 6251: }
 6252: 
 6253: .LC_internal_info {
 6254:   color: #999999;
 6255: }
 6256: 
 6257: .LC_discussion {
 6258:   background: $data_table_dark;
 6259:   border: 1px solid black;
 6260:   margin: 2px;
 6261: }
 6262: 
 6263: .LC_disc_action_left {
 6264:   background: $sidebg;
 6265:   text-align: left;
 6266:   padding: 4px;
 6267:   margin: 2px;
 6268: }
 6269: 
 6270: .LC_disc_action_right {
 6271:   background: $sidebg;
 6272:   text-align: right;
 6273:   padding: 4px;
 6274:   margin: 2px;
 6275: }
 6276: 
 6277: .LC_disc_new_item {
 6278:   background: white;
 6279:   border: 2px solid red;
 6280:   margin: 4px;
 6281:   padding: 4px;
 6282: }
 6283: 
 6284: .LC_disc_old_item {
 6285:   background: white;
 6286:   margin: 4px;
 6287:   padding: 4px;
 6288: }
 6289: 
 6290: table.LC_pastsubmission {
 6291:   border: 1px solid black;
 6292:   margin: 2px;
 6293: }
 6294: 
 6295: table#LC_menubuttons {
 6296:   width: 100%;
 6297:   background: $pgbg;
 6298:   border: 2px;
 6299:   border-collapse: separate;
 6300:   padding: 0;
 6301: }
 6302: 
 6303: table#LC_title_bar a {
 6304:   color: $fontmenu;
 6305: }
 6306: 
 6307: table#LC_title_bar {
 6308:   clear: both;
 6309:   display: none;
 6310: }
 6311: 
 6312: table#LC_title_bar,
 6313: table.LC_breadcrumbs, /* obsolete? */
 6314: table#LC_title_bar.LC_with_remote {
 6315:   width: 100%;
 6316:   border-color: $pgbg;
 6317:   border-style: solid;
 6318:   border-width: $border;
 6319:   background: $pgbg;
 6320:   color: $fontmenu;
 6321:   border-collapse: collapse;
 6322:   padding: 0;
 6323:   margin: 0;
 6324: }
 6325: 
 6326: ul.LC_breadcrumb_tools_outerlist {
 6327:     margin: 0;
 6328:     padding: 0;
 6329:     position: relative;
 6330:     list-style: none;
 6331: }
 6332: ul.LC_breadcrumb_tools_outerlist li {
 6333:     display: inline;
 6334: }
 6335: 
 6336: .LC_breadcrumb_tools_navigation {
 6337:     padding: 0;
 6338:     margin: 0;
 6339:     float: left;
 6340: }
 6341: .LC_breadcrumb_tools_tools {
 6342:     padding: 0;
 6343:     margin: 0;
 6344:     float: right;
 6345: }
 6346: 
 6347: .LC_placement_prog {
 6348:     padding-right: 20px;
 6349:     font-weight: bold;
 6350:     font-size: 90%;
 6351: }
 6352: 
 6353: table#LC_title_bar td {
 6354:   background: $tabbg;
 6355: }
 6356: 
 6357: table#LC_menubuttons img {
 6358:   border: none;
 6359: }
 6360: 
 6361: .LC_breadcrumbs_component {
 6362:   float: right;
 6363:   margin: 0 1em;
 6364: }
 6365: .LC_breadcrumbs_component img {
 6366:   vertical-align: middle;
 6367: }
 6368: 
 6369: .LC_breadcrumbs_hoverable {
 6370:   background: $sidebg;
 6371: }
 6372: 
 6373: td.LC_table_cell_checkbox {
 6374:   text-align: center;
 6375: }
 6376: 
 6377: .LC_fontsize_small {
 6378:   font-size: 70%;
 6379: }
 6380: 
 6381: #LC_breadcrumbs {
 6382:   clear:both;
 6383:   background: $sidebg;
 6384:   border-bottom: 1px solid $lg_border_color;
 6385:   line-height: 2.5em;
 6386:   overflow: hidden;
 6387:   margin: 0;
 6388:   padding: 0;
 6389:   text-align: left;
 6390: }
 6391: 
 6392: .LC_head_subbox, .LC_actionbox {
 6393:   clear:both;
 6394:   background: #F8F8F8; /* $sidebg; */
 6395:   border: 1px solid $sidebg;
 6396:   margin: 0 0 10px 0;
 6397:   padding: 3px;
 6398:   text-align: left;
 6399: }
 6400: 
 6401: .LC_fontsize_medium {
 6402:   font-size: 85%;
 6403: }
 6404: 
 6405: .LC_fontsize_large {
 6406:   font-size: 120%;
 6407: }
 6408: 
 6409: .LC_menubuttons_inline_text {
 6410:   color: $font;
 6411:   font-size: 90%;
 6412:   padding-left:3px;
 6413: }
 6414: 
 6415: .LC_menubuttons_inline_text img{
 6416:   vertical-align: middle;
 6417: }
 6418: 
 6419: li.LC_menubuttons_inline_text img {
 6420:   cursor:pointer;
 6421:   text-decoration: none;
 6422: }
 6423: 
 6424: .LC_menubuttons_link {
 6425:   text-decoration: none;
 6426: }
 6427: 
 6428: .LC_menubuttons_category {
 6429:   color: $font;
 6430:   background: $pgbg;
 6431:   font-size: larger;
 6432:   font-weight: bold;
 6433: }
 6434: 
 6435: td.LC_menubuttons_text {
 6436:   color: $font;
 6437: }
 6438: 
 6439: .LC_current_location {
 6440:   background: $tabbg;
 6441: }
 6442: 
 6443: table.LC_data_table {
 6444:   border: 1px solid #000000;
 6445:   border-collapse: separate;
 6446:   border-spacing: 1px;
 6447:   background: $pgbg;
 6448: }
 6449: 
 6450: .LC_data_table_dense {
 6451:   font-size: small;
 6452: }
 6453: 
 6454: table.LC_nested_outer {
 6455:   border: 1px solid #000000;
 6456:   border-collapse: collapse;
 6457:   border-spacing: 0;
 6458:   width: 100%;
 6459: }
 6460: 
 6461: table.LC_innerpickbox,
 6462: table.LC_nested {
 6463:   border: none;
 6464:   border-collapse: collapse;
 6465:   border-spacing: 0;
 6466:   width: 100%;
 6467: }
 6468: 
 6469: table.LC_data_table tr th,
 6470: table.LC_calendar tr th,
 6471: table.LC_prior_tries tr th,
 6472: table.LC_innerpickbox tr th {
 6473:   font-weight: bold;
 6474:   background-color: $data_table_head;
 6475:   color:$fontmenu;
 6476:   font-size:90%;
 6477: }
 6478: 
 6479: table.LC_innerpickbox tr th,
 6480: table.LC_innerpickbox tr td {
 6481:   vertical-align: top;
 6482: }
 6483: 
 6484: table.LC_data_table tr.LC_info_row > td {
 6485:   background-color: #CCCCCC;
 6486:   font-weight: bold;
 6487:   text-align: left;
 6488: }
 6489: 
 6490: table.LC_data_table tr.LC_odd_row > td {
 6491:   background-color: $data_table_light;
 6492:   padding: 2px;
 6493:   vertical-align: top;
 6494: }
 6495: 
 6496: table.LC_pick_box tr > td.LC_odd_row {
 6497:   background-color: $data_table_light;
 6498:   vertical-align: top;
 6499: }
 6500: 
 6501: table.LC_data_table tr.LC_even_row > td {
 6502:   background-color: $data_table_dark;
 6503:   padding: 2px;
 6504:   vertical-align: top;
 6505: }
 6506: 
 6507: table.LC_pick_box tr > td.LC_even_row {
 6508:   background-color: $data_table_dark;
 6509:   vertical-align: top;
 6510: }
 6511: 
 6512: table.LC_data_table tr.LC_data_table_highlight td {
 6513:   background-color: $data_table_darker;
 6514: }
 6515: 
 6516: table.LC_data_table tr td.LC_leftcol_header {
 6517:   background-color: $data_table_head;
 6518:   font-weight: bold;
 6519: }
 6520: 
 6521: table.LC_data_table tr.LC_empty_row td,
 6522: table.LC_nested tr.LC_empty_row td {
 6523:   font-weight: bold;
 6524:   font-style: italic;
 6525:   text-align: center;
 6526:   padding: 8px;
 6527: }
 6528: 
 6529: table.LC_data_table tr.LC_empty_row td,
 6530: table.LC_data_table tr.LC_footer_row td {
 6531:   background-color: $sidebg;
 6532: }
 6533: 
 6534: table.LC_nested tr.LC_empty_row td {
 6535:   background-color: #FFFFFF;
 6536: }
 6537: 
 6538: table.LC_caption {
 6539: }
 6540: 
 6541: table.LC_nested tr.LC_empty_row td {
 6542:   padding: 4ex
 6543: }
 6544: 
 6545: table.LC_nested_outer tr th {
 6546:   font-weight: bold;
 6547:   color:$fontmenu;
 6548:   background-color: $data_table_head;
 6549:   font-size: small;
 6550:   border-bottom: 1px solid #000000;
 6551: }
 6552: 
 6553: table.LC_nested_outer tr td.LC_subheader {
 6554:   background-color: $data_table_head;
 6555:   font-weight: bold;
 6556:   font-size: small;
 6557:   border-bottom: 1px solid #000000;
 6558:   text-align: right;
 6559: }
 6560: 
 6561: table.LC_nested tr.LC_info_row td {
 6562:   background-color: #CCCCCC;
 6563:   font-weight: bold;
 6564:   font-size: small;
 6565:   text-align: center;
 6566: }
 6567: 
 6568: table.LC_nested tr.LC_info_row td.LC_left_item,
 6569: table.LC_nested_outer tr th.LC_left_item {
 6570:   text-align: left;
 6571: }
 6572: 
 6573: table.LC_nested td {
 6574:   background-color: #FFFFFF;
 6575:   font-size: small;
 6576: }
 6577: 
 6578: table.LC_nested_outer tr th.LC_right_item,
 6579: table.LC_nested tr.LC_info_row td.LC_right_item,
 6580: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6581: table.LC_nested tr td.LC_right_item {
 6582:   text-align: right;
 6583: }
 6584: 
 6585: table.LC_nested tr.LC_odd_row td {
 6586:   background-color: #EEEEEE;
 6587: }
 6588: 
 6589: table.LC_createuser {
 6590: }
 6591: 
 6592: table.LC_createuser tr.LC_section_row td {
 6593:   font-size: small;
 6594: }
 6595: 
 6596: table.LC_createuser tr.LC_info_row td  {
 6597:   background-color: #CCCCCC;
 6598:   font-weight: bold;
 6599:   text-align: center;
 6600: }
 6601: 
 6602: table.LC_calendar {
 6603:   border: 1px solid #000000;
 6604:   border-collapse: collapse;
 6605:   width: 98%;
 6606: }
 6607: 
 6608: table.LC_calendar_pickdate {
 6609:   font-size: xx-small;
 6610: }
 6611: 
 6612: table.LC_calendar tr td {
 6613:   border: 1px solid #000000;
 6614:   vertical-align: top;
 6615:   width: 14%;
 6616: }
 6617: 
 6618: table.LC_calendar tr td.LC_calendar_day_empty {
 6619:   background-color: $data_table_dark;
 6620: }
 6621: 
 6622: table.LC_calendar tr td.LC_calendar_day_current {
 6623:   background-color: $data_table_highlight;
 6624: }
 6625: 
 6626: table.LC_data_table tr td.LC_mail_new {
 6627:   background-color: $mail_new;
 6628: }
 6629: 
 6630: table.LC_data_table tr.LC_mail_new:hover {
 6631:   background-color: $mail_new_hover;
 6632: }
 6633: 
 6634: table.LC_data_table tr td.LC_mail_read {
 6635:   background-color: $mail_read;
 6636: }
 6637: 
 6638: /*
 6639: table.LC_data_table tr.LC_mail_read:hover {
 6640:   background-color: $mail_read_hover;
 6641: }
 6642: */
 6643: 
 6644: table.LC_data_table tr td.LC_mail_replied {
 6645:   background-color: $mail_replied;
 6646: }
 6647: 
 6648: /*
 6649: table.LC_data_table tr.LC_mail_replied:hover {
 6650:   background-color: $mail_replied_hover;
 6651: }
 6652: */
 6653: 
 6654: table.LC_data_table tr td.LC_mail_other {
 6655:   background-color: $mail_other;
 6656: }
 6657: 
 6658: /*
 6659: table.LC_data_table tr.LC_mail_other:hover {
 6660:   background-color: $mail_other_hover;
 6661: }
 6662: */
 6663: 
 6664: table.LC_data_table tr > td.LC_browser_file,
 6665: table.LC_data_table tr > td.LC_browser_file_published {
 6666:   background: #AAEE77;
 6667: }
 6668: 
 6669: table.LC_data_table tr > td.LC_browser_file_locked,
 6670: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6671:   background: #FFAA99;
 6672: }
 6673: 
 6674: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6675:   background: #888888;
 6676: }
 6677: 
 6678: table.LC_data_table tr > td.LC_browser_file_modified,
 6679: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6680:   background: #F8F866;
 6681: }
 6682: 
 6683: table.LC_data_table tr.LC_browser_folder > td {
 6684:   background: #E0E8FF;
 6685: }
 6686: 
 6687: table.LC_data_table tr > td.LC_roles_is {
 6688:   /* background: #77FF77; */
 6689: }
 6690: 
 6691: table.LC_data_table tr > td.LC_roles_future {
 6692:   border-right: 8px solid #FFFF77;
 6693: }
 6694: 
 6695: table.LC_data_table tr > td.LC_roles_will {
 6696:   border-right: 8px solid #FFAA77;
 6697: }
 6698: 
 6699: table.LC_data_table tr > td.LC_roles_expired {
 6700:   border-right: 8px solid #FF7777;
 6701: }
 6702: 
 6703: table.LC_data_table tr > td.LC_roles_will_not {
 6704:   border-right: 8px solid #AAFF77;
 6705: }
 6706: 
 6707: table.LC_data_table tr > td.LC_roles_selected {
 6708:   border-right: 8px solid #11CC55;
 6709: }
 6710: 
 6711: span.LC_current_location {
 6712:   font-size:larger;
 6713:   background: $pgbg;
 6714: }
 6715: 
 6716: span.LC_current_nav_location {
 6717:   font-weight:bold;
 6718:   background: $sidebg;
 6719: }
 6720: 
 6721: span.LC_parm_menu_item {
 6722:   font-size: larger;
 6723: }
 6724: 
 6725: span.LC_parm_scope_all {
 6726:   color: red;
 6727: }
 6728: 
 6729: span.LC_parm_scope_folder {
 6730:   color: green;
 6731: }
 6732: 
 6733: span.LC_parm_scope_resource {
 6734:   color: orange;
 6735: }
 6736: 
 6737: span.LC_parm_part {
 6738:   color: blue;
 6739: }
 6740: 
 6741: span.LC_parm_folder,
 6742: span.LC_parm_symb {
 6743:   font-size: x-small;
 6744:   font-family: $mono;
 6745:   color: #AAAAAA;
 6746: }
 6747: 
 6748: ul.LC_parm_parmlist li {
 6749:   display: inline-block;
 6750:   padding: 0.3em 0.8em;
 6751:   vertical-align: top;
 6752:   width: 150px;
 6753:   border-top:1px solid $lg_border_color;
 6754: }
 6755: 
 6756: td.LC_parm_overview_level_menu,
 6757: td.LC_parm_overview_map_menu,
 6758: td.LC_parm_overview_parm_selectors,
 6759: td.LC_parm_overview_restrictions  {
 6760:   border: 1px solid black;
 6761:   border-collapse: collapse;
 6762: }
 6763: 
 6764: table.LC_parm_overview_restrictions td {
 6765:   border-width: 1px 4px 1px 4px;
 6766:   border-style: solid;
 6767:   border-color: $pgbg;
 6768:   text-align: center;
 6769: }
 6770: 
 6771: table.LC_parm_overview_restrictions th {
 6772:   background: $tabbg;
 6773:   border-width: 1px 4px 1px 4px;
 6774:   border-style: solid;
 6775:   border-color: $pgbg;
 6776: }
 6777: 
 6778: table#LC_helpmenu {
 6779:   border: none;
 6780:   height: 55px;
 6781:   border-spacing: 0;
 6782: }
 6783: 
 6784: table#LC_helpmenu fieldset legend {
 6785:   font-size: larger;
 6786: }
 6787: 
 6788: table#LC_helpmenu_links {
 6789:   width: 100%;
 6790:   border: 1px solid black;
 6791:   background: $pgbg;
 6792:   padding: 0;
 6793:   border-spacing: 1px;
 6794: }
 6795: 
 6796: table#LC_helpmenu_links tr td {
 6797:   padding: 1px;
 6798:   background: $tabbg;
 6799:   text-align: center;
 6800:   font-weight: bold;
 6801: }
 6802: 
 6803: table#LC_helpmenu_links a:link,
 6804: table#LC_helpmenu_links a:visited,
 6805: table#LC_helpmenu_links a:active {
 6806:   text-decoration: none;
 6807:   color: $font;
 6808: }
 6809: 
 6810: table#LC_helpmenu_links a:hover {
 6811:   text-decoration: underline;
 6812:   color: $vlink;
 6813: }
 6814: 
 6815: .LC_chrt_popup_exists {
 6816:   border: 1px solid #339933;
 6817:   margin: -1px;
 6818: }
 6819: 
 6820: .LC_chrt_popup_up {
 6821:   border: 1px solid yellow;
 6822:   margin: -1px;
 6823: }
 6824: 
 6825: .LC_chrt_popup {
 6826:   border: 1px solid #8888FF;
 6827:   background: #CCCCFF;
 6828: }
 6829: 
 6830: table.LC_pick_box {
 6831:   border-collapse: separate;
 6832:   background: white;
 6833:   border: 1px solid black;
 6834:   border-spacing: 1px;
 6835: }
 6836: 
 6837: table.LC_pick_box td.LC_pick_box_title {
 6838:   background: $sidebg;
 6839:   font-weight: bold;
 6840:   text-align: left;
 6841:   vertical-align: top;
 6842:   width: 184px;
 6843:   padding: 8px;
 6844: }
 6845: 
 6846: table.LC_pick_box td.LC_pick_box_value {
 6847:   text-align: left;
 6848:   padding: 8px;
 6849: }
 6850: 
 6851: table.LC_pick_box td.LC_pick_box_select {
 6852:   text-align: left;
 6853:   padding: 8px;
 6854: }
 6855: 
 6856: table.LC_pick_box td.LC_pick_box_separator {
 6857:   padding: 0;
 6858:   height: 1px;
 6859:   background: black;
 6860: }
 6861: 
 6862: table.LC_pick_box td.LC_pick_box_submit {
 6863:   text-align: right;
 6864: }
 6865: 
 6866: table.LC_pick_box td.LC_evenrow_value {
 6867:   text-align: left;
 6868:   padding: 8px;
 6869:   background-color: $data_table_light;
 6870: }
 6871: 
 6872: table.LC_pick_box td.LC_oddrow_value {
 6873:   text-align: left;
 6874:   padding: 8px;
 6875:   background-color: $data_table_light;
 6876: }
 6877: 
 6878: span.LC_helpform_receipt_cat {
 6879:   font-weight: bold;
 6880: }
 6881: 
 6882: table.LC_group_priv_box {
 6883:   background: white;
 6884:   border: 1px solid black;
 6885:   border-spacing: 1px;
 6886: }
 6887: 
 6888: table.LC_group_priv_box td.LC_pick_box_title {
 6889:   background: $tabbg;
 6890:   font-weight: bold;
 6891:   text-align: right;
 6892:   width: 184px;
 6893: }
 6894: 
 6895: table.LC_group_priv_box td.LC_groups_fixed {
 6896:   background: $data_table_light;
 6897:   text-align: center;
 6898: }
 6899: 
 6900: table.LC_group_priv_box td.LC_groups_optional {
 6901:   background: $data_table_dark;
 6902:   text-align: center;
 6903: }
 6904: 
 6905: table.LC_group_priv_box td.LC_groups_functionality {
 6906:   background: $data_table_darker;
 6907:   text-align: center;
 6908:   font-weight: bold;
 6909: }
 6910: 
 6911: table.LC_group_priv td {
 6912:   text-align: left;
 6913:   padding: 0;
 6914: }
 6915: 
 6916: .LC_navbuttons {
 6917:   margin: 2ex 0ex 2ex 0ex;
 6918: }
 6919: 
 6920: .LC_topic_bar {
 6921:   font-weight: bold;
 6922:   background: $tabbg;
 6923:   margin: 1em 0em 1em 2em;
 6924:   padding: 3px;
 6925:   font-size: 1.2em;
 6926: }
 6927: 
 6928: .LC_topic_bar span {
 6929:   left: 0.5em;
 6930:   position: absolute;
 6931:   vertical-align: middle;
 6932:   font-size: 1.2em;
 6933: }
 6934: 
 6935: table.LC_course_group_status {
 6936:   margin: 20px;
 6937: }
 6938: 
 6939: table.LC_status_selector td {
 6940:   vertical-align: top;
 6941:   text-align: center;
 6942:   padding: 4px;
 6943: }
 6944: 
 6945: div.LC_feedback_link {
 6946:   clear: both;
 6947:   background: $sidebg;
 6948:   width: 100%;
 6949:   padding-bottom: 10px;
 6950:   border: 1px $tabbg solid;
 6951:   height: 22px;
 6952:   line-height: 22px;
 6953:   padding-top: 5px;
 6954: }
 6955: 
 6956: div.LC_feedback_link img {
 6957:   height: 22px;
 6958:   vertical-align:middle;
 6959: }
 6960: 
 6961: div.LC_feedback_link a {
 6962:   text-decoration: none;
 6963: }
 6964: 
 6965: div.LC_comblock {
 6966:   display:inline;
 6967:   color:$font;
 6968:   font-size:90%;
 6969: }
 6970: 
 6971: div.LC_feedback_link div.LC_comblock {
 6972:   padding-left:5px;
 6973: }
 6974: 
 6975: div.LC_feedback_link div.LC_comblock a {
 6976:   color:$font;
 6977: }
 6978: 
 6979: span.LC_feedback_link {
 6980:   /* background: $feedback_link_bg; */
 6981:   font-size: larger;
 6982: }
 6983: 
 6984: span.LC_message_link {
 6985:   /* background: $feedback_link_bg; */
 6986:   font-size: larger;
 6987:   position: absolute;
 6988:   right: 1em;
 6989: }
 6990: 
 6991: table.LC_prior_tries {
 6992:   border: 1px solid #000000;
 6993:   border-collapse: separate;
 6994:   border-spacing: 1px;
 6995: }
 6996: 
 6997: table.LC_prior_tries td {
 6998:   padding: 2px;
 6999: }
 7000: 
 7001: .LC_answer_correct {
 7002:   background: lightgreen;
 7003:   color: darkgreen;
 7004:   padding: 6px;
 7005: }
 7006: 
 7007: .LC_answer_charged_try {
 7008:   background: #FFAAAA;
 7009:   color: darkred;
 7010:   padding: 6px;
 7011: }
 7012: 
 7013: .LC_answer_not_charged_try,
 7014: .LC_answer_no_grade,
 7015: .LC_answer_late {
 7016:   background: lightyellow;
 7017:   color: black;
 7018:   padding: 6px;
 7019: }
 7020: 
 7021: .LC_answer_previous {
 7022:   background: lightblue;
 7023:   color: darkblue;
 7024:   padding: 6px;
 7025: }
 7026: 
 7027: .LC_answer_no_message {
 7028:   background: #FFFFFF;
 7029:   color: black;
 7030:   padding: 6px;
 7031: }
 7032: 
 7033: .LC_answer_unknown {
 7034:   background: orange;
 7035:   color: black;
 7036:   padding: 6px;
 7037: }
 7038: 
 7039: span.LC_prior_numerical,
 7040: span.LC_prior_string,
 7041: span.LC_prior_custom,
 7042: span.LC_prior_reaction,
 7043: span.LC_prior_math {
 7044:   font-family: $mono;
 7045:   white-space: pre;
 7046: }
 7047: 
 7048: span.LC_prior_string {
 7049:   font-family: $mono;
 7050:   white-space: pre;
 7051: }
 7052: 
 7053: table.LC_prior_option {
 7054:   width: 100%;
 7055:   border-collapse: collapse;
 7056: }
 7057: 
 7058: table.LC_prior_rank,
 7059: table.LC_prior_match {
 7060:   border-collapse: collapse;
 7061: }
 7062: 
 7063: table.LC_prior_option tr td,
 7064: table.LC_prior_rank tr td,
 7065: table.LC_prior_match tr td {
 7066:   border: 1px solid #000000;
 7067: }
 7068: 
 7069: .LC_nobreak {
 7070:   white-space: nowrap;
 7071: }
 7072: 
 7073: span.LC_cusr_emph {
 7074:   font-style: italic;
 7075: }
 7076: 
 7077: span.LC_cusr_subheading {
 7078:   font-weight: normal;
 7079:   font-size: 85%;
 7080: }
 7081: 
 7082: div.LC_docs_entry_move {
 7083:   border: 1px solid #BBBBBB;
 7084:   background: #DDDDDD;
 7085:   width: 22px;
 7086:   padding: 1px;
 7087:   margin: 0;
 7088: }
 7089: 
 7090: table.LC_data_table tr > td.LC_docs_entry_commands,
 7091: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7092:   font-size: x-small;
 7093: }
 7094: 
 7095: .LC_docs_entry_parameter {
 7096:   white-space: nowrap;
 7097: }
 7098: 
 7099: .LC_docs_copy {
 7100:   color: #000099;
 7101: }
 7102: 
 7103: .LC_docs_cut {
 7104:   color: #550044;
 7105: }
 7106: 
 7107: .LC_docs_rename {
 7108:   color: #009900;
 7109: }
 7110: 
 7111: .LC_docs_remove {
 7112:   color: #990000;
 7113: }
 7114: 
 7115: .LC_docs_reinit_warn,
 7116: .LC_docs_ext_edit {
 7117:   font-size: x-small;
 7118: }
 7119: 
 7120: table.LC_docs_adddocs td,
 7121: table.LC_docs_adddocs th {
 7122:   border: 1px solid #BBBBBB;
 7123:   padding: 4px;
 7124:   background: #DDDDDD;
 7125: }
 7126: 
 7127: table.LC_sty_begin {
 7128:   background: #BBFFBB;
 7129: }
 7130: 
 7131: table.LC_sty_end {
 7132:   background: #FFBBBB;
 7133: }
 7134: 
 7135: table.LC_double_column {
 7136:   border-width: 0;
 7137:   border-collapse: collapse;
 7138:   width: 100%;
 7139:   padding: 2px;
 7140: }
 7141: 
 7142: table.LC_double_column tr td.LC_left_col {
 7143:   top: 2px;
 7144:   left: 2px;
 7145:   width: 47%;
 7146:   vertical-align: top;
 7147: }
 7148: 
 7149: table.LC_double_column tr td.LC_right_col {
 7150:   top: 2px;
 7151:   right: 2px;
 7152:   width: 47%;
 7153:   vertical-align: top;
 7154: }
 7155: 
 7156: div.LC_left_float {
 7157:   float: left;
 7158:   padding-right: 5%;
 7159:   padding-bottom: 4px;
 7160: }
 7161: 
 7162: div.LC_clear_float_header {
 7163:   padding-bottom: 2px;
 7164: }
 7165: 
 7166: div.LC_clear_float_footer {
 7167:   padding-top: 10px;
 7168:   clear: both;
 7169: }
 7170: 
 7171: div.LC_grade_show_user {
 7172: /*  border-left: 5px solid $sidebg; */
 7173:   border-top: 5px solid #000000;
 7174:   margin: 50px 0 0 0;
 7175:   padding: 15px 0 5px 10px;
 7176: }
 7177: 
 7178: div.LC_grade_show_user_odd_row {
 7179: /*  border-left: 5px solid #000000; */
 7180: }
 7181: 
 7182: div.LC_grade_show_user div.LC_Box {
 7183:   margin-right: 50px;
 7184: }
 7185: 
 7186: div.LC_grade_submissions,
 7187: div.LC_grade_message_center,
 7188: div.LC_grade_info_links {
 7189:   margin: 5px;
 7190:   width: 99%;
 7191:   background: #FFFFFF;
 7192: }
 7193: 
 7194: div.LC_grade_submissions_header,
 7195: div.LC_grade_message_center_header {
 7196:   font-weight: bold;
 7197:   font-size: large;
 7198: }
 7199: 
 7200: div.LC_grade_submissions_body,
 7201: div.LC_grade_message_center_body {
 7202:   border: 1px solid black;
 7203:   width: 99%;
 7204:   background: #FFFFFF;
 7205: }
 7206: 
 7207: table.LC_scantron_action {
 7208:   width: 100%;
 7209: }
 7210: 
 7211: table.LC_scantron_action tr th {
 7212:   font-weight:bold;
 7213:   font-style:normal;
 7214: }
 7215: 
 7216: .LC_edit_problem_header,
 7217: div.LC_edit_problem_footer {
 7218:   font-weight: normal;
 7219:   font-size:  medium;
 7220:   margin: 2px;
 7221:   background-color: $sidebg;
 7222: }
 7223: 
 7224: div.LC_edit_problem_header,
 7225: div.LC_edit_problem_header div,
 7226: div.LC_edit_problem_footer,
 7227: div.LC_edit_problem_footer div,
 7228: div.LC_edit_problem_editxml_header,
 7229: div.LC_edit_problem_editxml_header div {
 7230:   z-index: 100;
 7231: }
 7232: 
 7233: div.LC_edit_problem_header_title {
 7234:   font-weight: bold;
 7235:   font-size: larger;
 7236:   background: $tabbg;
 7237:   padding: 3px;
 7238:   margin: 0 0 5px 0;
 7239: }
 7240: 
 7241: table.LC_edit_problem_header_title {
 7242:   width: 100%;
 7243:   background: $tabbg;
 7244: }
 7245: 
 7246: div.LC_edit_actionbar {
 7247:     background-color: $sidebg;
 7248:     margin: 0;
 7249:     padding: 0;
 7250:     line-height: 200%;
 7251: }
 7252: 
 7253: div.LC_edit_actionbar div{
 7254:     padding: 0;
 7255:     margin: 0;
 7256:     display: inline-block;
 7257: }
 7258: 
 7259: .LC_edit_opt {
 7260:   padding-left: 1em;
 7261:   white-space: nowrap;
 7262: }
 7263: 
 7264: .LC_edit_problem_latexhelper{
 7265:     text-align: right;
 7266: }
 7267: 
 7268: #LC_edit_problem_colorful div{
 7269:     margin-left: 40px;
 7270: }
 7271: 
 7272: #LC_edit_problem_codemirror div{
 7273:     margin-left: 0px;
 7274: }
 7275: 
 7276: img.stift {
 7277:   border-width: 0;
 7278:   vertical-align: middle;
 7279: }
 7280: 
 7281: table td.LC_mainmenu_col_fieldset {
 7282:   vertical-align: top;
 7283: }
 7284: 
 7285: div.LC_createcourse {
 7286:   margin: 10px 10px 10px 10px;
 7287: }
 7288: 
 7289: .LC_dccid {
 7290:   float: right;
 7291:   margin: 0.2em 0 0 0;
 7292:   padding: 0;
 7293:   font-size: 90%;
 7294:   display:none;
 7295: }
 7296: 
 7297: ol.LC_primary_menu a:hover,
 7298: ol#LC_MenuBreadcrumbs a:hover,
 7299: ol#LC_PathBreadcrumbs a:hover,
 7300: ul#LC_secondary_menu a:hover,
 7301: .LC_FormSectionClearButton input:hover
 7302: ul.LC_TabContent   li:hover a {
 7303:   color:$button_hover;
 7304:   text-decoration:none;
 7305: }
 7306: 
 7307: h1 {
 7308:   padding: 0;
 7309:   line-height:130%;
 7310: }
 7311: 
 7312: h2,
 7313: h3,
 7314: h4,
 7315: h5,
 7316: h6 {
 7317:   margin: 5px 0 5px 0;
 7318:   padding: 0;
 7319:   line-height:130%;
 7320: }
 7321: 
 7322: .LC_hcell {
 7323:   padding:3px 15px 3px 15px;
 7324:   margin: 0;
 7325:   background-color:$tabbg;
 7326:   color:$fontmenu;
 7327:   border-bottom:solid 1px $lg_border_color;
 7328: }
 7329: 
 7330: .LC_Box > .LC_hcell {
 7331:   margin: 0 -10px 10px -10px;
 7332: }
 7333: 
 7334: .LC_noBorder {
 7335:   border: 0;
 7336: }
 7337: 
 7338: .LC_FormSectionClearButton input {
 7339:   background-color:transparent;
 7340:   border: none;
 7341:   cursor:pointer;
 7342:   text-decoration:underline;
 7343: }
 7344: 
 7345: .LC_help_open_topic {
 7346:   color: #FFFFFF;
 7347:   background-color: #EEEEFF;
 7348:   margin: 1px;
 7349:   padding: 4px;
 7350:   border: 1px solid #000033;
 7351:   white-space: nowrap;
 7352:   /* vertical-align: middle; */
 7353: }
 7354: 
 7355: dl,
 7356: ul,
 7357: div,
 7358: fieldset {
 7359:   margin: 10px 10px 10px 0;
 7360:   /* overflow: hidden; */
 7361: }
 7362: 
 7363: article.geogebraweb div {
 7364:     margin: 0;
 7365: }
 7366: 
 7367: fieldset > legend {
 7368:   font-weight: bold;
 7369:   padding: 0 5px 0 5px;
 7370: }
 7371: 
 7372: #LC_nav_bar {
 7373:   float: left;
 7374:   background-color: $pgbg_or_bgcolor;
 7375:   margin: 0 0 2px 0;
 7376: }
 7377: 
 7378: #LC_realm {
 7379:   margin: 0.2em 0 0 0;
 7380:   padding: 0;
 7381:   font-weight: bold;
 7382:   text-align: center;
 7383:   background-color: $pgbg_or_bgcolor;
 7384: }
 7385: 
 7386: #LC_nav_bar em {
 7387:   font-weight: bold;
 7388:   font-style: normal;
 7389: }
 7390: 
 7391: ol.LC_primary_menu {
 7392:   margin: 0;
 7393:   padding: 0;
 7394: }
 7395: 
 7396: ol#LC_PathBreadcrumbs {
 7397:   margin: 0;
 7398: }
 7399: 
 7400: ol.LC_primary_menu li {
 7401:   color: RGB(80, 80, 80);
 7402:   vertical-align: middle;
 7403:   text-align: left;
 7404:   list-style: none;
 7405:   position: relative;
 7406:   float: left;
 7407:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7408:   line-height: 1.5em;
 7409: }
 7410: 
 7411: ol.LC_primary_menu li a,
 7412: ol.LC_primary_menu li p {
 7413:   display: block;
 7414:   margin: 0;
 7415:   padding: 0 5px 0 10px;
 7416:   text-decoration: none;
 7417: }
 7418: 
 7419: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7420:   display: inline-block;
 7421:   width: 95%;
 7422:   text-align: left;
 7423: }
 7424: 
 7425: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7426:   display: inline-block;	
 7427:   width: 5%;
 7428:   float: right;
 7429:   text-align: right;
 7430:   font-size: 70%;
 7431: }
 7432: 
 7433: ol.LC_primary_menu ul {
 7434:   display: none;
 7435:   width: 15em;
 7436:   background-color: $data_table_light;
 7437:   position: absolute;
 7438:   top: 100%;
 7439: }
 7440: 
 7441: ol.LC_primary_menu ul ul {
 7442:   left: 100%;
 7443:   top: 0;
 7444: }
 7445: 
 7446: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7447:   display: block;
 7448:   position: absolute;
 7449:   margin: 0;
 7450:   padding: 0;
 7451:   z-index: 2;
 7452: }
 7453: 
 7454: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7455: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7456:   font-size: 90%;
 7457:   vertical-align: top;
 7458:   float: none;
 7459:   border-left: 1px solid black;
 7460:   border-right: 1px solid black;
 7461: /* A dark bottom border to visualize different menu options; 
 7462: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7463:   border-bottom: 1px solid $data_table_dark; 
 7464: }
 7465: 
 7466: ol.LC_primary_menu li li p:hover {
 7467:   color:$button_hover;
 7468:   text-decoration:none;
 7469:   background-color:$data_table_dark;
 7470: }
 7471: 
 7472: ol.LC_primary_menu li li a:hover {
 7473:    color:$button_hover;
 7474:    background-color:$data_table_dark;
 7475: }
 7476: 
 7477: /* Font-size equal to the size of the predecessors*/
 7478: ol.LC_primary_menu li:hover li li {
 7479:   font-size: 100%;
 7480: }
 7481: 
 7482: ol.LC_primary_menu li img {
 7483:   vertical-align: bottom;
 7484:   height: 1.1em;
 7485:   margin: 0.2em 0 0 0;
 7486: }
 7487: 
 7488: ol.LC_primary_menu a {
 7489:   color: RGB(80, 80, 80);
 7490:   text-decoration: none;
 7491: }
 7492: 
 7493: ol.LC_primary_menu a.LC_new_message {
 7494:   font-weight:bold;
 7495:   color: darkred;
 7496: }
 7497: 
 7498: ol.LC_docs_parameters {
 7499:   margin-left: 0;
 7500:   padding: 0;
 7501:   list-style: none;
 7502: }
 7503: 
 7504: ol.LC_docs_parameters li {
 7505:   margin: 0;
 7506:   padding-right: 20px;
 7507:   display: inline;
 7508: }
 7509: 
 7510: ol.LC_docs_parameters li:before {
 7511:   content: "\\002022 \\0020";
 7512: }
 7513: 
 7514: li.LC_docs_parameters_title {
 7515:   font-weight: bold;
 7516: }
 7517: 
 7518: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7519:   content: "";
 7520: }
 7521: 
 7522: ul#LC_secondary_menu {
 7523:   clear: right;
 7524:   color: $fontmenu;
 7525:   background: $tabbg;
 7526:   list-style: none;
 7527:   padding: 0;
 7528:   margin: 0;
 7529:   width: 100%;
 7530:   text-align: left;
 7531:   float: left;
 7532: }
 7533: 
 7534: ul#LC_secondary_menu li {
 7535:   font-weight: bold;
 7536:   line-height: 1.8em;
 7537:   border-right: 1px solid black;
 7538:   float: left;
 7539: }
 7540: 
 7541: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7542:   background-color: $data_table_light;
 7543: }
 7544: 
 7545: ul#LC_secondary_menu li a {
 7546:   padding: 0 0.8em;
 7547: }
 7548: 
 7549: ul#LC_secondary_menu li ul {
 7550:   display: none;
 7551: }
 7552: 
 7553: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7554:   display: block;
 7555:   position: absolute;
 7556:   margin: 0;
 7557:   padding: 0;
 7558:   list-style:none;
 7559:   float: none;
 7560:   background-color: $data_table_light;
 7561:   z-index: 2;
 7562:   margin-left: -1px;
 7563: }
 7564: 
 7565: ul#LC_secondary_menu li ul li {
 7566:   font-size: 90%;
 7567:   vertical-align: top;
 7568:   border-left: 1px solid black;
 7569:   border-right: 1px solid black;
 7570:   background-color: $data_table_light;
 7571:   list-style:none;
 7572:   float: none;
 7573: }
 7574: 
 7575: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7576:   background-color: $data_table_dark;
 7577: }
 7578: 
 7579: ul.LC_TabContent {
 7580:   display:block;
 7581:   background: $sidebg;
 7582:   border-bottom: solid 1px $lg_border_color;
 7583:   list-style:none;
 7584:   margin: -1px -10px 0 -10px;
 7585:   padding: 0;
 7586: }
 7587: 
 7588: ul.LC_TabContent li,
 7589: ul.LC_TabContentBigger li {
 7590:   float:left;
 7591: }
 7592: 
 7593: ul#LC_secondary_menu li a {
 7594:   color: $fontmenu;
 7595:   text-decoration: none;
 7596: }
 7597: 
 7598: ul.LC_TabContent {
 7599:   min-height:20px;
 7600: }
 7601: 
 7602: ul.LC_TabContent li {
 7603:   vertical-align:middle;
 7604:   padding: 0 16px 0 10px;
 7605:   background-color:$tabbg;
 7606:   border-bottom:solid 1px $lg_border_color;
 7607:   border-left: solid 1px $font;
 7608: }
 7609: 
 7610: ul.LC_TabContent .right {
 7611:   float:right;
 7612: }
 7613: 
 7614: ul.LC_TabContent li a,
 7615: ul.LC_TabContent li {
 7616:   color:rgb(47,47,47);
 7617:   text-decoration:none;
 7618:   font-size:95%;
 7619:   font-weight:bold;
 7620:   min-height:20px;
 7621: }
 7622: 
 7623: ul.LC_TabContent li a:hover,
 7624: ul.LC_TabContent li a:focus {
 7625:   color: $button_hover;
 7626:   background:none;
 7627:   outline:none;
 7628: }
 7629: 
 7630: ul.LC_TabContent li:hover {
 7631:   color: $button_hover;
 7632:   cursor:pointer;
 7633: }
 7634: 
 7635: ul.LC_TabContent li.active {
 7636:   color: $font;
 7637:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7638:   border-bottom:solid 1px #FFFFFF;
 7639:   cursor: default;
 7640: }
 7641: 
 7642: ul.LC_TabContent li.active a {
 7643:   color:$font;
 7644:   background:#FFFFFF;
 7645:   outline: none;
 7646: }
 7647: 
 7648: ul.LC_TabContent li.goback {
 7649:   float: left;
 7650:   border-left: none;
 7651: }
 7652: 
 7653: #maincoursedoc {
 7654:   clear:both;
 7655: }
 7656: 
 7657: ul.LC_TabContentBigger {
 7658:   display:block;
 7659:   list-style:none;
 7660:   padding: 0;
 7661: }
 7662: 
 7663: ul.LC_TabContentBigger li {
 7664:   vertical-align:bottom;
 7665:   height: 30px;
 7666:   font-size:110%;
 7667:   font-weight:bold;
 7668:   color: #737373;
 7669: }
 7670: 
 7671: ul.LC_TabContentBigger li.active {
 7672:   position: relative;
 7673:   top: 1px;
 7674: }
 7675: 
 7676: ul.LC_TabContentBigger li a {
 7677:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7678:   height: 30px;
 7679:   line-height: 30px;
 7680:   text-align: center;
 7681:   display: block;
 7682:   text-decoration: none;
 7683:   outline: none;  
 7684: }
 7685: 
 7686: ul.LC_TabContentBigger li.active a {
 7687:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7688:   color:$font;
 7689: }
 7690: 
 7691: ul.LC_TabContentBigger li b {
 7692:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7693:   display: block;
 7694:   float: left;
 7695:   padding: 0 30px;
 7696:   border-bottom: 1px solid $lg_border_color;
 7697: }
 7698: 
 7699: ul.LC_TabContentBigger li:hover b {
 7700:   color:$button_hover;
 7701: }
 7702: 
 7703: ul.LC_TabContentBigger li.active b {
 7704:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7705:   color:$font;
 7706:   border: 0;
 7707: }
 7708: 
 7709: 
 7710: ul.LC_CourseBreadcrumbs {
 7711:   background: $sidebg;
 7712:   height: 2em;
 7713:   padding-left: 10px;
 7714:   margin: 0;
 7715:   list-style-position: inside;
 7716: }
 7717: 
 7718: ol#LC_MenuBreadcrumbs,
 7719: ol#LC_PathBreadcrumbs {
 7720:   padding-left: 10px;
 7721:   margin: 0;
 7722:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7723: }
 7724: 
 7725: ol#LC_MenuBreadcrumbs li,
 7726: ol#LC_PathBreadcrumbs li,
 7727: ul.LC_CourseBreadcrumbs li {
 7728:   display: inline;
 7729:   white-space: normal;  
 7730: }
 7731: 
 7732: ol#LC_MenuBreadcrumbs li a,
 7733: ul.LC_CourseBreadcrumbs li a {
 7734:   text-decoration: none;
 7735:   font-size:90%;
 7736: }
 7737: 
 7738: ol#LC_MenuBreadcrumbs h1 {
 7739:   display: inline;
 7740:   font-size: 90%;
 7741:   line-height: 2.5em;
 7742:   margin: 0;
 7743:   padding: 0;
 7744: }
 7745: 
 7746: ol#LC_PathBreadcrumbs li a {
 7747:   text-decoration:none;
 7748:   font-size:100%;
 7749:   font-weight:bold;
 7750: }
 7751: 
 7752: .LC_Box {
 7753:   border: solid 1px $lg_border_color;
 7754:   padding: 0 10px 10px 10px;
 7755: }
 7756: 
 7757: .LC_DocsBox {
 7758:   border: solid 1px $lg_border_color;
 7759:   padding: 0 0 10px 10px;
 7760: }
 7761: 
 7762: .LC_AboutMe_Image {
 7763:   float:left;
 7764:   margin-right:10px;
 7765: }
 7766: 
 7767: .LC_Clear_AboutMe_Image {
 7768:   clear:left;
 7769: }
 7770: 
 7771: dl.LC_ListStyleClean dt {
 7772:   padding-right: 5px;
 7773:   display: table-header-group;
 7774: }
 7775: 
 7776: dl.LC_ListStyleClean dd {
 7777:   display: table-row;
 7778: }
 7779: 
 7780: .LC_ListStyleClean,
 7781: .LC_ListStyleSimple,
 7782: .LC_ListStyleNormal,
 7783: .LC_ListStyleSpecial {
 7784:   /* display:block; */
 7785:   list-style-position: inside;
 7786:   list-style-type: none;
 7787:   overflow: hidden;
 7788:   padding: 0;
 7789: }
 7790: 
 7791: .LC_ListStyleSimple li,
 7792: .LC_ListStyleSimple dd,
 7793: .LC_ListStyleNormal li,
 7794: .LC_ListStyleNormal dd,
 7795: .LC_ListStyleSpecial li,
 7796: .LC_ListStyleSpecial dd {
 7797:   margin: 0;
 7798:   padding: 5px 5px 5px 10px;
 7799:   clear: both;
 7800: }
 7801: 
 7802: .LC_ListStyleClean li,
 7803: .LC_ListStyleClean dd {
 7804:   padding-top: 0;
 7805:   padding-bottom: 0;
 7806: }
 7807: 
 7808: .LC_ListStyleSimple dd,
 7809: .LC_ListStyleSimple li {
 7810:   border-bottom: solid 1px $lg_border_color;
 7811: }
 7812: 
 7813: .LC_ListStyleSpecial li,
 7814: .LC_ListStyleSpecial dd {
 7815:   list-style-type: none;
 7816:   background-color: RGB(220, 220, 220);
 7817:   margin-bottom: 4px;
 7818: }
 7819: 
 7820: table.LC_SimpleTable {
 7821:   margin:5px;
 7822:   border:solid 1px $lg_border_color;
 7823: }
 7824: 
 7825: table.LC_SimpleTable tr {
 7826:   padding: 0;
 7827:   border:solid 1px $lg_border_color;
 7828: }
 7829: 
 7830: table.LC_SimpleTable thead {
 7831:   background:rgb(220,220,220);
 7832: }
 7833: 
 7834: div.LC_columnSection {
 7835:   display: block;
 7836:   clear: both;
 7837:   overflow: hidden;
 7838:   margin: 0;
 7839: }
 7840: 
 7841: div.LC_columnSection>* {
 7842:   float: left;
 7843:   margin: 10px 20px 10px 0;
 7844:   overflow:hidden;
 7845: }
 7846: 
 7847: table em {
 7848:   font-weight: bold;
 7849:   font-style: normal;
 7850: }
 7851: 
 7852: table.LC_tableBrowseRes,
 7853: table.LC_tableOfContent {
 7854:   border:none;
 7855:   border-spacing: 1px;
 7856:   padding: 3px;
 7857:   background-color: #FFFFFF;
 7858:   font-size: 90%;
 7859: }
 7860: 
 7861: table.LC_tableOfContent {
 7862:   border-collapse: collapse;
 7863: }
 7864: 
 7865: table.LC_tableBrowseRes a,
 7866: table.LC_tableOfContent a {
 7867:   background-color: transparent;
 7868:   text-decoration: none;
 7869: }
 7870: 
 7871: table.LC_tableOfContent img {
 7872:   border: none;
 7873:   height: 1.3em;
 7874:   vertical-align: text-bottom;
 7875:   margin-right: 0.3em;
 7876: }
 7877: 
 7878: a#LC_content_toolbar_firsthomework {
 7879:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7880: }
 7881: 
 7882: a#LC_content_toolbar_everything {
 7883:   background-image:url(/res/adm/pages/show-all.gif);
 7884: }
 7885: 
 7886: a#LC_content_toolbar_uncompleted {
 7887:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7888: }
 7889: 
 7890: #LC_content_toolbar_clearbubbles {
 7891:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7892: }
 7893: 
 7894: a#LC_content_toolbar_changefolder {
 7895:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7896: }
 7897: 
 7898: a#LC_content_toolbar_changefolder_toggled {
 7899:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7900: }
 7901: 
 7902: a#LC_content_toolbar_edittoplevel {
 7903:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7904: }
 7905: 
 7906: ul#LC_toolbar li a:hover {
 7907:   background-position: bottom center;
 7908: }
 7909: 
 7910: ul#LC_toolbar {
 7911:   padding: 0;
 7912:   margin: 2px;
 7913:   list-style:none;
 7914:   position:relative;
 7915:   background-color:white;
 7916:   overflow: auto;
 7917: }
 7918: 
 7919: ul#LC_toolbar li {
 7920:   border:1px solid white;
 7921:   padding: 0;
 7922:   margin: 0;
 7923:   float: left;
 7924:   display:inline;
 7925:   vertical-align:middle;
 7926:   white-space: nowrap;
 7927: }
 7928: 
 7929: 
 7930: a.LC_toolbarItem {
 7931:   display:block;
 7932:   padding: 0;
 7933:   margin: 0;
 7934:   height: 32px;
 7935:   width: 32px;
 7936:   color:white;
 7937:   border: none;
 7938:   background-repeat:no-repeat;
 7939:   background-color:transparent;
 7940: }
 7941: 
 7942: ul.LC_funclist {
 7943:     margin: 0;
 7944:     padding: 0.5em 1em 0.5em 0;
 7945: }
 7946: 
 7947: ul.LC_funclist > li:first-child {
 7948:     font-weight:bold; 
 7949:     margin-left:0.8em;
 7950: }
 7951: 
 7952: ul.LC_funclist + ul.LC_funclist {
 7953:     /* 
 7954:        left border as a seperator if we have more than
 7955:        one list 
 7956:     */
 7957:     border-left: 1px solid $sidebg;
 7958:     /* 
 7959:        this hides the left border behind the border of the 
 7960:        outer box if element is wrapped to the next 'line' 
 7961:     */
 7962:     margin-left: -1px;
 7963: }
 7964: 
 7965: ul.LC_funclist li {
 7966:   display: inline;
 7967:   white-space: nowrap;
 7968:   margin: 0 0 0 25px;
 7969:   line-height: 150%;
 7970: }
 7971: 
 7972: .LC_hidden {
 7973:   display: none;
 7974: }
 7975: 
 7976: .LCmodal-overlay {
 7977: 		position:fixed;
 7978: 		top:0;
 7979: 		right:0;
 7980: 		bottom:0;
 7981: 		left:0;
 7982: 		height:100%;
 7983: 		width:100%;
 7984: 		margin:0;
 7985: 		padding:0;
 7986: 		background:#999;
 7987: 		opacity:.75;
 7988: 		filter: alpha(opacity=75);
 7989: 		-moz-opacity: 0.75;
 7990: 		z-index:101;
 7991: }
 7992: 
 7993: * html .LCmodal-overlay {   
 7994: 		position: absolute;
 7995: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7996: }
 7997: 
 7998: .LCmodal-window {
 7999: 		position:fixed;
 8000: 		top:50%;
 8001: 		left:50%;
 8002: 		margin:0;
 8003: 		padding:0;
 8004: 		z-index:102;
 8005: 	}
 8006: 
 8007: * html .LCmodal-window {
 8008: 		position:absolute;
 8009: }
 8010: 
 8011: .LCclose-window {
 8012: 		position:absolute;
 8013: 		width:32px;
 8014: 		height:32px;
 8015: 		right:8px;
 8016: 		top:8px;
 8017: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8018: 		text-indent:-99999px;
 8019: 		overflow:hidden;
 8020: 		cursor:pointer;
 8021: }
 8022: 
 8023: /*
 8024:   styles used for response display
 8025: */
 8026: div.LC_radiofoil, div.LC_rankfoil {
 8027:   margin: .5em 0em .5em 0em;
 8028: }
 8029: table.LC_itemgroup {
 8030:   margin-top: 1em;
 8031: }
 8032: 
 8033: /*
 8034:   styles used by TTH when "Default set of options to pass to tth/m
 8035:   when converting TeX" in course settings has been set
 8036: 
 8037:   option passed: -t
 8038: 
 8039: */
 8040: 
 8041: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8042: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8043: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8044: td div.norm {line-height:normal;}
 8045: 
 8046: /*
 8047:   option passed -y3
 8048: */
 8049: 
 8050: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8051: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8052: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8053: 
 8054: /*
 8055:   sections with roles, for content only
 8056: */
 8057: section[class^="role-"] {
 8058:   padding-left: 10px;
 8059:   padding-right: 5px;
 8060:   margin-top: 8px;
 8061:   margin-bottom: 8px;
 8062:   border: 1px solid #2A4;
 8063:   border-radius: 5px;
 8064:   box-shadow: 0px 1px 1px #BBB;
 8065: }
 8066: section[class^="role-"]>h1 {
 8067:   position: relative;
 8068:   margin: 0px;
 8069:   padding-top: 10px;
 8070:   padding-left: 40px;
 8071: }
 8072: section[class^="role-"]>h1:before {
 8073:   position: absolute;
 8074:   left: -5px;
 8075:   top: 5px;
 8076: }
 8077: section.role-activity>h1:before {
 8078:   content:url('/adm/daxe/images/section_icons/activity.png');
 8079: }
 8080: section.role-advice>h1:before {
 8081:   content:url('/adm/daxe/images/section_icons/advice.png');
 8082: }
 8083: section.role-bibliography>h1:before {
 8084:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8085: }
 8086: section.role-citation>h1:before {
 8087:   content:url('/adm/daxe/images/section_icons/citation.png');
 8088: }
 8089: section.role-conclusion>h1:before {
 8090:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8091: }
 8092: section.role-definition>h1:before {
 8093:   content:url('/adm/daxe/images/section_icons/definition.png');
 8094: }
 8095: section.role-demonstration>h1:before {
 8096:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8097: }
 8098: section.role-example>h1:before {
 8099:   content:url('/adm/daxe/images/section_icons/example.png');
 8100: }
 8101: section.role-explanation>h1:before {
 8102:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8103: }
 8104: section.role-introduction>h1:before {
 8105:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8106: }
 8107: section.role-method>h1:before {
 8108:   content:url('/adm/daxe/images/section_icons/method.png');
 8109: }
 8110: section.role-more_information>h1:before {
 8111:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8112: }
 8113: section.role-objectives>h1:before {
 8114:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8115: }
 8116: section.role-prerequisites>h1:before {
 8117:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8118: }
 8119: section.role-remark>h1:before {
 8120:   content:url('/adm/daxe/images/section_icons/remark.png');
 8121: }
 8122: section.role-reminder>h1:before {
 8123:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8124: }
 8125: section.role-summary>h1:before {
 8126:   content:url('/adm/daxe/images/section_icons/summary.png');
 8127: }
 8128: section.role-syntax>h1:before {
 8129:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8130: }
 8131: section.role-warning>h1:before {
 8132:   content:url('/adm/daxe/images/section_icons/warning.png');
 8133: }
 8134: 
 8135: #LC_minitab_header {
 8136:   float:left;
 8137:   width:100%;
 8138:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8139:   font-size:93%;
 8140:   line-height:normal;
 8141:   margin: 0.5em 0 0.5em 0;
 8142: }
 8143: #LC_minitab_header ul {
 8144:   margin:0;
 8145:   padding:10px 10px 0;
 8146:   list-style:none;
 8147: }
 8148: #LC_minitab_header li {
 8149:   float:left;
 8150:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8151:   margin:0;
 8152:   padding:0 0 0 9px;
 8153: }
 8154: #LC_minitab_header a {
 8155:   display:block;
 8156:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8157:   padding:5px 15px 4px 6px;
 8158: }
 8159: #LC_minitab_header #LC_current_minitab {
 8160:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8161: }
 8162: #LC_minitab_header #LC_current_minitab a {
 8163:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8164:   padding-bottom:5px;
 8165: }
 8166: 
 8167: 
 8168: END
 8169: }
 8170: 
 8171: =pod
 8172: 
 8173: =item * &headtag()
 8174: 
 8175: Returns a uniform footer for LON-CAPA web pages.
 8176: 
 8177: Inputs: $title - optional title for the head
 8178:         $head_extra - optional extra HTML to put inside the <head>
 8179:         $args - optional arguments
 8180:             force_register - if is true call registerurl so the remote is 
 8181:                              informed
 8182:             redirect       -> array ref of
 8183:                                    1- seconds before redirect occurs
 8184:                                    2- url to redirect to
 8185:                                    3- whether the side effect should occur
 8186:                            (side effect of setting 
 8187:                                $env{'internal.head.redirect'} to the url 
 8188:                                redirected too)
 8189:             domain         -> force to color decorate a page for a specific
 8190:                                domain
 8191:             function       -> force usage of a specific rolish color scheme
 8192:             bgcolor        -> override the default page bgcolor
 8193:             no_auto_mt_title
 8194:                            -> prevent &mt()ing the title arg
 8195: 
 8196: =cut
 8197: 
 8198: sub headtag {
 8199:     my ($title,$head_extra,$args) = @_;
 8200:     
 8201:     my $function = $args->{'function'} || &get_users_function();
 8202:     my $domain   = $args->{'domain'}   || &determinedomain();
 8203:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8204:     my $httphost = $args->{'use_absolute'};
 8205:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8206: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8207: 		   #time(),
 8208: 		   $env{'environment.color.timestamp'},
 8209: 		   $function,$domain,$bgcolor);
 8210: 
 8211:     $url = '/adm/css/'.&escape($url).'.css';
 8212: 
 8213:     my $result =
 8214: 	'<head>'.
 8215: 	&font_settings($args);
 8216: 
 8217:     my $inhibitprint;
 8218:     if ($args->{'print_suppress'}) {
 8219:         $inhibitprint = &print_suppression();
 8220:     }
 8221: 
 8222:     if (!$args->{'frameset'}) {
 8223: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8224:     }
 8225:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8226:         $result .= Apache::lonxml::display_title();
 8227:     }
 8228:     if (!$args->{'no_nav_bar'} 
 8229: 	&& !$args->{'only_body'}
 8230: 	&& !$args->{'frameset'}) {
 8231: 	$result .= &help_menu_js($httphost);
 8232:         $result.=&modal_window();
 8233:         $result.=&togglebox_script();
 8234:         $result.=&wishlist_window();
 8235:         $result.=&LCprogressbarUpdate_script();
 8236:     } else {
 8237:         if ($args->{'add_modal'}) {
 8238:            $result.=&modal_window();
 8239:         }
 8240:         if ($args->{'add_wishlist'}) {
 8241:            $result.=&wishlist_window();
 8242:         }
 8243:         if ($args->{'add_togglebox'}) {
 8244:            $result.=&togglebox_script();
 8245:         }
 8246:         if ($args->{'add_progressbar'}) {
 8247:            $result.=&LCprogressbarUpdate_script();
 8248:         }
 8249:     }
 8250:     if (ref($args->{'redirect'})) {
 8251: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8252: 	$url = &Apache::lonenc::check_encrypt($url);
 8253: 	if (!$inhibit_continue) {
 8254: 	    $env{'internal.head.redirect'} = $url;
 8255: 	}
 8256: 	$result.=<<ADDMETA
 8257: <meta http-equiv="pragma" content="no-cache" />
 8258: <meta http-equiv="Refresh" content="$time; url=$url" />
 8259: ADDMETA
 8260:     } else {
 8261:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8262:             my $requrl = $env{'request.uri'};
 8263:             if ($requrl eq '') {
 8264:                 $requrl = $ENV{'REQUEST_URI'};
 8265:                 $requrl =~ s/\?.+$//;
 8266:             }
 8267:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8268:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8269:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8270:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8271:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8272:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8273:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8274:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8275:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8276:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8277:                             if (($newserver) && ($newserver ne $lonhost)) {
 8278:                                 my $numsec = 5;
 8279:                                 my $timeout = $numsec * 1000;
 8280:                                 my ($newurl,$locknum,%locks,$msg);
 8281:                                 if ($env{'request.role.adv'}) {
 8282:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 8283:                                 }
 8284:                                 my $disable_submit = 0;
 8285:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 8286:                                     $disable_submit = 1;
 8287:                                 }
 8288:                                 if ($locknum) {
 8289:                                     my @lockinfo = sort(values(%locks));
 8290:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 8291:                                            join(", ",sort(values(%locks)))."\\n".
 8292:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 8293:                                 } else {
 8294:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8295:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 8296:                                     }
 8297:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8298:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 8299:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8300:                                         $newurl .= '&role='.$env{'request.role'};
 8301:                                     }
 8302:                                     if ($env{'request.symb'}) {
 8303:                                         $newurl .= '&symb='.$env{'request.symb'};
 8304:                                     } else {
 8305:                                         $newurl .= '&origurl='.$requrl;
 8306:                                     }
 8307:                                 }
 8308:                                 &js_escape(\$msg);
 8309:                                 $result.=<<OFFLOAD
 8310: <meta http-equiv="pragma" content="no-cache" />
 8311: <script type="text/javascript">
 8312: // <![CDATA[
 8313: function LC_Offload_Now() {
 8314:     var dest = "$newurl";
 8315:     if (dest != '') {
 8316:         window.location.href="$newurl";
 8317:     }
 8318: }
 8319: \$(document).ready(function () {
 8320:     window.alert('$msg');
 8321:     if ($disable_submit) {
 8322:         \$(".LC_hwk_submit").prop("disabled", true);
 8323:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8324:     }
 8325:     setTimeout('LC_Offload_Now()', $timeout);
 8326: });
 8327: // ]]>
 8328: </script>
 8329: OFFLOAD
 8330:                             }
 8331:                         }
 8332:                     }
 8333:                 }
 8334:             }
 8335:         }
 8336:     }
 8337:     if (!defined($title)) {
 8338: 	$title = 'The LearningOnline Network with CAPA';
 8339:     }
 8340:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8341:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8342: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8343:     if (!$args->{'frameset'}) {
 8344:         $result .= ' /';
 8345:     }
 8346:     $result .= '>' 
 8347:         .$inhibitprint
 8348: 	.$head_extra;
 8349:     my $clientmobile;
 8350:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8351:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8352:     } else {
 8353:         $clientmobile = $env{'browser.mobile'};
 8354:     }
 8355:     if ($clientmobile) {
 8356:         $result .= '
 8357: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8358: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8359:     }
 8360:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8361:     return $result.'</head>';
 8362: }
 8363: 
 8364: =pod
 8365: 
 8366: =item * &font_settings()
 8367: 
 8368: Returns neccessary <meta> to set the proper encoding
 8369: 
 8370: Inputs: optional reference to HASH -- $args passed to &headtag()
 8371: 
 8372: =cut
 8373: 
 8374: sub font_settings {
 8375:     my ($args) = @_;
 8376:     my $headerstring='';
 8377:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8378:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8379:         $headerstring.=
 8380:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8381:         if (!$args->{'frameset'}) {
 8382: 	    $headerstring.= ' /';
 8383:         }
 8384: 	$headerstring .= '>'."\n";
 8385:     }
 8386:     return $headerstring;
 8387: }
 8388: 
 8389: =pod
 8390: 
 8391: =item * &print_suppression()
 8392: 
 8393: In course context returns css which causes the body to be blank when media="print",
 8394: if printout generation is unavailable for the current resource.
 8395: 
 8396: This could be because:
 8397: 
 8398: (a) printstartdate is in the future
 8399: 
 8400: (b) printenddate is in the past
 8401: 
 8402: (c) there is an active exam block with "printout"
 8403: functionality blocked
 8404: 
 8405: Users with pav, pfo or evb privileges are exempt.
 8406: 
 8407: Inputs: none
 8408: 
 8409: =cut
 8410: 
 8411: 
 8412: sub print_suppression {
 8413:     my $noprint;
 8414:     if ($env{'request.course.id'}) {
 8415:         my $scope = $env{'request.course.id'};
 8416:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8417:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8418:             return;
 8419:         }
 8420:         if ($env{'request.course.sec'} ne '') {
 8421:             $scope .= "/$env{'request.course.sec'}";
 8422:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8423:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8424:                 return;
 8425:             }
 8426:         }
 8427:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8428:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8429:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8430:         if ($blocked) {
 8431:             my $checkrole = "cm./$cdom/$cnum";
 8432:             if ($env{'request.course.sec'} ne '') {
 8433:                 $checkrole .= "/$env{'request.course.sec'}";
 8434:             }
 8435:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8436:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8437:                 $noprint = 1;
 8438:             }
 8439:         }
 8440:         unless ($noprint) {
 8441:             my $symb = &Apache::lonnet::symbread();
 8442:             if ($symb ne '') {
 8443:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8444:                 if (ref($navmap)) {
 8445:                     my $res = $navmap->getBySymb($symb);
 8446:                     if (ref($res)) {
 8447:                         if (!$res->resprintable()) {
 8448:                             $noprint = 1;
 8449:                         }
 8450:                     }
 8451:                 }
 8452:             }
 8453:         }
 8454:         if ($noprint) {
 8455:             return <<"ENDSTYLE";
 8456: <style type="text/css" media="print">
 8457:     body { display:none }
 8458: </style>
 8459: ENDSTYLE
 8460:         }
 8461:     }
 8462:     return;
 8463: }
 8464: 
 8465: =pod
 8466: 
 8467: =item * &xml_begin()
 8468: 
 8469: Returns the needed doctype and <html>
 8470: 
 8471: Inputs: none
 8472: 
 8473: =cut
 8474: 
 8475: sub xml_begin {
 8476:     my ($is_frameset) = @_;
 8477:     my $output='';
 8478: 
 8479:     if ($env{'browser.mathml'}) {
 8480: 	$output='<?xml version="1.0"?>'
 8481:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8482: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8483:             
 8484: #	    .'<!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">] >'
 8485: 	    .'<!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">'
 8486:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8487: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8488:     } elsif ($is_frameset) {
 8489:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8490:                 '<html>'."\n";
 8491:     } else {
 8492: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8493:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8494:     }
 8495:     return $output;
 8496: }
 8497: 
 8498: =pod
 8499: 
 8500: =item * &start_page()
 8501: 
 8502: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8503: 
 8504: Inputs:
 8505: 
 8506: =over 4
 8507: 
 8508: $title - optional title for the page
 8509: 
 8510: $head_extra - optional extra HTML to incude inside the <head>
 8511: 
 8512: $args - additional optional args supported are:
 8513: 
 8514: =over 8
 8515: 
 8516:              only_body      -> is true will set &bodytag() onlybodytag
 8517:                                     arg on
 8518:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8519:              add_entries    -> additional attributes to add to the  <body>
 8520:              domain         -> force to color decorate a page for a 
 8521:                                     specific domain
 8522:              function       -> force usage of a specific rolish color
 8523:                                     scheme
 8524:              redirect       -> see &headtag()
 8525:              bgcolor        -> override the default page bg color
 8526:              js_ready       -> return a string ready for being used in 
 8527:                                     a javascript writeln
 8528:              html_encode    -> return a string ready for being used in 
 8529:                                     a html attribute
 8530:              force_register -> if is true will turn on the &bodytag()
 8531:                                     $forcereg arg
 8532:              frameset       -> if true will start with a <frameset>
 8533:                                     rather than <body>
 8534:              skip_phases    -> hash ref of 
 8535:                                     head -> skip the <html><head> generation
 8536:                                     body -> skip all <body> generation
 8537:              no_auto_mt_title -> prevent &mt()ing the title arg
 8538:              bread_crumbs ->             Array containing breadcrumbs
 8539:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8540:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8541:                                     to lonhtmlcommon::breadcrumbs
 8542:              group          -> includes the current group, if page is for a 
 8543:                                specific group
 8544:              use_absolute   -> for request for external resource or syllabus, this
 8545:                                will contain https://<hostname> if server uses
 8546:                                https (as per hosts.tab), but request is for http
 8547:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8548: 
 8549: =back
 8550: 
 8551: =back
 8552: 
 8553: =cut
 8554: 
 8555: sub start_page {
 8556:     my ($title,$head_extra,$args) = @_;
 8557:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8558: 
 8559:     $env{'internal.start_page'}++;
 8560:     my ($result,@advtools);
 8561: 
 8562:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8563:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8564:     }
 8565:     
 8566:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8567: 	if ($args->{'frameset'}) {
 8568: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8569: 						$args->{'add_entries'});
 8570: 	    $result .= "\n<frameset $attr_string>\n";
 8571:         } else {
 8572:             $result .=
 8573:                 &bodytag($title, 
 8574:                          $args->{'function'},       $args->{'add_entries'},
 8575:                          $args->{'only_body'},      $args->{'domain'},
 8576:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8577:                          $args->{'bgcolor'},        $args,
 8578:                          \@advtools);
 8579:         }
 8580:     }
 8581: 
 8582:     if ($args->{'js_ready'}) {
 8583: 		$result = &js_ready($result);
 8584:     }
 8585:     if ($args->{'html_encode'}) {
 8586: 		$result = &html_encode($result);
 8587:     }
 8588: 
 8589:     # Preparation for new and consistent functionlist at top of screen
 8590:     # if ($args->{'functionlist'}) {
 8591:     #            $result .= &build_functionlist();
 8592:     #}
 8593: 
 8594:     # Don't add anything more if only_body wanted or in const space
 8595:     return $result if    $args->{'only_body'} 
 8596:                       || $env{'request.state'} eq 'construct';
 8597: 
 8598:     #Breadcrumbs
 8599:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8600: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8601: 		#if any br links exists, add them to the breadcrumbs
 8602: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8603: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8604: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8605: 			}
 8606: 		}
 8607:                 # if @advtools array contains items add then to the breadcrumbs
 8608:                 if (@advtools > 0) {
 8609:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8610:                 }
 8611:                 my $menulink;
 8612:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8613:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8614:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 8615:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 8616:                      (!$env{'request.role.adv'}))) {
 8617:                     $menulink = 0;
 8618:                 } else {
 8619:                     undef($menulink);
 8620:                 }
 8621: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8622: 		if(exists($args->{'bread_crumbs_component'})){
 8623: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8624:                 } else {
 8625: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8626: 		}
 8627:     }
 8628:     return $result;
 8629: }
 8630: 
 8631: sub end_page {
 8632:     my ($args) = @_;
 8633:     $env{'internal.end_page'}++;
 8634:     my $result;
 8635:     if ($args->{'discussion'}) {
 8636: 	my ($target,$parser);
 8637: 	if (ref($args->{'discussion'})) {
 8638: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8639: 				$args->{'discussion'}{'parser'});
 8640: 	}
 8641: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8642:     }
 8643:     if ($args->{'frameset'}) {
 8644: 	$result .= '</frameset>';
 8645:     } else {
 8646: 	$result .= &endbodytag($args);
 8647:     }
 8648:     unless ($args->{'notbody'}) {
 8649:         $result .= "\n</html>";
 8650:     }
 8651: 
 8652:     if ($args->{'js_ready'}) {
 8653: 	$result = &js_ready($result);
 8654:     }
 8655: 
 8656:     if ($args->{'html_encode'}) {
 8657: 	$result = &html_encode($result);
 8658:     }
 8659: 
 8660:     return $result;
 8661: }
 8662: 
 8663: sub wishlist_window {
 8664:     return(<<'ENDWISHLIST');
 8665: <script type="text/javascript">
 8666: // <![CDATA[
 8667: // <!-- BEGIN LON-CAPA Internal
 8668: function set_wishlistlink(title, path) {
 8669:     if (!title) {
 8670:         title = document.title;
 8671:         title = title.replace(/^LON-CAPA /,'');
 8672:     }
 8673:     title = encodeURIComponent(title);
 8674:     title = title.replace("'","\\\'");
 8675:     if (!path) {
 8676:         path = location.pathname;
 8677:     }
 8678:     path = encodeURIComponent(path);
 8679:     path = path.replace("'","\\\'");
 8680:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8681:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8682: }
 8683: // END LON-CAPA Internal -->
 8684: // ]]>
 8685: </script>
 8686: ENDWISHLIST
 8687: }
 8688: 
 8689: sub modal_window {
 8690:     return(<<'ENDMODAL');
 8691: <script type="text/javascript">
 8692: // <![CDATA[
 8693: // <!-- BEGIN LON-CAPA Internal
 8694: var modalWindow = {
 8695: 	parent:"body",
 8696: 	windowId:null,
 8697: 	content:null,
 8698: 	width:null,
 8699: 	height:null,
 8700: 	close:function()
 8701: 	{
 8702: 	        $(".LCmodal-window").remove();
 8703: 	        $(".LCmodal-overlay").remove();
 8704: 	},
 8705: 	open:function()
 8706: 	{
 8707: 		var modal = "";
 8708: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8709: 		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;\">";
 8710: 		modal += this.content;
 8711: 		modal += "</div>";	
 8712: 
 8713: 		$(this.parent).append(modal);
 8714: 
 8715: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8716: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8717: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8718: 	}
 8719: };
 8720: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8721: 	{
 8722:                 source = source.replace(/'/g,"&#39;");
 8723: 		modalWindow.windowId = "myModal";
 8724: 		modalWindow.width = width;
 8725: 		modalWindow.height = height;
 8726: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8727: 		modalWindow.open();
 8728: 	};
 8729: // END LON-CAPA Internal -->
 8730: // ]]>
 8731: </script>
 8732: ENDMODAL
 8733: }
 8734: 
 8735: sub modal_link {
 8736:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8737:     unless ($width) { $width=480; }
 8738:     unless ($height) { $height=400; }
 8739:     unless ($scrolling) { $scrolling='yes'; }
 8740:     unless ($transparency) { $transparency='true'; }
 8741: 
 8742:     my $target_attr;
 8743:     if (defined($target)) {
 8744:         $target_attr = 'target="'.$target.'"';
 8745:     }
 8746:     return <<"ENDLINK";
 8747: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8748:            $linktext</a>
 8749: ENDLINK
 8750: }
 8751: 
 8752: sub modal_adhoc_script {
 8753:     my ($funcname,$width,$height,$content)=@_;
 8754:     return (<<ENDADHOC);
 8755: <script type="text/javascript">
 8756: // <![CDATA[
 8757:         var $funcname = function()
 8758:         {
 8759:                 modalWindow.windowId = "myModal";
 8760:                 modalWindow.width = $width;
 8761:                 modalWindow.height = $height;
 8762:                 modalWindow.content = '$content';
 8763:                 modalWindow.open();
 8764:         };  
 8765: // ]]>
 8766: </script>
 8767: ENDADHOC
 8768: }
 8769: 
 8770: sub modal_adhoc_inner {
 8771:     my ($funcname,$width,$height,$content)=@_;
 8772:     my $innerwidth=$width-20;
 8773:     $content=&js_ready(
 8774:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8775:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8776:                  $content.
 8777:                  &end_scrollbox().
 8778:                  &end_page()
 8779:              );
 8780:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8781: }
 8782: 
 8783: sub modal_adhoc_window {
 8784:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8785:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8786:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8787: }
 8788: 
 8789: sub modal_adhoc_launch {
 8790:     my ($funcname,$width,$height,$content)=@_;
 8791:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8792: <script type="text/javascript">
 8793: // <![CDATA[
 8794: $funcname();
 8795: // ]]>
 8796: </script>
 8797: ENDLAUNCH
 8798: }
 8799: 
 8800: sub modal_adhoc_close {
 8801:     return (<<ENDCLOSE);
 8802: <script type="text/javascript">
 8803: // <![CDATA[
 8804: modalWindow.close();
 8805: // ]]>
 8806: </script>
 8807: ENDCLOSE
 8808: }
 8809: 
 8810: sub togglebox_script {
 8811:    return(<<ENDTOGGLE);
 8812: <script type="text/javascript"> 
 8813: // <![CDATA[
 8814: function LCtoggleDisplay(id,hidetext,showtext) {
 8815:    link = document.getElementById(id + "link").childNodes[0];
 8816:    with (document.getElementById(id).style) {
 8817:       if (display == "none" ) {
 8818:           display = "inline";
 8819:           link.nodeValue = hidetext;
 8820:         } else {
 8821:           display = "none";
 8822:           link.nodeValue = showtext;
 8823:        }
 8824:    }
 8825: }
 8826: // ]]>
 8827: </script>
 8828: ENDTOGGLE
 8829: }
 8830: 
 8831: sub start_togglebox {
 8832:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8833:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8834:     unless ($showtext) { $showtext=&mt('show'); }
 8835:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8836:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8837:     return &start_data_table().
 8838:            &start_data_table_header_row().
 8839:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8840:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8841:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8842:            &end_data_table_header_row().
 8843:            '<tr id="'.$id.'" style="display:none""><td>';
 8844: }
 8845: 
 8846: sub end_togglebox {
 8847:     return '</td></tr>'.&end_data_table();
 8848: }
 8849: 
 8850: sub LCprogressbar_script {
 8851:    my ($id)=@_;
 8852:    return(<<ENDPROGRESS);
 8853: <script type="text/javascript">
 8854: // <![CDATA[
 8855: \$('#progressbar$id').progressbar({
 8856:   value: 0,
 8857:   change: function(event, ui) {
 8858:     var newVal = \$(this).progressbar('option', 'value');
 8859:     \$('.pblabel', this).text(LCprogressTxt);
 8860:   }
 8861: });
 8862: // ]]>
 8863: </script>
 8864: ENDPROGRESS
 8865: }
 8866: 
 8867: sub LCprogressbarUpdate_script {
 8868:    return(<<ENDPROGRESSUPDATE);
 8869: <style type="text/css">
 8870: .ui-progressbar { position:relative; }
 8871: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8872: </style>
 8873: <script type="text/javascript">
 8874: // <![CDATA[
 8875: var LCprogressTxt='---';
 8876: 
 8877: function LCupdateProgress(percent,progresstext,id) {
 8878:    LCprogressTxt=progresstext;
 8879:    \$('#progressbar'+id).progressbar('value',percent);
 8880: }
 8881: // ]]>
 8882: </script>
 8883: ENDPROGRESSUPDATE
 8884: }
 8885: 
 8886: my $LClastpercent;
 8887: my $LCidcnt;
 8888: my $LCcurrentid;
 8889: 
 8890: sub LCprogressbar {
 8891:     my ($r)=(@_);
 8892:     $LClastpercent=0;
 8893:     $LCidcnt++;
 8894:     $LCcurrentid=$$.'_'.$LCidcnt;
 8895:     my $starting=&mt('Starting');
 8896:     my $content=(<<ENDPROGBAR);
 8897:   <div id="progressbar$LCcurrentid">
 8898:     <span class="pblabel">$starting</span>
 8899:   </div>
 8900: ENDPROGBAR
 8901:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8902: }
 8903: 
 8904: sub LCprogressbarUpdate {
 8905:     my ($r,$val,$text)=@_;
 8906:     unless ($val) { 
 8907:        if ($LClastpercent) {
 8908:            $val=$LClastpercent;
 8909:        } else {
 8910:            $val=0;
 8911:        }
 8912:     }
 8913:     if ($val<0) { $val=0; }
 8914:     if ($val>100) { $val=0; }
 8915:     $LClastpercent=$val;
 8916:     unless ($text) { $text=$val.'%'; }
 8917:     $text=&js_ready($text);
 8918:     &r_print($r,<<ENDUPDATE);
 8919: <script type="text/javascript">
 8920: // <![CDATA[
 8921: LCupdateProgress($val,'$text','$LCcurrentid');
 8922: // ]]>
 8923: </script>
 8924: ENDUPDATE
 8925: }
 8926: 
 8927: sub LCprogressbarClose {
 8928:     my ($r)=@_;
 8929:     $LClastpercent=0;
 8930:     &r_print($r,<<ENDCLOSE);
 8931: <script type="text/javascript">
 8932: // <![CDATA[
 8933: \$("#progressbar$LCcurrentid").hide('slow'); 
 8934: // ]]>
 8935: </script>
 8936: ENDCLOSE
 8937: }
 8938: 
 8939: sub r_print {
 8940:     my ($r,$to_print)=@_;
 8941:     if ($r) {
 8942:       $r->print($to_print);
 8943:       $r->rflush();
 8944:     } else {
 8945:       print($to_print);
 8946:     }
 8947: }
 8948: 
 8949: sub html_encode {
 8950:     my ($result) = @_;
 8951: 
 8952:     $result = &HTML::Entities::encode($result,'<>&"');
 8953:     
 8954:     return $result;
 8955: }
 8956: 
 8957: sub js_ready {
 8958:     my ($result) = @_;
 8959: 
 8960:     $result =~ s/[\n\r]/ /xmsg;
 8961:     $result =~ s/\\/\\\\/xmsg;
 8962:     $result =~ s/'/\\'/xmsg;
 8963:     $result =~ s{</}{<\\/}xmsg;
 8964:     
 8965:     return $result;
 8966: }
 8967: 
 8968: sub validate_page {
 8969:     if (  exists($env{'internal.start_page'})
 8970: 	  &&     $env{'internal.start_page'} > 1) {
 8971: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8972: 				 $env{'internal.start_page'}.' '.
 8973: 				 $ENV{'request.filename'});
 8974:     }
 8975:     if (  exists($env{'internal.end_page'})
 8976: 	  &&     $env{'internal.end_page'} > 1) {
 8977: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8978: 				 $env{'internal.end_page'}.' '.
 8979: 				 $env{'request.filename'});
 8980:     }
 8981:     if (     exists($env{'internal.start_page'})
 8982: 	&& ! exists($env{'internal.end_page'})) {
 8983: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8984: 				 $env{'request.filename'});
 8985:     }
 8986:     if (   ! exists($env{'internal.start_page'})
 8987: 	&&   exists($env{'internal.end_page'})) {
 8988: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8989: 				 $env{'request.filename'});
 8990:     }
 8991: }
 8992: 
 8993: 
 8994: sub start_scrollbox {
 8995:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8996:     unless ($outerwidth) { $outerwidth='520px'; }
 8997:     unless ($width) { $width='500px'; }
 8998:     unless ($height) { $height='200px'; }
 8999:     my ($table_id,$div_id,$tdcol);
 9000:     if ($id ne '') {
 9001:         $table_id = ' id="table_'.$id.'"';
 9002:         $div_id = ' id="div_'.$id.'"';
 9003:     }
 9004:     if ($bgcolor ne '') {
 9005:         $tdcol = "background-color: $bgcolor;";
 9006:     }
 9007:     my $nicescroll_js;
 9008:     if ($env{'browser.mobile'}) {
 9009:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9010:     }
 9011:     return <<"END";
 9012: $nicescroll_js
 9013: 
 9014: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9015: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9016: END
 9017: }
 9018: 
 9019: sub end_scrollbox {
 9020:     return '</div></td></tr></table>';
 9021: }
 9022: 
 9023: sub nicescroll_javascript {
 9024:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9025:     my %options;
 9026:     if (ref($cursor) eq 'HASH') {
 9027:         %options = %{$cursor};
 9028:     }
 9029:     unless ($options{'railalign'} =~ /^left|right$/) {
 9030:         $options{'railalign'} = 'left';
 9031:     }
 9032:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9033:         my $function  = &get_users_function();
 9034:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9035:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9036:             $options{'cursorcolor'} = '#00F';
 9037:         }
 9038:     }
 9039:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9040:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9041:             $options{'cursoropacity'}='1.0';
 9042:         }
 9043:     } else {
 9044:         $options{'cursoropacity'}='1.0';
 9045:     }
 9046:     if ($options{'cursorfixedheight'} eq 'none') {
 9047:         delete($options{'cursorfixedheight'});
 9048:     } else {
 9049:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9050:     }
 9051:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9052:         delete($options{'railoffset'});
 9053:     }
 9054:     my @niceoptions;
 9055:     while (my($key,$value) = each(%options)) {
 9056:         if ($value =~ /^\{.+\}$/) {
 9057:             push(@niceoptions,$key.':'.$value);
 9058:         } else {
 9059:             push(@niceoptions,$key.':"'.$value.'"');
 9060:         }
 9061:     }
 9062:     my $nicescroll_js = '
 9063: $(document).ready(
 9064:       function() {
 9065:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9066:       }
 9067: );
 9068: ';
 9069:     if ($framecheck) {
 9070:         $nicescroll_js .= '
 9071: function expand_div(caller) {
 9072:     if (top === self) {
 9073:         document.getElementById("'.$id.'").style.width = "auto";
 9074:         document.getElementById("'.$id.'").style.height = "auto";
 9075:     } else {
 9076:         try {
 9077:             if (parent.frames) {
 9078:                 if (parent.frames.length > 1) {
 9079:                     var framesrc = parent.frames[1].location.href;
 9080:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9081:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9082:                         document.getElementById("'.$id.'").style.width = "auto";
 9083:                         document.getElementById("'.$id.'").style.height = "auto";
 9084:                     }
 9085:                 }
 9086:             }
 9087:         } catch (e) {
 9088:             return;
 9089:         }
 9090:     }
 9091:     return;
 9092: }
 9093: ';
 9094:     }
 9095:     if ($needjsready) {
 9096:         $nicescroll_js = '
 9097: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9098:     } else {
 9099:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9100:     }
 9101:     return $nicescroll_js;
 9102: }
 9103: 
 9104: sub simple_error_page {
 9105:     my ($r,$title,$msg,$args) = @_;
 9106:     if (ref($args) eq 'HASH') {
 9107:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9108:     } else {
 9109:         $msg = &mt($msg);
 9110:     }
 9111: 
 9112:     my $page =
 9113: 	&Apache::loncommon::start_page($title).
 9114: 	'<p class="LC_error">'.$msg.'</p>'.
 9115: 	&Apache::loncommon::end_page();
 9116:     if (ref($r)) {
 9117: 	$r->print($page);
 9118: 	return;
 9119:     }
 9120:     return $page;
 9121: }
 9122: 
 9123: {
 9124:     my @row_count;
 9125: 
 9126:     sub start_data_table_count {
 9127:         unshift(@row_count, 0);
 9128:         return;
 9129:     }
 9130: 
 9131:     sub end_data_table_count {
 9132:         shift(@row_count);
 9133:         return;
 9134:     }
 9135: 
 9136:     sub start_data_table {
 9137: 	my ($add_class,$id) = @_;
 9138: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9139:         my $table_id;
 9140:         if (defined($id)) {
 9141:             $table_id = ' id="'.$id.'"';
 9142:         }
 9143: 	&start_data_table_count();
 9144: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9145:     }
 9146: 
 9147:     sub end_data_table {
 9148: 	&end_data_table_count();
 9149: 	return '</table>'."\n";;
 9150:     }
 9151: 
 9152:     sub start_data_table_row {
 9153: 	my ($add_class, $id) = @_;
 9154: 	$row_count[0]++;
 9155: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9156: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9157:         $id = (' id="'.$id.'"') unless ($id eq '');
 9158:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9159:     }
 9160:     
 9161:     sub continue_data_table_row {
 9162: 	my ($add_class, $id) = @_;
 9163: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9164: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9165:         $id = (' id="'.$id.'"') unless ($id eq '');
 9166:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9167:     }
 9168: 
 9169:     sub end_data_table_row {
 9170: 	return '</tr>'."\n";;
 9171:     }
 9172: 
 9173:     sub start_data_table_empty_row {
 9174: #	$row_count[0]++;
 9175: 	return  '<tr class="LC_empty_row" >'."\n";;
 9176:     }
 9177: 
 9178:     sub end_data_table_empty_row {
 9179: 	return '</tr>'."\n";;
 9180:     }
 9181: 
 9182:     sub start_data_table_header_row {
 9183: 	return  '<tr class="LC_header_row">'."\n";;
 9184:     }
 9185: 
 9186:     sub end_data_table_header_row {
 9187: 	return '</tr>'."\n";;
 9188:     }
 9189: 
 9190:     sub data_table_caption {
 9191:         my $caption = shift;
 9192:         return "<caption class=\"LC_caption\">$caption</caption>";
 9193:     }
 9194: }
 9195: 
 9196: =pod
 9197: 
 9198: =item * &inhibit_menu_check($arg)
 9199: 
 9200: Checks for a inhibitmenu state and generates output to preserve it
 9201: 
 9202: Inputs:         $arg - can be any of
 9203:                      - undef - in which case the return value is a string 
 9204:                                to add  into arguments list of a uri
 9205:                      - 'input' - in which case the return value is a HTML
 9206:                                  <form> <input> field of type hidden to
 9207:                                  preserve the value
 9208:                      - a url - in which case the return value is the url with
 9209:                                the neccesary cgi args added to preserve the
 9210:                                inhibitmenu state
 9211:                      - a ref to a url - no return value, but the string is
 9212:                                         updated to include the neccessary cgi
 9213:                                         args to preserve the inhibitmenu state
 9214: 
 9215: =cut
 9216: 
 9217: sub inhibit_menu_check {
 9218:     my ($arg) = @_;
 9219:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9220:     if ($arg eq 'input') {
 9221: 	if ($env{'form.inhibitmenu'}) {
 9222: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9223: 	} else {
 9224: 	    return
 9225: 	}
 9226:     }
 9227:     if ($env{'form.inhibitmenu'}) {
 9228: 	if (ref($arg)) {
 9229: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9230: 	} elsif ($arg eq '') {
 9231: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9232: 	} else {
 9233: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9234: 	}
 9235:     }
 9236:     if (!ref($arg)) {
 9237: 	return $arg;
 9238:     }
 9239: }
 9240: 
 9241: ###############################################
 9242: 
 9243: =pod
 9244: 
 9245: =back
 9246: 
 9247: =head1 User Information Routines
 9248: 
 9249: =over 4
 9250: 
 9251: =item * &get_users_function()
 9252: 
 9253: Used by &bodytag to determine the current users primary role.
 9254: Returns either 'student','coordinator','admin', or 'author'.
 9255: 
 9256: =cut
 9257: 
 9258: ###############################################
 9259: sub get_users_function {
 9260:     my $function = 'norole';
 9261:     if ($env{'request.role'}=~/^(st)/) {
 9262:         $function='student';
 9263:     }
 9264:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9265:         $function='coordinator';
 9266:     }
 9267:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9268:         $function='admin';
 9269:     }
 9270:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9271:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9272:         $function='author';
 9273:     }
 9274:     return $function;
 9275: }
 9276: 
 9277: ###############################################
 9278: 
 9279: =pod
 9280: 
 9281: =item * &show_course()
 9282: 
 9283: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9284: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9285: 
 9286: Inputs:
 9287: None
 9288: 
 9289: Outputs:
 9290: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9291: 
 9292: =cut
 9293: 
 9294: ###############################################
 9295: sub show_course {
 9296:     my $course = !$env{'user.adv'};
 9297:     if (!$env{'user.adv'}) {
 9298:         foreach my $env (keys(%env)) {
 9299:             next if ($env !~ m/^user\.priv\./);
 9300:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9301:                 $course = 0;
 9302:                 last;
 9303:             }
 9304:         }
 9305:     }
 9306:     return $course;
 9307: }
 9308: 
 9309: ###############################################
 9310: 
 9311: =pod
 9312: 
 9313: =item * &check_user_status()
 9314: 
 9315: Determines current status of supplied role for a
 9316: specific user. Roles can be active, previous or future.
 9317: 
 9318: Inputs: 
 9319: user's domain, user's username, course's domain,
 9320: course's number, optional section ID.
 9321: 
 9322: Outputs:
 9323: role status: active, previous or future. 
 9324: 
 9325: =cut
 9326: 
 9327: sub check_user_status {
 9328:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9329:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9330:     my @uroles = keys(%userinfo);
 9331:     my $srchstr;
 9332:     my $active_chk = 'none';
 9333:     my $now = time;
 9334:     if (@uroles > 0) {
 9335:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9336:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9337:         } else {
 9338:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9339:         }
 9340:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9341:             my $role_end = 0;
 9342:             my $role_start = 0;
 9343:             $active_chk = 'active';
 9344:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9345:                 $role_end = $1;
 9346:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9347:                     $role_start = $1;
 9348:                 }
 9349:             }
 9350:             if ($role_start > 0) {
 9351:                 if ($now < $role_start) {
 9352:                     $active_chk = 'future';
 9353:                 }
 9354:             }
 9355:             if ($role_end > 0) {
 9356:                 if ($now > $role_end) {
 9357:                     $active_chk = 'previous';
 9358:                 }
 9359:             }
 9360:         }
 9361:     }
 9362:     return $active_chk;
 9363: }
 9364: 
 9365: ###############################################
 9366: 
 9367: =pod
 9368: 
 9369: =item * &get_sections()
 9370: 
 9371: Determines all the sections for a course including
 9372: sections with students and sections containing other roles.
 9373: Incoming parameters: 
 9374: 
 9375: 1. domain
 9376: 2. course number 
 9377: 3. reference to array containing roles for which sections should 
 9378: be gathered (optional).
 9379: 4. reference to array containing status types for which sections 
 9380: should be gathered (optional).
 9381: 
 9382: If the third argument is undefined, sections are gathered for any role. 
 9383: If the fourth argument is undefined, sections are gathered for any status.
 9384: Permissible values are 'active' or 'future' or 'previous'.
 9385:  
 9386: Returns section hash (keys are section IDs, values are
 9387: number of users in each section), subject to the
 9388: optional roles filter, optional status filter 
 9389: 
 9390: =cut
 9391: 
 9392: ###############################################
 9393: sub get_sections {
 9394:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9395:     if (!defined($cdom) || !defined($cnum)) {
 9396:         my $cid =  $env{'request.course.id'};
 9397: 
 9398: 	return if (!defined($cid));
 9399: 
 9400:         $cdom = $env{'course.'.$cid.'.domain'};
 9401:         $cnum = $env{'course.'.$cid.'.num'};
 9402:     }
 9403: 
 9404:     my %sectioncount;
 9405:     my $now = time;
 9406: 
 9407:     my $check_students = 1;
 9408:     my $only_students = 0;
 9409:     if (ref($possible_roles) eq 'ARRAY') {
 9410:         if (grep(/^st$/,@{$possible_roles})) {
 9411:             if (@{$possible_roles} == 1) {
 9412:                 $only_students = 1;
 9413:             }
 9414:         } else {
 9415:             $check_students = 0;
 9416:         }
 9417:     }
 9418: 
 9419:     if ($check_students) { 
 9420: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9421: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9422: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9423:         my $start_index = &Apache::loncoursedata::CL_START();
 9424:         my $end_index = &Apache::loncoursedata::CL_END();
 9425:         my $status;
 9426: 	while (my ($student,$data) = each(%$classlist)) {
 9427: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9428: 				                     $data->[$status_index],
 9429:                                                      $data->[$start_index],
 9430:                                                      $data->[$end_index]);
 9431:             if ($stu_status eq 'Active') {
 9432:                 $status = 'active';
 9433:             } elsif ($end < $now) {
 9434:                 $status = 'previous';
 9435:             } elsif ($start > $now) {
 9436:                 $status = 'future';
 9437:             } 
 9438: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9439:                 if ((!defined($possible_status)) || (($status ne '') && 
 9440:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9441: 		    $sectioncount{$section}++;
 9442:                 }
 9443: 	    }
 9444: 	}
 9445:     }
 9446:     if ($only_students) {
 9447:         return %sectioncount;
 9448:     }
 9449:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9450:     foreach my $user (sort(keys(%courseroles))) {
 9451: 	if ($user !~ /^(\w{2})/) { next; }
 9452: 	my ($role) = ($user =~ /^(\w{2})/);
 9453: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9454: 	my ($section,$status);
 9455: 	if ($role eq 'cr' &&
 9456: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9457: 	    $section=$1;
 9458: 	}
 9459: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9460: 	if (!defined($section) || $section eq '-1') { next; }
 9461:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9462:         if ($end == -1 && $start == -1) {
 9463:             next; #deleted role
 9464:         }
 9465:         if (!defined($possible_status)) { 
 9466:             $sectioncount{$section}++;
 9467:         } else {
 9468:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9469:                 $status = 'active';
 9470:             } elsif ($end < $now) {
 9471:                 $status = 'future';
 9472:             } elsif ($start > $now) {
 9473:                 $status = 'previous';
 9474:             }
 9475:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9476:                 $sectioncount{$section}++;
 9477:             }
 9478:         }
 9479:     }
 9480:     return %sectioncount;
 9481: }
 9482: 
 9483: ###############################################
 9484: 
 9485: =pod
 9486: 
 9487: =item * &get_course_users()
 9488: 
 9489: Retrieves usernames:domains for users in the specified course
 9490: with specific role(s), and access status. 
 9491: 
 9492: Incoming parameters:
 9493: 1. course domain
 9494: 2. course number
 9495: 3. access status: users must have - either active, 
 9496: previous, future, or all.
 9497: 4. reference to array of permissible roles
 9498: 5. reference to array of section restrictions (optional)
 9499: 6. reference to results object (hash of hashes).
 9500: 7. reference to optional userdata hash
 9501: 8. reference to optional statushash
 9502: 9. flag if privileged users (except those set to unhide in
 9503:    course settings) should be excluded    
 9504: Keys of top level results hash are roles.
 9505: Keys of inner hashes are username:domain, with 
 9506: values set to access type.
 9507: Optional userdata hash returns an array with arguments in the 
 9508: same order as loncoursedata::get_classlist() for student data.
 9509: 
 9510: Optional statushash returns
 9511: 
 9512: Entries for end, start, section and status are blank because
 9513: of the possibility of multiple values for non-student roles.
 9514: 
 9515: =cut
 9516: 
 9517: ###############################################
 9518: 
 9519: sub get_course_users {
 9520:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9521:     my %idx = ();
 9522:     my %seclists;
 9523: 
 9524:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9525:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9526:     $idx{end} = &Apache::loncoursedata::CL_END();
 9527:     $idx{start} = &Apache::loncoursedata::CL_START();
 9528:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9529:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9530:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9531:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9532: 
 9533:     if (grep(/^st$/,@{$roles})) {
 9534:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9535:         my $now = time;
 9536:         foreach my $student (keys(%{$classlist})) {
 9537:             my $match = 0;
 9538:             my $secmatch = 0;
 9539:             my $section = $$classlist{$student}[$idx{section}];
 9540:             my $status = $$classlist{$student}[$idx{status}];
 9541:             if ($section eq '') {
 9542:                 $section = 'none';
 9543:             }
 9544:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9545:                 if (grep(/^all$/,@{$sections})) {
 9546:                     $secmatch = 1;
 9547:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9548:                     if (grep(/^none$/,@{$sections})) {
 9549:                         $secmatch = 1;
 9550:                     }
 9551:                 } else {  
 9552: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9553: 		        $secmatch = 1;
 9554:                     }
 9555: 		}
 9556:                 if (!$secmatch) {
 9557:                     next;
 9558:                 }
 9559:             }
 9560:             if (defined($$types{'active'})) {
 9561:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9562:                     push(@{$$users{st}{$student}},'active');
 9563:                     $match = 1;
 9564:                 }
 9565:             }
 9566:             if (defined($$types{'previous'})) {
 9567:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9568:                     push(@{$$users{st}{$student}},'previous');
 9569:                     $match = 1;
 9570:                 }
 9571:             }
 9572:             if (defined($$types{'future'})) {
 9573:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9574:                     push(@{$$users{st}{$student}},'future');
 9575:                     $match = 1;
 9576:                 }
 9577:             }
 9578:             if ($match) {
 9579:                 push(@{$seclists{$student}},$section);
 9580:                 if (ref($userdata) eq 'HASH') {
 9581:                     $$userdata{$student} = $$classlist{$student};
 9582:                 }
 9583:                 if (ref($statushash) eq 'HASH') {
 9584:                     $statushash->{$student}{'st'}{$section} = $status;
 9585:                 }
 9586:             }
 9587:         }
 9588:     }
 9589:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9590:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9591:         my $now = time;
 9592:         my %displaystatus = ( previous => 'Expired',
 9593:                               active   => 'Active',
 9594:                               future   => 'Future',
 9595:                             );
 9596:         my (%nothide,@possdoms);
 9597:         if ($hidepriv) {
 9598:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9599:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9600:                 if ($user !~ /:/) {
 9601:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9602:                 } else {
 9603:                     $nothide{$user} = 1;
 9604:                 }
 9605:             }
 9606:             my @possdoms = ($cdom);
 9607:             if ($coursehash{'checkforpriv'}) {
 9608:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9609:             }
 9610:         }
 9611:         foreach my $person (sort(keys(%coursepersonnel))) {
 9612:             my $match = 0;
 9613:             my $secmatch = 0;
 9614:             my $status;
 9615:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9616:             $user =~ s/:$//;
 9617:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9618:             if ($end == -1 || $start == -1) {
 9619:                 next;
 9620:             }
 9621:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9622:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9623:                 my ($uname,$udom) = split(/:/,$user);
 9624:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9625:                     if (grep(/^all$/,@{$sections})) {
 9626:                         $secmatch = 1;
 9627:                     } elsif ($usec eq '') {
 9628:                         if (grep(/^none$/,@{$sections})) {
 9629:                             $secmatch = 1;
 9630:                         }
 9631:                     } else {
 9632:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9633:                             $secmatch = 1;
 9634:                         }
 9635:                     }
 9636:                     if (!$secmatch) {
 9637:                         next;
 9638:                     }
 9639:                 }
 9640:                 if ($usec eq '') {
 9641:                     $usec = 'none';
 9642:                 }
 9643:                 if ($uname ne '' && $udom ne '') {
 9644:                     if ($hidepriv) {
 9645:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9646:                             (!$nothide{$uname.':'.$udom})) {
 9647:                             next;
 9648:                         }
 9649:                     }
 9650:                     if ($end > 0 && $end < $now) {
 9651:                         $status = 'previous';
 9652:                     } elsif ($start > $now) {
 9653:                         $status = 'future';
 9654:                     } else {
 9655:                         $status = 'active';
 9656:                     }
 9657:                     foreach my $type (keys(%{$types})) { 
 9658:                         if ($status eq $type) {
 9659:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9660:                                 push(@{$$users{$role}{$user}},$type);
 9661:                             }
 9662:                             $match = 1;
 9663:                         }
 9664:                     }
 9665:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9666:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9667: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9668:                         }
 9669:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9670:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9671:                         }
 9672:                         if (ref($statushash) eq 'HASH') {
 9673:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9674:                         }
 9675:                     }
 9676:                 }
 9677:             }
 9678:         }
 9679:         if (grep(/^ow$/,@{$roles})) {
 9680:             if ((defined($cdom)) && (defined($cnum))) {
 9681:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9682:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9683:                     my $owner = $csettings{'internal.courseowner'};
 9684:                     next if ($owner eq '');
 9685:                     my ($ownername,$ownerdom);
 9686:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9687:                         $ownername = $1;
 9688:                         $ownerdom = $2;
 9689:                     } else {
 9690:                         $ownername = $owner;
 9691:                         $ownerdom = $cdom;
 9692:                         $owner = $ownername.':'.$ownerdom;
 9693:                     }
 9694:                     @{$$users{'ow'}{$owner}} = 'any';
 9695:                     if (defined($userdata) && 
 9696: 			!exists($$userdata{$owner})) {
 9697: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9698:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9699:                             push(@{$seclists{$owner}},'none');
 9700:                         }
 9701:                         if (ref($statushash) eq 'HASH') {
 9702:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9703:                         }
 9704: 		    }
 9705:                 }
 9706:             }
 9707:         }
 9708:         foreach my $user (keys(%seclists)) {
 9709:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9710:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9711:         }
 9712:     }
 9713:     return;
 9714: }
 9715: 
 9716: sub get_user_info {
 9717:     my ($udom,$uname,$idx,$userdata) = @_;
 9718:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9719: 	&plainname($uname,$udom,'lastname');
 9720:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9721:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9722:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9723:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9724:     return;
 9725: }
 9726: 
 9727: ###############################################
 9728: 
 9729: =pod
 9730: 
 9731: =item * &get_user_quota()
 9732: 
 9733: Retrieves quota assigned for storage of user files.
 9734: Default is to report quota for portfolio files.
 9735: 
 9736: Incoming parameters:
 9737: 1. user's username
 9738: 2. user's domain
 9739: 3. quota name - portfolio, author, or course
 9740:    (if no quota name provided, defaults to portfolio).
 9741: 4. crstype - official, unofficial, textbook, placement or community, 
 9742:    if quota name is course
 9743: 
 9744: Returns:
 9745: 1. Disk quota (in MB) assigned to student.
 9746: 2. (Optional) Type of setting: custom or default
 9747:    (individually assigned or default for user's 
 9748:    institutional status).
 9749: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9750:    or student - types as defined in localenroll::inst_usertypes 
 9751:    for user's domain, which determines default quota for user.
 9752: 4. (Optional) - Default quota which would apply to the user.
 9753: 
 9754: If a value has been stored in the user's environment, 
 9755: it will return that, otherwise it returns the maximal default
 9756: defined for the user's institutional status(es) in the domain.
 9757: 
 9758: =cut
 9759: 
 9760: ###############################################
 9761: 
 9762: 
 9763: sub get_user_quota {
 9764:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9765:     my ($quota,$quotatype,$settingstatus,$defquota);
 9766:     if (!defined($udom)) {
 9767:         $udom = $env{'user.domain'};
 9768:     }
 9769:     if (!defined($uname)) {
 9770:         $uname = $env{'user.name'};
 9771:     }
 9772:     if (($udom eq '' || $uname eq '') ||
 9773:         ($udom eq 'public') && ($uname eq 'public')) {
 9774:         $quota = 0;
 9775:         $quotatype = 'default';
 9776:         $defquota = 0; 
 9777:     } else {
 9778:         my $inststatus;
 9779:         if ($quotaname eq 'course') {
 9780:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9781:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9782:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9783:             } else {
 9784:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9785:                 $quota = $cenv{'internal.uploadquota'};
 9786:             }
 9787:         } else {
 9788:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9789:                 if ($quotaname eq 'author') {
 9790:                     $quota = $env{'environment.authorquota'};
 9791:                 } else {
 9792:                     $quota = $env{'environment.portfolioquota'};
 9793:                 }
 9794:                 $inststatus = $env{'environment.inststatus'};
 9795:             } else {
 9796:                 my %userenv = 
 9797:                     &Apache::lonnet::get('environment',['portfolioquota',
 9798:                                          'authorquota','inststatus'],$udom,$uname);
 9799:                 my ($tmp) = keys(%userenv);
 9800:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9801:                     if ($quotaname eq 'author') {
 9802:                         $quota = $userenv{'authorquota'};
 9803:                     } else {
 9804:                         $quota = $userenv{'portfolioquota'};
 9805:                     }
 9806:                     $inststatus = $userenv{'inststatus'};
 9807:                 } else {
 9808:                     undef(%userenv);
 9809:                 }
 9810:             }
 9811:         }
 9812:         if ($quota eq '' || wantarray) {
 9813:             if ($quotaname eq 'course') {
 9814:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9815:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9816:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
 9817:                     ($crstype eq 'placement')) { 
 9818:                     $defquota = $domdefs{$crstype.'quota'};
 9819:                 }
 9820:                 if ($defquota eq '') {
 9821:                     $defquota = 500;
 9822:                 }
 9823:             } else {
 9824:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9825:             }
 9826:             if ($quota eq '') {
 9827:                 $quota = $defquota;
 9828:                 $quotatype = 'default';
 9829:             } else {
 9830:                 $quotatype = 'custom';
 9831:             }
 9832:         }
 9833:     }
 9834:     if (wantarray) {
 9835:         return ($quota,$quotatype,$settingstatus,$defquota);
 9836:     } else {
 9837:         return $quota;
 9838:     }
 9839: }
 9840: 
 9841: ###############################################
 9842: 
 9843: =pod
 9844: 
 9845: =item * &default_quota()
 9846: 
 9847: Retrieves default quota assigned for storage of user portfolio files,
 9848: given an (optional) user's institutional status.
 9849: 
 9850: Incoming parameters:
 9851: 
 9852: 1. domain
 9853: 2. (Optional) institutional status(es).  This is a : separated list of 
 9854:    status types (e.g., faculty, staff, student etc.)
 9855:    which apply to the user for whom the default is being retrieved.
 9856:    If the institutional status string in undefined, the domain
 9857:    default quota will be returned.
 9858: 3.  quota name - portfolio, author, or course
 9859:    (if no quota name provided, defaults to portfolio).
 9860: 
 9861: Returns:
 9862: 
 9863: 1. Default disk quota (in MB) for user portfolios in the domain.
 9864: 2. (Optional) institutional type which determined the value of the
 9865:    default quota.
 9866: 
 9867: If a value has been stored in the domain's configuration db,
 9868: it will return that, otherwise it returns 20 (for backwards 
 9869: compatibility with domains which have not set up a configuration
 9870: db file; the original statically defined portfolio quota was 20 MB). 
 9871: 
 9872: If the user's status includes multiple types (e.g., staff and student),
 9873: the largest default quota which applies to the user determines the
 9874: default quota returned.
 9875: 
 9876: =cut
 9877: 
 9878: ###############################################
 9879: 
 9880: 
 9881: sub default_quota {
 9882:     my ($udom,$inststatus,$quotaname) = @_;
 9883:     my ($defquota,$settingstatus);
 9884:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9885:                                             ['quotas'],$udom);
 9886:     my $key = 'defaultquota';
 9887:     if ($quotaname eq 'author') {
 9888:         $key = 'authorquota';
 9889:     }
 9890:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9891:         if ($inststatus ne '') {
 9892:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9893:             foreach my $item (@statuses) {
 9894:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9895:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9896:                         if ($defquota eq '') {
 9897:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9898:                             $settingstatus = $item;
 9899:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9900:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9901:                             $settingstatus = $item;
 9902:                         }
 9903:                     }
 9904:                 } elsif ($key eq 'defaultquota') {
 9905:                     if ($quotahash{'quotas'}{$item} ne '') {
 9906:                         if ($defquota eq '') {
 9907:                             $defquota = $quotahash{'quotas'}{$item};
 9908:                             $settingstatus = $item;
 9909:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9910:                             $defquota = $quotahash{'quotas'}{$item};
 9911:                             $settingstatus = $item;
 9912:                         }
 9913:                     }
 9914:                 }
 9915:             }
 9916:         }
 9917:         if ($defquota eq '') {
 9918:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9919:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9920:             } elsif ($key eq 'defaultquota') {
 9921:                 $defquota = $quotahash{'quotas'}{'default'};
 9922:             }
 9923:             $settingstatus = 'default';
 9924:             if ($defquota eq '') {
 9925:                 if ($quotaname eq 'author') {
 9926:                     $defquota = 500;
 9927:                 }
 9928:             }
 9929:         }
 9930:     } else {
 9931:         $settingstatus = 'default';
 9932:         if ($quotaname eq 'author') {
 9933:             $defquota = 500;
 9934:         } else {
 9935:             $defquota = 20;
 9936:         }
 9937:     }
 9938:     if (wantarray) {
 9939:         return ($defquota,$settingstatus);
 9940:     } else {
 9941:         return $defquota;
 9942:     }
 9943: }
 9944: 
 9945: ###############################################
 9946: 
 9947: =pod
 9948: 
 9949: =item * &excess_filesize_warning()
 9950: 
 9951: Returns warning message if upload of file to authoring space, or copying
 9952: of existing file within authoring space will cause quota for the authoring
 9953: space to be exceeded.
 9954: 
 9955: Same, if upload of a file directly to a course/community via Course Editor
 9956: will cause quota for uploaded content for the course to be exceeded.
 9957: 
 9958: Inputs: 7 
 9959: 1. username or coursenum
 9960: 2. domain
 9961: 3. context ('author' or 'course')
 9962: 4. filename of file for which action is being requested
 9963: 5. filesize (kB) of file
 9964: 6. action being taken: copy or upload.
 9965: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
 9966: 
 9967: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9968:          otherwise return null.
 9969: 
 9970: =back
 9971: 
 9972: =cut
 9973: 
 9974: sub excess_filesize_warning {
 9975:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9976:     my $current_disk_usage = 0;
 9977:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9978:     if ($context eq 'author') {
 9979:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9980:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9981:     } else {
 9982:         foreach my $subdir ('docs','supplemental') {
 9983:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9984:         }
 9985:     }
 9986:     $disk_quota = int($disk_quota * 1000);
 9987:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9988:         return '<p class="LC_warning">'.
 9989:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9990:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9991:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9992:                             $disk_quota,$current_disk_usage).
 9993:                '</p>';
 9994:     }
 9995:     return;
 9996: }
 9997: 
 9998: ###############################################
 9999: 
10000: 
10001: 
10002: 
10003: sub get_secgrprole_info {
10004:     my ($cdom,$cnum,$needroles,$type)  = @_;
10005:     my %sections_count = &get_sections($cdom,$cnum);
10006:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10007:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10008:     my @groups = sort(keys(%curr_groups));
10009:     my $allroles = [];
10010:     my $rolehash;
10011:     my $accesshash = {
10012:                      active => 'Currently has access',
10013:                      future => 'Will have future access',
10014:                      previous => 'Previously had access',
10015:                   };
10016:     if ($needroles) {
10017:         $rolehash = {'all' => 'all'};
10018:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10019: 	if (&Apache::lonnet::error(%user_roles)) {
10020: 	    undef(%user_roles);
10021: 	}
10022:         foreach my $item (keys(%user_roles)) {
10023:             my ($role)=split(/\:/,$item,2);
10024:             if ($role eq 'cr') { next; }
10025:             if ($role =~ /^cr/) {
10026:                 $$rolehash{$role} = (split('/',$role))[3];
10027:             } else {
10028:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10029:             }
10030:         }
10031:         foreach my $key (sort(keys(%{$rolehash}))) {
10032:             push(@{$allroles},$key);
10033:         }
10034:         push (@{$allroles},'st');
10035:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10036:     }
10037:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10038: }
10039: 
10040: sub user_picker {
10041:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom) = @_;
10042:     my $currdom = $dom;
10043:     my @alldoms = &Apache::lonnet::all_domains();
10044:     if (@alldoms == 1) {
10045:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10046:                                                ['directorysrch'],$alldoms[0]);
10047:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10048:         my $showdom = $domdesc;
10049:         if ($showdom eq '') {
10050:             $showdom = $dom;
10051:         }
10052:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10053:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10054:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10055:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10056:             }
10057:         }
10058:     }
10059:     my %curr_selected = (
10060:                         srchin => 'dom',
10061:                         srchby => 'lastname',
10062:                       );
10063:     my $srchterm;
10064:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10065:         if ($srch->{'srchby'} ne '') {
10066:             $curr_selected{'srchby'} = $srch->{'srchby'};
10067:         }
10068:         if ($srch->{'srchin'} ne '') {
10069:             $curr_selected{'srchin'} = $srch->{'srchin'};
10070:         }
10071:         if ($srch->{'srchtype'} ne '') {
10072:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10073:         }
10074:         if ($srch->{'srchdomain'} ne '') {
10075:             $currdom = $srch->{'srchdomain'};
10076:         }
10077:         $srchterm = $srch->{'srchterm'};
10078:     }
10079:     my %html_lt=&Apache::lonlocal::texthash(
10080:                     'usr'       => 'Search criteria',
10081:                     'doma'      => 'Domain/institution to search',
10082:                     'uname'     => 'username',
10083:                     'lastname'  => 'last name',
10084:                     'lastfirst' => 'last name, first name',
10085:                     'crs'       => 'in this course',
10086:                     'dom'       => 'in selected LON-CAPA domain', 
10087:                     'alc'       => 'all LON-CAPA',
10088:                     'instd'     => 'in institutional directory for selected domain',
10089:                     'exact'     => 'is',
10090:                     'contains'  => 'contains',
10091:                     'begins'    => 'begins with',
10092:                                        );
10093:     my %js_lt=&Apache::lonlocal::texthash(
10094:                     'youm'      => "You must include some text to search for.",
10095:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10096:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10097:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10098:                     'ymcd'      => "You must choose a domain when using a domain search.",
10099:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10100:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10101:                      'thfo'     => "The following need to be corrected before the search can be run:",
10102:                                        );
10103:     &html_escape(\%html_lt);
10104:     &js_escape(\%js_lt);
10105:     my $domform;
10106:     my $allow_blank = 1;
10107:     if ($fixeddom) {
10108:         $allow_blank = 0;
10109:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10110:     } else {
10111:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10112:     }
10113:     my $srchinsel = ' <select name="srchin">';
10114: 
10115:     my @srchins = ('crs','dom','alc','instd');
10116: 
10117:     foreach my $option (@srchins) {
10118:         # FIXME 'alc' option unavailable until 
10119:         #       loncreateuser::print_user_query_page()
10120:         #       has been completed.
10121:         next if ($option eq 'alc');
10122:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10123:         next if ($option eq 'crs' && !$env{'request.course.id'});
10124:         if ($curr_selected{'srchin'} eq $option) {
10125:             $srchinsel .= ' 
10126:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10127:         } else {
10128:             $srchinsel .= '
10129:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10130:         }
10131:     }
10132:     $srchinsel .= "\n  </select>\n";
10133: 
10134:     my $srchbysel =  ' <select name="srchby">';
10135:     foreach my $option ('lastname','lastfirst','uname') {
10136:         if ($curr_selected{'srchby'} eq $option) {
10137:             $srchbysel .= '
10138:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10139:         } else {
10140:             $srchbysel .= '
10141:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10142:          }
10143:     }
10144:     $srchbysel .= "\n  </select>\n";
10145: 
10146:     my $srchtypesel = ' <select name="srchtype">';
10147:     foreach my $option ('begins','contains','exact') {
10148:         if ($curr_selected{'srchtype'} eq $option) {
10149:             $srchtypesel .= '
10150:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10151:         } else {
10152:             $srchtypesel .= '
10153:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10154:         }
10155:     }
10156:     $srchtypesel .= "\n  </select>\n";
10157: 
10158:     my ($newuserscript,$new_user_create);
10159:     my $context_dom = $env{'request.role.domain'};
10160:     if ($context eq 'requestcrs') {
10161:         if ($env{'form.coursedom'} ne '') { 
10162:             $context_dom = $env{'form.coursedom'};
10163:         }
10164:     }
10165:     if ($forcenewuser) {
10166:         if (ref($srch) eq 'HASH') {
10167:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10168:                 if ($cancreate) {
10169:                     $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>';
10170:                 } else {
10171:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10172:                     my %usertypetext = (
10173:                         official   => 'institutional',
10174:                         unofficial => 'non-institutional',
10175:                     );
10176:                     $new_user_create = '<p class="LC_warning">'
10177:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10178:                                       .' '
10179:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10180:                                           ,'<a href="'.$helplink.'">','</a>')
10181:                                       .'</p><br />';
10182:                 }
10183:             }
10184:         }
10185: 
10186:         $newuserscript = <<"ENDSCRIPT";
10187: 
10188: function setSearch(createnew,callingForm) {
10189:     if (createnew == 1) {
10190:         for (var i=0; i<callingForm.srchby.length; i++) {
10191:             if (callingForm.srchby.options[i].value == 'uname') {
10192:                 callingForm.srchby.selectedIndex = i;
10193:             }
10194:         }
10195:         for (var i=0; i<callingForm.srchin.length; i++) {
10196:             if ( callingForm.srchin.options[i].value == 'dom') {
10197: 		callingForm.srchin.selectedIndex = i;
10198:             }
10199:         }
10200:         for (var i=0; i<callingForm.srchtype.length; i++) {
10201:             if (callingForm.srchtype.options[i].value == 'exact') {
10202:                 callingForm.srchtype.selectedIndex = i;
10203:             }
10204:         }
10205:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10206:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10207:                 callingForm.srchdomain.selectedIndex = i;
10208:             }
10209:         }
10210:     }
10211: }
10212: ENDSCRIPT
10213: 
10214:     }
10215: 
10216:     my $output = <<"END_BLOCK";
10217: <script type="text/javascript">
10218: // <![CDATA[
10219: function validateEntry(callingForm) {
10220: 
10221:     var checkok = 1;
10222:     var srchin;
10223:     for (var i=0; i<callingForm.srchin.length; i++) {
10224: 	if ( callingForm.srchin[i].checked ) {
10225: 	    srchin = callingForm.srchin[i].value;
10226: 	}
10227:     }
10228: 
10229:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10230:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10231:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10232:     var srchterm =  callingForm.srchterm.value;
10233:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10234:     var msg = "";
10235: 
10236:     if (srchterm == "") {
10237:         checkok = 0;
10238:         msg += "$js_lt{'youm'}\\n";
10239:     }
10240: 
10241:     if (srchtype== 'begins') {
10242:         if (srchterm.length < 2) {
10243:             checkok = 0;
10244:             msg += "$js_lt{'thte'}\\n";
10245:         }
10246:     }
10247: 
10248:     if (srchtype== 'contains') {
10249:         if (srchterm.length < 3) {
10250:             checkok = 0;
10251:             msg += "$js_lt{'thet'}\\n";
10252:         }
10253:     }
10254:     if (srchin == 'instd') {
10255:         if (srchdomain == '') {
10256:             checkok = 0;
10257:             msg += "$js_lt{'yomc'}\\n";
10258:         }
10259:     }
10260:     if (srchin == 'dom') {
10261:         if (srchdomain == '') {
10262:             checkok = 0;
10263:             msg += "$js_lt{'ymcd'}\\n";
10264:         }
10265:     }
10266:     if (srchby == 'lastfirst') {
10267:         if (srchterm.indexOf(",") == -1) {
10268:             checkok = 0;
10269:             msg += "$js_lt{'whus'}\\n";
10270:         }
10271:         if (srchterm.indexOf(",") == srchterm.length -1) {
10272:             checkok = 0;
10273:             msg += "$js_lt{'whse'}\\n";
10274:         }
10275:     }
10276:     if (checkok == 0) {
10277:         alert("$js_lt{'thfo'}\\n"+msg);
10278:         return;
10279:     }
10280:     if (checkok == 1) {
10281:         callingForm.submit();
10282:     }
10283: }
10284: 
10285: $newuserscript
10286: 
10287: // ]]>
10288: </script>
10289: 
10290: $new_user_create
10291: 
10292: END_BLOCK
10293: 
10294:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10295:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10296:                $domform.
10297:                &Apache::lonhtmlcommon::row_closure().
10298:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10299:                $srchbysel.
10300:                $srchtypesel. 
10301:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10302:                $srchinsel.
10303:                &Apache::lonhtmlcommon::row_closure(1). 
10304:                &Apache::lonhtmlcommon::end_pick_box().
10305:                '<br />';
10306:     return ($output,1);
10307: }
10308: 
10309: sub user_rule_check {
10310:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10311:     my ($response,%inst_response);
10312:     if (ref($usershash) eq 'HASH') {
10313:         if (keys(%{$usershash}) > 1) {
10314:             my (%by_username,%by_id,%userdoms);
10315:             my $checkid; 
10316:             if (ref($checks) eq 'HASH') {
10317:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10318:                     $checkid = 1;
10319:                 }
10320:             }
10321:             foreach my $user (keys(%{$usershash})) {
10322:                 my ($uname,$udom) = split(/:/,$user);
10323:                 if ($checkid) {
10324:                     if (ref($usershash->{$user}) eq 'HASH') {
10325:                         if ($usershash->{$user}->{'id'} ne '') {
10326:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10327:                             $userdoms{$udom} = 1;
10328:                             if (ref($inst_results) eq 'HASH') {
10329:                                 $inst_results->{$uname.':'.$udom} = {};
10330:                             }
10331:                         }
10332:                     }
10333:                 } else {
10334:                     $by_username{$udom}{$uname} = 1;
10335:                     $userdoms{$udom} = 1;
10336:                     if (ref($inst_results) eq 'HASH') {
10337:                         $inst_results->{$uname.':'.$udom} = {};
10338:                     }
10339:                 }
10340:             }
10341:             foreach my $udom (keys(%userdoms)) {
10342:                 if (!$got_rules->{$udom}) {
10343:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10344:                                                              ['usercreation'],$udom);
10345:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10346:                         foreach my $item ('username','id') {
10347:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10348:                                 $$curr_rules{$udom}{$item} =
10349:                                     $domconfig{'usercreation'}{$item.'_rule'};
10350:                             }
10351:                         }
10352:                     }
10353:                     $got_rules->{$udom} = 1;
10354:                 }
10355:             }
10356:             if ($checkid) {
10357:                 foreach my $udom (keys(%by_id)) {
10358:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10359:                     if ($outcome eq 'ok') {
10360:                         foreach my $id (keys(%{$by_id{$udom}})) {
10361:                             my $uname = $by_id{$udom}{$id};
10362:                             $inst_response{$uname.':'.$udom} = $outcome;
10363:                         }
10364:                         if (ref($results) eq 'HASH') {
10365:                             foreach my $uname (keys(%{$results})) {
10366:                                 if (exists($inst_response{$uname.':'.$udom})) {
10367:                                     $inst_response{$uname.':'.$udom} = $outcome;
10368:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10369:                                 }
10370:                             }
10371:                         }
10372:                     }
10373:                 }
10374:             } else {
10375:                 foreach my $udom (keys(%by_username)) {
10376:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10377:                     if ($outcome eq 'ok') {
10378:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10379:                             $inst_response{$uname.':'.$udom} = $outcome;
10380:                         }
10381:                         if (ref($results) eq 'HASH') {
10382:                             foreach my $uname (keys(%{$results})) {
10383:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10384:                             }
10385:                         }
10386:                     }
10387:                 }
10388:             }
10389:         } elsif (keys(%{$usershash}) == 1) {
10390:             my $user = (keys(%{$usershash}))[0];
10391:             my ($uname,$udom) = split(/:/,$user);
10392:             if (($udom ne '') && ($uname ne '')) {
10393:                 if (ref($usershash->{$user}) eq 'HASH') {
10394:                     if (ref($checks) eq 'HASH') {
10395:                         if (defined($checks->{'username'})) {
10396:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10397:                                 &Apache::lonnet::get_instuser($udom,$uname);
10398:                         } elsif (defined($checks->{'id'})) {
10399:                             if ($usershash->{$user}->{'id'} ne '') {
10400:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10401:                                     &Apache::lonnet::get_instuser($udom,undef,
10402:                                                                   $usershash->{$user}->{'id'});
10403:                             } else {
10404:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10405:                                     &Apache::lonnet::get_instuser($udom,$uname);
10406:                             }
10407:                         }
10408:                     } else {
10409:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10410:                             &Apache::lonnet::get_instuser($udom,$uname);
10411:                        return;
10412:                     }
10413:                     if (!$got_rules->{$udom}) {
10414:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10415:                                                                  ['usercreation'],$udom);
10416:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10417:                             foreach my $item ('username','id') {
10418:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10419:                                    $$curr_rules{$udom}{$item} = 
10420:                                        $domconfig{'usercreation'}{$item.'_rule'};
10421:                                 }
10422:                             }
10423:                         }
10424:                         $got_rules->{$udom} = 1;
10425:                     }
10426:                 }
10427:             } else {
10428:                 return;
10429:             }
10430:         } else {
10431:             return;
10432:         }
10433:         foreach my $user (keys(%{$usershash})) {
10434:             my ($uname,$udom) = split(/:/,$user);
10435:             next if (($udom eq '') || ($uname eq ''));
10436:             my $id;
10437:             if (ref($inst_results) eq 'HASH') {
10438:                 if (ref($inst_results->{$user}) eq 'HASH') {
10439:                     $id = $inst_results->{$user}->{'id'};
10440:                 }
10441:             }
10442:             if ($id eq '') { 
10443:                 if (ref($usershash->{$user})) {
10444:                     $id = $usershash->{$user}->{'id'};
10445:                 }
10446:             }
10447:             foreach my $item (keys(%{$checks})) {
10448:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10449:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10450:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10451:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10452:                                                                              $$curr_rules{$udom}{$item});
10453:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10454:                                 if ($rule_check{$rule}) {
10455:                                     $$rulematch{$user}{$item} = $rule;
10456:                                     if ($inst_response{$user} eq 'ok') {
10457:                                         if (ref($inst_results) eq 'HASH') {
10458:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10459:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10460:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10461:                                                 } elsif ($item eq 'id') {
10462:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10463:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10464:                                                     }
10465:                                                 }
10466:                                             }
10467:                                         }
10468:                                     }
10469:                                     last;
10470:                                 }
10471:                             }
10472:                         }
10473:                     }
10474:                 }
10475:             }
10476:         }
10477:     }
10478:     return;
10479: }
10480: 
10481: sub user_rule_formats {
10482:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10483:     my %text = ( 
10484:                  'username' => 'Usernames',
10485:                  'id'       => 'IDs',
10486:                );
10487:     my $output;
10488:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10489:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10490:         if (@{$ruleorder} > 0) {
10491:             $output = '<br />'.
10492:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10493:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10494:                       ' <ul>';
10495:             foreach my $rule (@{$ruleorder}) {
10496:                 if (ref($curr_rules) eq 'ARRAY') {
10497:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10498:                         if (ref($rules->{$rule}) eq 'HASH') {
10499:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10500:                                         $rules->{$rule}{'desc'}.'</li>';
10501:                         }
10502:                     }
10503:                 }
10504:             }
10505:             $output .= '</ul>';
10506:         }
10507:     }
10508:     return $output;
10509: }
10510: 
10511: sub instrule_disallow_msg {
10512:     my ($checkitem,$domdesc,$count,$mode) = @_;
10513:     my $response;
10514:     my %text = (
10515:                   item   => 'username',
10516:                   items  => 'usernames',
10517:                   match  => 'matches',
10518:                   do     => 'does',
10519:                   action => 'a username',
10520:                   one    => 'one',
10521:                );
10522:     if ($count > 1) {
10523:         $text{'item'} = 'usernames';
10524:         $text{'match'} ='match';
10525:         $text{'do'} = 'do';
10526:         $text{'action'} = 'usernames',
10527:         $text{'one'} = 'ones';
10528:     }
10529:     if ($checkitem eq 'id') {
10530:         $text{'items'} = 'IDs';
10531:         $text{'item'} = 'ID';
10532:         $text{'action'} = 'an ID';
10533:         if ($count > 1) {
10534:             $text{'item'} = 'IDs';
10535:             $text{'action'} = 'IDs';
10536:         }
10537:     }
10538:     $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 />';
10539:     if ($mode eq 'upload') {
10540:         if ($checkitem eq 'username') {
10541:             $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'}.");
10542:         } elsif ($checkitem eq 'id') {
10543:             $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.");
10544:         }
10545:     } elsif ($mode eq 'selfcreate') {
10546:         if ($checkitem eq 'id') {
10547:             $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.");
10548:         }
10549:     } else {
10550:         if ($checkitem eq 'username') {
10551:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10552:         } elsif ($checkitem eq 'id') {
10553:             $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.");
10554:         }
10555:     }
10556:     return $response;
10557: }
10558: 
10559: sub personal_data_fieldtitles {
10560:     my %fieldtitles = &Apache::lonlocal::texthash (
10561:                         id => 'Student/Employee ID',
10562:                         permanentemail => 'E-mail address',
10563:                         lastname => 'Last Name',
10564:                         firstname => 'First Name',
10565:                         middlename => 'Middle Name',
10566:                         generation => 'Generation',
10567:                         gen => 'Generation',
10568:                         inststatus => 'Affiliation',
10569:                    );
10570:     return %fieldtitles;
10571: }
10572: 
10573: sub sorted_inst_types {
10574:     my ($dom) = @_;
10575:     my ($usertypes,$order);
10576:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10577:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10578:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10579:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10580:     } else {
10581:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10582:     }
10583:     my $othertitle = &mt('All users');
10584:     if ($env{'request.course.id'}) {
10585:         $othertitle  = &mt('Any users');
10586:     }
10587:     my @types;
10588:     if (ref($order) eq 'ARRAY') {
10589:         @types = @{$order};
10590:     }
10591:     if (@types == 0) {
10592:         if (ref($usertypes) eq 'HASH') {
10593:             @types = sort(keys(%{$usertypes}));
10594:         }
10595:     }
10596:     if (keys(%{$usertypes}) > 0) {
10597:         $othertitle = &mt('Other users');
10598:     }
10599:     return ($othertitle,$usertypes,\@types);
10600: }
10601: 
10602: sub get_institutional_codes {
10603:     my ($settings,$allcourses,$LC_code) = @_;
10604: # Get complete list of course sections to update
10605:     my @currsections = ();
10606:     my @currxlists = ();
10607:     my $coursecode = $$settings{'internal.coursecode'};
10608: 
10609:     if ($$settings{'internal.sectionnums'} ne '') {
10610:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10611:     }
10612: 
10613:     if ($$settings{'internal.crosslistings'} ne '') {
10614:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10615:     }
10616: 
10617:     if (@currxlists > 0) {
10618:         foreach (@currxlists) {
10619:             if (m/^([^:]+):(\w*)$/) {
10620:                 unless (grep/^$1$/,@{$allcourses}) {
10621:                     push(@{$allcourses},$1);
10622:                     $$LC_code{$1} = $2;
10623:                 }
10624:             }
10625:         }
10626:     }
10627:  
10628:     if (@currsections > 0) {
10629:         foreach (@currsections) {
10630:             if (m/^(\w+):(\w*)$/) {
10631:                 my $sec = $coursecode.$1;
10632:                 my $lc_sec = $2;
10633:                 unless (grep/^$sec$/,@{$allcourses}) {
10634:                     push(@{$allcourses},$sec);
10635:                     $$LC_code{$sec} = $lc_sec;
10636:                 }
10637:             }
10638:         }
10639:     }
10640:     return;
10641: }
10642: 
10643: sub get_standard_codeitems {
10644:     return ('Year','Semester','Department','Number','Section');
10645: }
10646: 
10647: =pod
10648: 
10649: =head1 Slot Helpers
10650: 
10651: =over 4
10652: 
10653: =item * sorted_slots()
10654: 
10655: Sorts an array of slot names in order of an optional sort key,
10656: default sort is by slot start time (earliest first). 
10657: 
10658: Inputs:
10659: 
10660: =over 4
10661: 
10662: slotsarr  - Reference to array of unsorted slot names.
10663: 
10664: slots     - Reference to hash of hash, where outer hash keys are slot names.
10665: 
10666: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10667: 
10668: =back
10669: 
10670: Returns:
10671: 
10672: =over 4
10673: 
10674: sorted   - An array of slot names sorted by a specified sort key 
10675:            (default sort key is start time of the slot).
10676: 
10677: =back
10678: 
10679: =cut
10680: 
10681: 
10682: sub sorted_slots {
10683:     my ($slotsarr,$slots,$sortkey) = @_;
10684:     if ($sortkey eq '') {
10685:         $sortkey = 'starttime';
10686:     }
10687:     my @sorted;
10688:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10689:         @sorted =
10690:             sort {
10691:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10692:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10693:                      }
10694:                      if (ref($slots->{$a})) { return -1;}
10695:                      if (ref($slots->{$b})) { return 1;}
10696:                      return 0;
10697:                  } @{$slotsarr};
10698:     }
10699:     return @sorted;
10700: }
10701: 
10702: =pod
10703: 
10704: =item * get_future_slots()
10705: 
10706: Inputs:
10707: 
10708: =over 4
10709: 
10710: cnum - course number
10711: 
10712: cdom - course domain
10713: 
10714: now - current UNIX time
10715: 
10716: symb - optional symb
10717: 
10718: =back
10719: 
10720: Returns:
10721: 
10722: =over 4
10723: 
10724: sorted_reservable - ref to array of student_schedulable slots currently 
10725:                     reservable, ordered by end date of reservation period.
10726: 
10727: reservable_now - ref to hash of student_schedulable slots currently
10728:                  reservable.
10729: 
10730:     Keys in inner hash are:
10731:     (a) symb: either blank or symb to which slot use is restricted.
10732:     (b) endreserve: end date of reservation period.
10733:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10734:         selected.
10735: 
10736: sorted_future - ref to array of student_schedulable slots reservable in
10737:                 the future, ordered by start date of reservation period.
10738: 
10739: future_reservable - ref to hash of student_schedulable slots reservable
10740:                     in the future.
10741: 
10742:     Keys in inner hash are:
10743:     (a) symb: either blank or symb to which slot use is restricted.
10744:     (b) startreserve: start date of reservation period.
10745:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10746:         selected.
10747: 
10748: =back
10749: 
10750: =cut
10751: 
10752: sub get_future_slots {
10753:     my ($cnum,$cdom,$now,$symb) = @_;
10754:     my $map;
10755:     if ($symb) {
10756:         ($map) = &Apache::lonnet::decode_symb($symb);
10757:     }
10758:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10759:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10760:     foreach my $slot (keys(%slots)) {
10761:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10762:         if ($symb) {
10763:             if ($slots{$slot}->{'symb'} ne '') {
10764:                 my $canuse;
10765:                 my %oksymbs;
10766:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10767:                 map { $oksymbs{$_} = 1; } @slotsymbs;
10768:                 if ($oksymbs{$symb}) {
10769:                     $canuse = 1;
10770:                 } else {
10771:                     foreach my $item (@slotsymbs) {
10772:                         if ($item =~ /\.(page|sequence)$/) {
10773:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10774:                             if (($map ne '') && ($map eq $sloturl)) {
10775:                                 $canuse = 1;
10776:                                 last;
10777:                             }
10778:                         }
10779:                     }
10780:                 }
10781:                 next unless ($canuse);
10782:             }
10783:         }
10784:         if (($slots{$slot}->{'starttime'} > $now) &&
10785:             ($slots{$slot}->{'endtime'} > $now)) {
10786:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10787:                 my $userallowed = 0;
10788:                 if ($slots{$slot}->{'allowedsections'}) {
10789:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10790:                     if (!defined($env{'request.role.sec'})
10791:                         && grep(/^No section assigned$/,@allowed_sec)) {
10792:                         $userallowed=1;
10793:                     } else {
10794:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10795:                             $userallowed=1;
10796:                         }
10797:                     }
10798:                     unless ($userallowed) {
10799:                         if (defined($env{'request.course.groups'})) {
10800:                             my @groups = split(/:/,$env{'request.course.groups'});
10801:                             foreach my $group (@groups) {
10802:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10803:                                     $userallowed=1;
10804:                                     last;
10805:                                 }
10806:                             }
10807:                         }
10808:                     }
10809:                 }
10810:                 if ($slots{$slot}->{'allowedusers'}) {
10811:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10812:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10813:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10814:                         $userallowed = 1;
10815:                     }
10816:                 }
10817:                 next unless($userallowed);
10818:             }
10819:             my $startreserve = $slots{$slot}->{'startreserve'};
10820:             my $endreserve = $slots{$slot}->{'endreserve'};
10821:             my $symb = $slots{$slot}->{'symb'};
10822:             my $uniqueperiod;
10823:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10824:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10825:             }
10826:             if (($startreserve < $now) &&
10827:                 (!$endreserve || $endreserve > $now)) {
10828:                 my $lastres = $endreserve;
10829:                 if (!$lastres) {
10830:                     $lastres = $slots{$slot}->{'starttime'};
10831:                 }
10832:                 $reservable_now{$slot} = {
10833:                                            symb       => $symb,
10834:                                            endreserve => $lastres,
10835:                                            uniqueperiod => $uniqueperiod,
10836:                                          };
10837:             } elsif (($startreserve > $now) &&
10838:                      (!$endreserve || $endreserve > $startreserve)) {
10839:                 $future_reservable{$slot} = {
10840:                                               symb         => $symb,
10841:                                               startreserve => $startreserve,
10842:                                               uniqueperiod => $uniqueperiod,
10843:                                             };
10844:             }
10845:         }
10846:     }
10847:     my @unsorted_reservable = keys(%reservable_now);
10848:     if (@unsorted_reservable > 0) {
10849:         @sorted_reservable = 
10850:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10851:     }
10852:     my @unsorted_future = keys(%future_reservable);
10853:     if (@unsorted_future > 0) {
10854:         @sorted_future =
10855:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10856:     }
10857:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10858: }
10859: 
10860: =pod
10861: 
10862: =back
10863: 
10864: =head1 HTTP Helpers
10865: 
10866: =over 4
10867: 
10868: =item * &get_unprocessed_cgi($query,$possible_names)
10869: 
10870: Modify the %env hash to contain unprocessed CGI form parameters held in
10871: $query.  The parameters listed in $possible_names (an array reference),
10872: will be set in $env{'form.name'} if they do not already exist.
10873: 
10874: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10875: $possible_names is an ref to an array of form element names.  As an example:
10876: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10877: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10878: 
10879: =cut
10880: 
10881: sub get_unprocessed_cgi {
10882:   my ($query,$possible_names)= @_;
10883:   # $Apache::lonxml::debug=1;
10884:   foreach my $pair (split(/&/,$query)) {
10885:     my ($name, $value) = split(/=/,$pair);
10886:     $name = &unescape($name);
10887:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10888:       $value =~ tr/+/ /;
10889:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10890:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10891:     }
10892:   }
10893: }
10894: 
10895: =pod
10896: 
10897: =item * &cacheheader() 
10898: 
10899: returns cache-controlling header code
10900: 
10901: =cut
10902: 
10903: sub cacheheader {
10904:     unless ($env{'request.method'} eq 'GET') { return ''; }
10905:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10906:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10907:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10908:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10909:     return $output;
10910: }
10911: 
10912: =pod
10913: 
10914: =item * &no_cache($r) 
10915: 
10916: specifies header code to not have cache
10917: 
10918: =cut
10919: 
10920: sub no_cache {
10921:     my ($r) = @_;
10922:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10923: 	$env{'request.method'} ne 'GET') { return ''; }
10924:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10925:     $r->no_cache(1);
10926:     $r->header_out("Expires" => $date);
10927:     $r->header_out("Pragma" => "no-cache");
10928: }
10929: 
10930: sub content_type {
10931:     my ($r,$type,$charset) = @_;
10932:     if ($r) {
10933: 	#  Note that printout.pl calls this with undef for $r.
10934: 	&no_cache($r);
10935:     }
10936:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10937:     unless ($charset) {
10938: 	$charset=&Apache::lonlocal::current_encoding;
10939:     }
10940:     if ($charset) { $type.='; charset='.$charset; }
10941:     if ($r) {
10942: 	$r->content_type($type);
10943:     } else {
10944: 	print("Content-type: $type\n\n");
10945:     }
10946: }
10947: 
10948: =pod
10949: 
10950: =item * &add_to_env($name,$value) 
10951: 
10952: adds $name to the %env hash with value
10953: $value, if $name already exists, the entry is converted to an array
10954: reference and $value is added to the array.
10955: 
10956: =cut
10957: 
10958: sub add_to_env {
10959:   my ($name,$value)=@_;
10960:   if (defined($env{$name})) {
10961:     if (ref($env{$name})) {
10962:       #already have multiple values
10963:       push(@{ $env{$name} },$value);
10964:     } else {
10965:       #first time seeing multiple values, convert hash entry to an arrayref
10966:       my $first=$env{$name};
10967:       undef($env{$name});
10968:       push(@{ $env{$name} },$first,$value);
10969:     }
10970:   } else {
10971:     $env{$name}=$value;
10972:   }
10973: }
10974: 
10975: =pod
10976: 
10977: =item * &get_env_multiple($name) 
10978: 
10979: gets $name from the %env hash, it seemlessly handles the cases where multiple
10980: values may be defined and end up as an array ref.
10981: 
10982: returns an array of values
10983: 
10984: =cut
10985: 
10986: sub get_env_multiple {
10987:     my ($name) = @_;
10988:     my @values;
10989:     if (defined($env{$name})) {
10990:         # exists is it an array
10991:         if (ref($env{$name})) {
10992:             @values=@{ $env{$name} };
10993:         } else {
10994:             $values[0]=$env{$name};
10995:         }
10996:     }
10997:     return(@values);
10998: }
10999: 
11000: # Looks at given dependencies, and returns something depending on the context.
11001: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11002: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11003: # For all other contexts, returns ($output, $counter, $numpathchg).
11004: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11005: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
11006: # $numpathchg: integer with the number of cleaned up dependency paths.
11007: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11008: # \%mapping: hash reference clean path -> original path for all dependencies.
11009: # @param {string} actionurl - The path to the handler, indicative of the context.
11010: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11011: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11012: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11013: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
11014: # @return {Array} - array depending on the context (not a reference)
11015: sub ask_for_embedded_content {
11016:     # NOTE: documentation was added afterwards, it could be wrong
11017:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11018:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11019:         %currsubfile,%unused,$rem);
11020:     my $counter = 0;
11021:     my $numnew = 0;
11022:     my $numremref = 0;
11023:     my $numinvalid = 0;
11024:     my $numpathchg = 0;
11025:     my $numexisting = 0;
11026:     my $numunused = 0;
11027:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11028:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11029:     my $heading = &mt('Upload embedded files');
11030:     my $buttontext = &mt('Upload');
11031: 
11032:     # fills these variables based on the context:
11033:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11034:     # $path, $fileloc, $title, $rem, $filename
11035:     if ($env{'request.course.id'}) {
11036:         if ($actionurl eq '/adm/dependencies') {
11037:             $navmap = Apache::lonnavmaps::navmap->new();
11038:         }
11039:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11040:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11041:     }
11042:     if (($actionurl eq '/adm/portfolio') || 
11043:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11044:         my $current_path='/';
11045:         if ($env{'form.currentpath'}) {
11046:             $current_path = $env{'form.currentpath'};
11047:         }
11048:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11049:             $udom = $cdom;
11050:             $uname = $cnum;
11051:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11052:         } else {
11053:             $udom = $env{'user.domain'};
11054:             $uname = $env{'user.name'};
11055:             $url = '/userfiles/portfolio';
11056:         }
11057:         $toplevel = $url.'/';
11058:         $url .= $current_path;
11059:         $getpropath = 1;
11060:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11061:              ($actionurl eq '/adm/imsimport')) { 
11062:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11063:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11064:         $toplevel = $url;
11065:         if ($rest ne '') {
11066:             $url .= $rest;
11067:         }
11068:     } elsif ($actionurl eq '/adm/coursedocs') {
11069:         if (ref($args) eq 'HASH') {
11070:             $url = $args->{'docs_url'};
11071:             $toplevel = $url;
11072:             if ($args->{'context'} eq 'paste') {
11073:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11074:                 ($path) = 
11075:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11076:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11077:                 $fileloc =~ s{^/}{};
11078:             }
11079:         }
11080:     } elsif ($actionurl eq '/adm/dependencies')  {
11081:         if ($env{'request.course.id'} ne '') {
11082:             if (ref($args) eq 'HASH') {
11083:                 $url = $args->{'docs_url'};
11084:                 $title = $args->{'docs_title'};
11085:                 $toplevel = $url; 
11086:                 unless ($toplevel =~ m{^/}) {
11087:                     $toplevel = "/$url";
11088:                 }
11089:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11090:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11091:                     $path = $1;
11092:                 } else {
11093:                     ($path) =
11094:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11095:                 }
11096:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11097:                     $fileloc = $toplevel;
11098:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11099:                     my ($udom,$uname,$fname) =
11100:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11101:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11102:                 } else {
11103:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11104:                 }
11105:                 $fileloc =~ s{^/}{};
11106:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11107:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11108:             }
11109:         }
11110:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11111:         $udom = $cdom;
11112:         $uname = $cnum;
11113:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11114:         $toplevel = $url;
11115:         $path = $url;
11116:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11117:         $fileloc =~ s{^/}{};
11118:     }
11119:     
11120:     # parses the dependency paths to get some info
11121:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11122:     # $newfiles: hash URL -> 1 for new files or external URLs
11123:     # (will be completed later)
11124:     # $mapping:
11125:     #   for external URLs: external URL -> external URL
11126:     #   for relative paths: clean path -> original path
11127:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11128:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11129:     foreach my $file (keys(%{$allfiles})) {
11130:         my $embed_file;
11131:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11132:             $embed_file = $1;
11133:         } else {
11134:             $embed_file = $file;
11135:         }
11136:         my ($absolutepath,$cleaned_file);
11137:         if ($embed_file =~ m{^\w+://}) {
11138:             $cleaned_file = $embed_file;
11139:             $newfiles{$cleaned_file} = 1;
11140:             $mapping{$cleaned_file} = $embed_file;
11141:         } else {
11142:             $cleaned_file = &clean_path($embed_file);
11143:             if ($embed_file =~ m{^/}) {
11144:                 $absolutepath = $embed_file;
11145:             }
11146:             if ($cleaned_file =~ m{/}) {
11147:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11148:                 $path = &check_for_traversal($path,$url,$toplevel);
11149:                 my $item = $fname;
11150:                 if ($path ne '') {
11151:                     $item = $path.'/'.$fname;
11152:                     $subdependencies{$path}{$fname} = 1;
11153:                 } else {
11154:                     $dependencies{$item} = 1;
11155:                 }
11156:                 if ($absolutepath) {
11157:                     $mapping{$item} = $absolutepath;
11158:                 } else {
11159:                     $mapping{$item} = $embed_file;
11160:                 }
11161:             } else {
11162:                 $dependencies{$embed_file} = 1;
11163:                 if ($absolutepath) {
11164:                     $mapping{$cleaned_file} = $absolutepath;
11165:                 } else {
11166:                     $mapping{$cleaned_file} = $embed_file;
11167:                 }
11168:             }
11169:         }
11170:     }
11171:     
11172:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11173:     # and lists
11174:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11175:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11176:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11177:     #                                    the path had to be cleaned up
11178:     # $existing: hash clean path -> 1 if the file exists
11179:     # $numexisting: number of keys in $existing
11180:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11181:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11182:     #                                      dependency subdirectories that are
11183:     #                                      not listed as dependencies, with some exceptions using $rem
11184:     my $dirptr = 16384;
11185:     foreach my $path (keys(%subdependencies)) {
11186:         $currsubfile{$path} = {};
11187:         if (($actionurl eq '/adm/portfolio') || 
11188:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11189:             my ($sublistref,$listerror) =
11190:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11191:             if (ref($sublistref) eq 'ARRAY') {
11192:                 foreach my $line (@{$sublistref}) {
11193:                     my ($file_name,$rest) = split(/\&/,$line,2);
11194:                     $currsubfile{$path}{$file_name} = 1;
11195:                 }
11196:             }
11197:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11198:             if (opendir(my $dir,$url.'/'.$path)) {
11199:                 my @subdir_list = grep(!/^\./,readdir($dir));
11200:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11201:             }
11202:         } elsif (($actionurl eq '/adm/dependencies') ||
11203:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11204:                   ($args->{'context'} eq 'paste')) ||
11205:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11206:             if ($env{'request.course.id'} ne '') {
11207:                 my $dir;
11208:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11209:                     $dir = $fileloc;
11210:                 } else {
11211:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11212:                 }
11213:                 if ($dir ne '') {
11214:                     my ($sublistref,$listerror) =
11215:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11216:                     if (ref($sublistref) eq 'ARRAY') {
11217:                         foreach my $line (@{$sublistref}) {
11218:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11219:                                 undef,$mtime)=split(/\&/,$line,12);
11220:                             unless (($testdir&$dirptr) ||
11221:                                     ($file_name =~ /^\.\.?$/)) {
11222:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11223:                             }
11224:                         }
11225:                     }
11226:                 }
11227:             }
11228:         }
11229:         foreach my $file (keys(%{$subdependencies{$path}})) {
11230:             if (exists($currsubfile{$path}{$file})) {
11231:                 my $item = $path.'/'.$file;
11232:                 unless ($mapping{$item} eq $item) {
11233:                     $pathchanges{$item} = 1;
11234:                 }
11235:                 $existing{$item} = 1;
11236:                 $numexisting ++;
11237:             } else {
11238:                 $newfiles{$path.'/'.$file} = 1;
11239:             }
11240:         }
11241:         if ($actionurl eq '/adm/dependencies') {
11242:             foreach my $path (keys(%currsubfile)) {
11243:                 if (ref($currsubfile{$path}) eq 'HASH') {
11244:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11245:                          unless ($subdependencies{$path}{$file}) {
11246:                              next if (($rem ne '') &&
11247:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11248:                                        (ref($navmap) &&
11249:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11250:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11251:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11252:                              $unused{$path.'/'.$file} = 1; 
11253:                          }
11254:                     }
11255:                 }
11256:             }
11257:         }
11258:     }
11259:     
11260:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11261:     # for files in $url or $fileloc (target directory) in some contexts
11262:     my %currfile;
11263:     if (($actionurl eq '/adm/portfolio') ||
11264:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11265:         my ($dirlistref,$listerror) =
11266:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11267:         if (ref($dirlistref) eq 'ARRAY') {
11268:             foreach my $line (@{$dirlistref}) {
11269:                 my ($file_name,$rest) = split(/\&/,$line,2);
11270:                 $currfile{$file_name} = 1;
11271:             }
11272:         }
11273:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11274:         if (opendir(my $dir,$url)) {
11275:             my @dir_list = grep(!/^\./,readdir($dir));
11276:             map {$currfile{$_} = 1;} @dir_list;
11277:         }
11278:     } elsif (($actionurl eq '/adm/dependencies') ||
11279:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11280:               ($args->{'context'} eq 'paste')) ||
11281:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11282:         if ($env{'request.course.id'} ne '') {
11283:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11284:             if ($dir ne '') {
11285:                 my ($dirlistref,$listerror) =
11286:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11287:                 if (ref($dirlistref) eq 'ARRAY') {
11288:                     foreach my $line (@{$dirlistref}) {
11289:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11290:                             $size,undef,$mtime)=split(/\&/,$line,12);
11291:                         unless (($testdir&$dirptr) ||
11292:                                 ($file_name =~ /^\.\.?$/)) {
11293:                             $currfile{$file_name} = [$size,$mtime];
11294:                         }
11295:                     }
11296:                 }
11297:             }
11298:         }
11299:     }
11300:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11301:     # are not in subdirectories, using $currfile
11302:     foreach my $file (keys(%dependencies)) {
11303:         if (exists($currfile{$file})) {
11304:             unless ($mapping{$file} eq $file) {
11305:                 $pathchanges{$file} = 1;
11306:             }
11307:             $existing{$file} = 1;
11308:             $numexisting ++;
11309:         } else {
11310:             $newfiles{$file} = 1;
11311:         }
11312:     }
11313:     foreach my $file (keys(%currfile)) {
11314:         unless (($file eq $filename) ||
11315:                 ($file eq $filename.'.bak') ||
11316:                 ($dependencies{$file})) {
11317:             if ($actionurl eq '/adm/dependencies') {
11318:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11319:                     next if (($rem ne '') &&
11320:                              (($env{"httpref.$rem".$file} ne '') ||
11321:                               (ref($navmap) &&
11322:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11323:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11324:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11325:                 }
11326:             }
11327:             $unused{$file} = 1;
11328:         }
11329:     }
11330:     
11331:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11332:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11333:         ($args->{'context'} eq 'paste')) {
11334:         $counter = scalar(keys(%existing));
11335:         $numpathchg = scalar(keys(%pathchanges));
11336:         return ($output,$counter,$numpathchg,\%existing);
11337:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11338:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11339:         $counter = scalar(keys(%existing));
11340:         $numpathchg = scalar(keys(%pathchanges));
11341:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11342:     }
11343:     
11344:     # returns HTML otherwise, with dependency results and to ask for more uploads
11345:     
11346:     # $upload_output: missing dependencies (with upload form)
11347:     # $modify_output: uploaded dependencies (in use)
11348:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11349:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11350:         if ($actionurl eq '/adm/dependencies') {
11351:             next if ($embed_file =~ m{^\w+://});
11352:         }
11353:         $upload_output .= &start_data_table_row().
11354:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11355:                           '<span class="LC_filename">'.$embed_file.'</span>';
11356:         unless ($mapping{$embed_file} eq $embed_file) {
11357:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11358:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11359:         }
11360:         $upload_output .= '</td>';
11361:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11362:             $upload_output.='<td align="right">'.
11363:                             '<span class="LC_info LC_fontsize_medium">'.
11364:                             &mt("URL points to web address").'</span>';
11365:             $numremref++;
11366:         } elsif ($args->{'error_on_invalid_names'}
11367:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11368:             $upload_output.='<td align="right"><span class="LC_warning">'.
11369:                             &mt('Invalid characters').'</span>';
11370:             $numinvalid++;
11371:         } else {
11372:             $upload_output .= '<td>'.
11373:                               &embedded_file_element('upload_embedded',$counter,
11374:                                                      $embed_file,\%mapping,
11375:                                                      $allfiles,$codebase,'upload');
11376:             $counter ++;
11377:             $numnew ++;
11378:         }
11379:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11380:     }
11381:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11382:         if ($actionurl eq '/adm/dependencies') {
11383:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11384:             $modify_output .= &start_data_table_row().
11385:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11386:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11387:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11388:                               '<td>'.$size.'</td>'.
11389:                               '<td>'.$mtime.'</td>'.
11390:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11391:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11392:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11393:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11394:                               &embedded_file_element('upload_embedded',$counter,
11395:                                                      $embed_file,\%mapping,
11396:                                                      $allfiles,$codebase,'modify').
11397:                               '</div></td>'.
11398:                               &end_data_table_row()."\n";
11399:             $counter ++;
11400:         } else {
11401:             $upload_output .= &start_data_table_row().
11402:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11403:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11404:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11405:                               &Apache::loncommon::end_data_table_row()."\n";
11406:         }
11407:     }
11408:     my $delidx = $counter;
11409:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11410:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11411:         $delete_output .= &start_data_table_row().
11412:                           '<td><img src="'.&icon($oldfile).'" />'.
11413:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11414:                           '<td>'.$size.'</td>'.
11415:                           '<td>'.$mtime.'</td>'.
11416:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11417:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11418:                           &embedded_file_element('upload_embedded',$delidx,
11419:                                                  $oldfile,\%mapping,$allfiles,
11420:                                                  $codebase,'delete').'</td>'.
11421:                           &end_data_table_row()."\n"; 
11422:         $numunused ++;
11423:         $delidx ++;
11424:     }
11425:     if ($upload_output) {
11426:         $upload_output = &start_data_table().
11427:                          $upload_output.
11428:                          &end_data_table()."\n";
11429:     }
11430:     if ($modify_output) {
11431:         $modify_output = &start_data_table().
11432:                          &start_data_table_header_row().
11433:                          '<th>'.&mt('File').'</th>'.
11434:                          '<th>'.&mt('Size (KB)').'</th>'.
11435:                          '<th>'.&mt('Modified').'</th>'.
11436:                          '<th>'.&mt('Upload replacement?').'</th>'.
11437:                          &end_data_table_header_row().
11438:                          $modify_output.
11439:                          &end_data_table()."\n";
11440:     }
11441:     if ($delete_output) {
11442:         $delete_output = &start_data_table().
11443:                          &start_data_table_header_row().
11444:                          '<th>'.&mt('File').'</th>'.
11445:                          '<th>'.&mt('Size (KB)').'</th>'.
11446:                          '<th>'.&mt('Modified').'</th>'.
11447:                          '<th>'.&mt('Delete?').'</th>'.
11448:                          &end_data_table_header_row().
11449:                          $delete_output.
11450:                          &end_data_table()."\n";
11451:     }
11452:     my $applies = 0;
11453:     if ($numremref) {
11454:         $applies ++;
11455:     }
11456:     if ($numinvalid) {
11457:         $applies ++;
11458:     }
11459:     if ($numexisting) {
11460:         $applies ++;
11461:     }
11462:     if ($counter || $numunused) {
11463:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11464:                   ' method="post" enctype="multipart/form-data">'."\n".
11465:                   $state.'<h3>'.$heading.'</h3>'; 
11466:         if ($actionurl eq '/adm/dependencies') {
11467:             if ($numnew) {
11468:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11469:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11470:                            $upload_output.'<br />'."\n";
11471:             }
11472:             if ($numexisting) {
11473:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11474:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11475:                            $modify_output.'<br />'."\n";
11476:                            $buttontext = &mt('Save changes');
11477:             }
11478:             if ($numunused) {
11479:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11480:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11481:                            $delete_output.'<br />'."\n";
11482:                            $buttontext = &mt('Save changes');
11483:             }
11484:         } else {
11485:             $output .= $upload_output.'<br />'."\n";
11486:         }
11487:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11488:                    $counter.'" />'."\n";
11489:         if ($actionurl eq '/adm/dependencies') { 
11490:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11491:                        $numnew.'" />'."\n";
11492:         } elsif ($actionurl eq '') {
11493:             $output .=  '<input type="hidden" name="phase" value="three" />';
11494:         }
11495:     } elsif ($applies) {
11496:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11497:         if ($applies > 1) {
11498:             $output .=  
11499:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11500:             if ($numremref) {
11501:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11502:             }
11503:             if ($numinvalid) {
11504:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11505:             }
11506:             if ($numexisting) {
11507:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11508:             }
11509:             $output .= '</ul><br />';
11510:         } elsif ($numremref) {
11511:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11512:         } elsif ($numinvalid) {
11513:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11514:         } elsif ($numexisting) {
11515:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11516:         }
11517:         $output .= $upload_output.'<br />';
11518:     }
11519:     my ($pathchange_output,$chgcount);
11520:     $chgcount = $counter;
11521:     if (keys(%pathchanges) > 0) {
11522:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11523:             if ($counter) {
11524:                 $output .= &embedded_file_element('pathchange',$chgcount,
11525:                                                   $embed_file,\%mapping,
11526:                                                   $allfiles,$codebase,'change');
11527:             } else {
11528:                 $pathchange_output .= 
11529:                     &start_data_table_row().
11530:                     '<td><input type ="checkbox" name="namechange" value="'.
11531:                     $chgcount.'" checked="checked" /></td>'.
11532:                     '<td>'.$mapping{$embed_file}.'</td>'.
11533:                     '<td>'.$embed_file.
11534:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11535:                                            \%mapping,$allfiles,$codebase,'change').
11536:                     '</td>'.&end_data_table_row();
11537:             }
11538:             $numpathchg ++;
11539:             $chgcount ++;
11540:         }
11541:     }
11542:     if (($counter) || ($numunused)) {
11543:         if ($numpathchg) {
11544:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11545:                        $numpathchg.'" />'."\n";
11546:         }
11547:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11548:             ($actionurl eq '/adm/imsimport')) {
11549:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11550:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11551:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11552:         } elsif ($actionurl eq '/adm/dependencies') {
11553:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11554:         }
11555:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11556:     } elsif ($numpathchg) {
11557:         my %pathchange = ();
11558:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11559:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11560:             $output .= '<p>'.&mt('or').'</p>'; 
11561:         }
11562:     }
11563:     return ($output,$counter,$numpathchg);
11564: }
11565: 
11566: =pod
11567: 
11568: =item * clean_path($name)
11569: 
11570: Performs clean-up of directories, subdirectories and filename in an
11571: embedded object, referenced in an HTML file which is being uploaded
11572: to a course or portfolio, where 
11573: "Upload embedded images/multimedia files if HTML file" checkbox was
11574: checked.
11575: 
11576: Clean-up is similar to replacements in lonnet::clean_filename()
11577: except each / between sub-directory and next level is preserved.
11578: 
11579: =cut
11580: 
11581: sub clean_path {
11582:     my ($embed_file) = @_;
11583:     $embed_file =~s{^/+}{};
11584:     my @contents;
11585:     if ($embed_file =~ m{/}) {
11586:         @contents = split(/\//,$embed_file);
11587:     } else {
11588:         @contents = ($embed_file);
11589:     }
11590:     my $lastidx = scalar(@contents)-1;
11591:     for (my $i=0; $i<=$lastidx; $i++) { 
11592:         $contents[$i]=~s{\\}{/}g;
11593:         $contents[$i]=~s/\s+/\_/g;
11594:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11595:         if ($i == $lastidx) {
11596:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11597:         }
11598:     }
11599:     if ($lastidx > 0) {
11600:         return join('/',@contents);
11601:     } else {
11602:         return $contents[0];
11603:     }
11604: }
11605: 
11606: sub embedded_file_element {
11607:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11608:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11609:                    (ref($codebase) eq 'HASH'));
11610:     my $output;
11611:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11612:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11613:     }
11614:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11615:                &escape($embed_file).'" />';
11616:     unless (($context eq 'upload_embedded') && 
11617:             ($mapping->{$embed_file} eq $embed_file)) {
11618:         $output .='
11619:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11620:     }
11621:     my $attrib;
11622:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11623:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11624:     }
11625:     $output .=
11626:         "\n\t\t".
11627:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11628:         $attrib.'" />';
11629:     if (exists($codebase->{$mapping->{$embed_file}})) {
11630:         $output .=
11631:             "\n\t\t".
11632:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11633:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11634:     }
11635:     return $output;
11636: }
11637: 
11638: sub get_dependency_details {
11639:     my ($currfile,$currsubfile,$embed_file) = @_;
11640:     my ($size,$mtime,$showsize,$showmtime);
11641:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11642:         if ($embed_file =~ m{/}) {
11643:             my ($path,$fname) = split(/\//,$embed_file);
11644:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11645:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11646:             }
11647:         } else {
11648:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11649:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11650:             }
11651:         }
11652:         $showsize = $size/1024.0;
11653:         $showsize = sprintf("%.1f",$showsize);
11654:         if ($mtime > 0) {
11655:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11656:         }
11657:     }
11658:     return ($showsize,$showmtime);
11659: }
11660: 
11661: sub ask_embedded_js {
11662:     return <<"END";
11663: <script type="text/javascript"">
11664: // <![CDATA[
11665: function toggleBrowse(counter) {
11666:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11667:     var fileid = document.getElementById('embedded_item_'+counter);
11668:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11669:     if (chkboxid.checked == true) {
11670:         uploaddivid.style.display='block';
11671:     } else {
11672:         uploaddivid.style.display='none';
11673:         fileid.value = '';
11674:     }
11675: }
11676: // ]]>
11677: </script>
11678: 
11679: END
11680: }
11681: 
11682: sub upload_embedded {
11683:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11684:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11685:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11686:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11687:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11688:         my $orig_uploaded_filename =
11689:             $env{'form.embedded_item_'.$i.'.filename'};
11690:         foreach my $type ('orig','ref','attrib','codebase') {
11691:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11692:                 $env{'form.embedded_'.$type.'_'.$i} =
11693:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11694:             }
11695:         }
11696:         my ($path,$fname) =
11697:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11698:         # no path, whole string is fname
11699:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11700:         $fname = &Apache::lonnet::clean_filename($fname);
11701:         # See if there is anything left
11702:         next if ($fname eq '');
11703: 
11704:         # Check if file already exists as a file or directory.
11705:         my ($state,$msg);
11706:         if ($context eq 'portfolio') {
11707:             my $port_path = $dirpath;
11708:             if ($group ne '') {
11709:                 $port_path = "groups/$group/$port_path";
11710:             }
11711:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11712:                                               $fname,$group,'embedded_item_'.$i,
11713:                                               $dir_root,$port_path,$disk_quota,
11714:                                               $current_disk_usage,$uname,$udom);
11715:             if ($state eq 'will_exceed_quota'
11716:                 || $state eq 'file_locked') {
11717:                 $output .= $msg;
11718:                 next;
11719:             }
11720:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11721:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11722:             if ($state eq 'exists') {
11723:                 $output .= $msg;
11724:                 next;
11725:             }
11726:         }
11727:         # Check if extension is valid
11728:         if (($fname =~ /\.(\w+)$/) &&
11729:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11730:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11731:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11732:             next;
11733:         } elsif (($fname =~ /\.(\w+)$/) &&
11734:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11735:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11736:             next;
11737:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11738:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11739:             next;
11740:         }
11741:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11742:         my $subdir = $path;
11743:         $subdir =~ s{/+$}{};
11744:         if ($context eq 'portfolio') {
11745:             my $result;
11746:             if ($state eq 'existingfile') {
11747:                 $result=
11748:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11749:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11750:             } else {
11751:                 $result=
11752:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11753:                                                     $dirpath.
11754:                                                     $env{'form.currentpath'}.$subdir);
11755:                 if ($result !~ m|^/uploaded/|) {
11756:                     $output .= '<span class="LC_error">'
11757:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11758:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11759:                                .'</span><br />';
11760:                     next;
11761:                 } else {
11762:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11763:                                $path.$fname.'</span>').'<br />';     
11764:                 }
11765:             }
11766:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11767:             my $extendedsubdir = $dirpath.'/'.$subdir;
11768:             $extendedsubdir =~ s{/+$}{};
11769:             my $result =
11770:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11771:             if ($result !~ m|^/uploaded/|) {
11772:                 $output .= '<span class="LC_error">'
11773:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11774:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11775:                            .'</span><br />';
11776:                     next;
11777:             } else {
11778:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11779:                            $path.$fname.'</span>').'<br />';
11780:                 if ($context eq 'syllabus') {
11781:                     &Apache::lonnet::make_public_indefinitely($result);
11782:                 }
11783:             }
11784:         } else {
11785: # Save the file
11786:             my $target = $env{'form.embedded_item_'.$i};
11787:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11788:             my $dest = $fullpath.$fname;
11789:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11790:             my @parts=split(/\//,"$dirpath/$path");
11791:             my $count;
11792:             my $filepath = $dir_root;
11793:             foreach my $subdir (@parts) {
11794:                 $filepath .= "/$subdir";
11795:                 if (!-e $filepath) {
11796:                     mkdir($filepath,0770);
11797:                 }
11798:             }
11799:             my $fh;
11800:             if (!open($fh,'>'.$dest)) {
11801:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11802:                 $output .= '<span class="LC_error">'.
11803:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11804:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11805:                            '</span><br />';
11806:             } else {
11807:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11808:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11809:                     $output .= '<span class="LC_error">'.
11810:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11811:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11812:                               '</span><br />';
11813:                 } else {
11814:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11815:                                $url.'</span>').'<br />';
11816:                     unless ($context eq 'testbank') {
11817:                         $footer .= &mt('View embedded file: [_1]',
11818:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11819:                     }
11820:                 }
11821:                 close($fh);
11822:             }
11823:         }
11824:         if ($env{'form.embedded_ref_'.$i}) {
11825:             $pathchange{$i} = 1;
11826:         }
11827:     }
11828:     if ($output) {
11829:         $output = '<p>'.$output.'</p>';
11830:     }
11831:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11832:     $returnflag = 'ok';
11833:     my $numpathchgs = scalar(keys(%pathchange));
11834:     if ($numpathchgs > 0) {
11835:         if ($context eq 'portfolio') {
11836:             $output .= '<p>'.&mt('or').'</p>';
11837:         } elsif ($context eq 'testbank') {
11838:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11839:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11840:             $returnflag = 'modify_orightml';
11841:         }
11842:     }
11843:     return ($output.$footer,$returnflag,$numpathchgs);
11844: }
11845: 
11846: sub modify_html_form {
11847:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11848:     my $end = 0;
11849:     my $modifyform;
11850:     if ($context eq 'upload_embedded') {
11851:         return unless (ref($pathchange) eq 'HASH');
11852:         if ($env{'form.number_embedded_items'}) {
11853:             $end += $env{'form.number_embedded_items'};
11854:         }
11855:         if ($env{'form.number_pathchange_items'}) {
11856:             $end += $env{'form.number_pathchange_items'};
11857:         }
11858:         if ($end) {
11859:             for (my $i=0; $i<$end; $i++) {
11860:                 if ($i < $env{'form.number_embedded_items'}) {
11861:                     next unless($pathchange->{$i});
11862:                 }
11863:                 $modifyform .=
11864:                     &start_data_table_row().
11865:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11866:                     'checked="checked" /></td>'.
11867:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11868:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11869:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11870:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11871:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11872:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11873:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11874:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11875:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11876:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11877:                     &end_data_table_row();
11878:             }
11879:         }
11880:     } else {
11881:         $modifyform = $pathchgtable;
11882:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11883:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11884:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11885:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11886:         }
11887:     }
11888:     if ($modifyform) {
11889:         if ($actionurl eq '/adm/dependencies') {
11890:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11891:         }
11892:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11893:                '<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".
11894:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11895:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11896:                '</ol></p>'."\n".'<p>'.
11897:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11898:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11899:                &start_data_table()."\n".
11900:                &start_data_table_header_row().
11901:                '<th>'.&mt('Change?').'</th>'.
11902:                '<th>'.&mt('Current reference').'</th>'.
11903:                '<th>'.&mt('Required reference').'</th>'.
11904:                &end_data_table_header_row()."\n".
11905:                $modifyform.
11906:                &end_data_table().'<br />'."\n".$hiddenstate.
11907:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11908:                '</form>'."\n";
11909:     }
11910:     return;
11911: }
11912: 
11913: sub modify_html_refs {
11914:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11915:     my $container;
11916:     if ($context eq 'portfolio') {
11917:         $container = $env{'form.container'};
11918:     } elsif ($context eq 'coursedoc') {
11919:         $container = $env{'form.primaryurl'};
11920:     } elsif ($context eq 'manage_dependencies') {
11921:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11922:         $container = "/$container";
11923:     } elsif ($context eq 'syllabus') {
11924:         $container = $url;
11925:     } else {
11926:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11927:     }
11928:     my (%allfiles,%codebase,$output,$content);
11929:     my @changes = &get_env_multiple('form.namechange');
11930:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11931:         if (wantarray) {
11932:             return ('',0,0); 
11933:         } else {
11934:             return;
11935:         }
11936:     }
11937:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11938:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11939:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11940:             if (wantarray) {
11941:                 return ('',0,0);
11942:             } else {
11943:                 return;
11944:             }
11945:         } 
11946:         $content = &Apache::lonnet::getfile($container);
11947:         if ($content eq '-1') {
11948:             if (wantarray) {
11949:                 return ('',0,0);
11950:             } else {
11951:                 return;
11952:             }
11953:         }
11954:     } else {
11955:         unless ($container =~ /^\Q$dir_root\E/) {
11956:             if (wantarray) {
11957:                 return ('',0,0);
11958:             } else {
11959:                 return;
11960:             }
11961:         } 
11962:         if (open(my $fh,"<$container")) {
11963:             $content = join('', <$fh>);
11964:             close($fh);
11965:         } else {
11966:             if (wantarray) {
11967:                 return ('',0,0);
11968:             } else {
11969:                 return;
11970:             }
11971:         }
11972:     }
11973:     my ($count,$codebasecount) = (0,0);
11974:     my $mm = new File::MMagic;
11975:     my $mime_type = $mm->checktype_contents($content);
11976:     if ($mime_type eq 'text/html') {
11977:         my $parse_result = 
11978:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11979:                                                     \%codebase,\$content);
11980:         if ($parse_result eq 'ok') {
11981:             foreach my $i (@changes) {
11982:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11983:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11984:                 if ($allfiles{$ref}) {
11985:                     my $newname =  $orig;
11986:                     my ($attrib_regexp,$codebase);
11987:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11988:                     if ($attrib_regexp =~ /:/) {
11989:                         $attrib_regexp =~ s/\:/|/g;
11990:                     }
11991:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11992:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11993:                         $count += $numchg;
11994:                         $allfiles{$newname} = $allfiles{$ref};
11995:                         delete($allfiles{$ref});
11996:                     }
11997:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11998:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11999:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12000:                         $codebasecount ++;
12001:                     }
12002:                 }
12003:             }
12004:             my $skiprewrites;
12005:             if ($count || $codebasecount) {
12006:                 my $saveresult;
12007:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12008:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12009:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12010:                     if ($url eq $container) {
12011:                         my ($fname) = ($container =~ m{/([^/]+)$});
12012:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12013:                                             $count,'<span class="LC_filename">'.
12014:                                             $fname.'</span>').'</p>';
12015:                     } else {
12016:                          $output = '<p class="LC_error">'.
12017:                                    &mt('Error: update failed for: [_1].',
12018:                                    '<span class="LC_filename">'.
12019:                                    $container.'</span>').'</p>';
12020:                     }
12021:                     if ($context eq 'syllabus') {
12022:                         unless ($saveresult eq 'ok') {
12023:                             $skiprewrites = 1;
12024:                         }
12025:                     }
12026:                 } else {
12027:                     if (open(my $fh,">$container")) {
12028:                         print $fh $content;
12029:                         close($fh);
12030:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12031:                                   $count,'<span class="LC_filename">'.
12032:                                   $container.'</span>').'</p>';
12033:                     } else {
12034:                          $output = '<p class="LC_error">'.
12035:                                    &mt('Error: could not update [_1].',
12036:                                    '<span class="LC_filename">'.
12037:                                    $container.'</span>').'</p>';
12038:                     }
12039:                 }
12040:             }
12041:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12042:                 my ($actionurl,$state);
12043:                 $actionurl = "/public/$udom/$uname/syllabus";
12044:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12045:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12046:                                               \%codebase,
12047:                                               {'context' => 'rewrites',
12048:                                                'ignore_remote_references' => 1,});
12049:                 if (ref($mapping) eq 'HASH') {
12050:                     my $rewrites = 0;
12051:                     foreach my $key (keys(%{$mapping})) {
12052:                         next if ($key =~ m{^https?://});
12053:                         my $ref = $mapping->{$key};
12054:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12055:                         my $attrib;
12056:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12057:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12058:                         }
12059:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12060:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12061:                             $rewrites += $numchg;
12062:                         }
12063:                     }
12064:                     if ($rewrites) {
12065:                         my $saveresult; 
12066:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12067:                         if ($url eq $container) {
12068:                             my ($fname) = ($container =~ m{/([^/]+)$});
12069:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12070:                                             $count,'<span class="LC_filename">'.
12071:                                             $fname.'</span>').'</p>';
12072:                         } else {
12073:                             $output .= '<p class="LC_error">'.
12074:                                        &mt('Error: could not update links in [_1].',
12075:                                        '<span class="LC_filename">'.
12076:                                        $container.'</span>').'</p>';
12077: 
12078:                         }
12079:                     }
12080:                 }
12081:             }
12082:         } else {
12083:             &logthis('Failed to parse '.$container.
12084:                      ' to modify references: '.$parse_result);
12085:         }
12086:     }
12087:     if (wantarray) {
12088:         return ($output,$count,$codebasecount);
12089:     } else {
12090:         return $output;
12091:     }
12092: }
12093: 
12094: sub check_for_existing {
12095:     my ($path,$fname,$element) = @_;
12096:     my ($state,$msg);
12097:     if (-d $path.'/'.$fname) {
12098:         $state = 'exists';
12099:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12100:     } elsif (-e $path.'/'.$fname) {
12101:         $state = 'exists';
12102:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12103:     }
12104:     if ($state eq 'exists') {
12105:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12106:     }
12107:     return ($state,$msg);
12108: }
12109: 
12110: sub check_for_upload {
12111:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12112:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12113:     my $filesize = length($env{'form.'.$element});
12114:     if (!$filesize) {
12115:         my $msg = '<span class="LC_error">'.
12116:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12117:                       '<span class="LC_filename">'.$fname.'</span>',
12118:                       $filesize).'<br />'.
12119:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12120:                   '</span>';
12121:         return ('zero_bytes',$msg);
12122:     }
12123:     $filesize =  $filesize/1000; #express in k (1024?)
12124:     my $getpropath = 1;
12125:     my ($dirlistref,$listerror) =
12126:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12127:     my $found_file = 0;
12128:     my $locked_file = 0;
12129:     my @lockers;
12130:     my $navmap;
12131:     if ($env{'request.course.id'}) {
12132:         $navmap = Apache::lonnavmaps::navmap->new();
12133:     }
12134:     if (ref($dirlistref) eq 'ARRAY') {
12135:         foreach my $line (@{$dirlistref}) {
12136:             my ($file_name,$rest)=split(/\&/,$line,2);
12137:             if ($file_name eq $fname){
12138:                 $file_name = $path.$file_name;
12139:                 if ($group ne '') {
12140:                     $file_name = $group.$file_name;
12141:                 }
12142:                 $found_file = 1;
12143:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12144:                     foreach my $lock (@lockers) {
12145:                         if (ref($lock) eq 'ARRAY') {
12146:                             my ($symb,$crsid) = @{$lock};
12147:                             if ($crsid eq $env{'request.course.id'}) {
12148:                                 if (ref($navmap)) {
12149:                                     my $res = $navmap->getBySymb($symb);
12150:                                     foreach my $part (@{$res->parts()}) { 
12151:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12152:                                         unless (($slot_status == $res->RESERVED) ||
12153:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12154:                                             $locked_file = 1;
12155:                                         }
12156:                                     }
12157:                                 } else {
12158:                                     $locked_file = 1;
12159:                                 }
12160:                             } else {
12161:                                 $locked_file = 1;
12162:                             }
12163:                         }
12164:                    }
12165:                 } else {
12166:                     my @info = split(/\&/,$rest);
12167:                     my $currsize = $info[6]/1000;
12168:                     if ($currsize < $filesize) {
12169:                         my $extra = $filesize - $currsize;
12170:                         if (($current_disk_usage + $extra) > $disk_quota) {
12171:                             my $msg = '<p class="LC_warning">'.
12172:                                       &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.',
12173:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12174:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12175:                                                    $disk_quota,$current_disk_usage).'</p>';
12176:                             return ('will_exceed_quota',$msg);
12177:                         }
12178:                     }
12179:                 }
12180:             }
12181:         }
12182:     }
12183:     if (($current_disk_usage + $filesize) > $disk_quota){
12184:         my $msg = '<p class="LC_warning">'.
12185:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12186:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12187:         return ('will_exceed_quota',$msg);
12188:     } elsif ($found_file) {
12189:         if ($locked_file) {
12190:             my $msg = '<p class="LC_warning">';
12191:             $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>');
12192:             $msg .= '</p>';
12193:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12194:             return ('file_locked',$msg);
12195:         } else {
12196:             my $msg = '<p class="LC_error">';
12197:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12198:             $msg .= '</p>';
12199:             return ('existingfile',$msg);
12200:         }
12201:     }
12202: }
12203: 
12204: sub check_for_traversal {
12205:     my ($path,$url,$toplevel) = @_;
12206:     my @parts=split(/\//,$path);
12207:     my $cleanpath;
12208:     my $fullpath = $url;
12209:     for (my $i=0;$i<@parts;$i++) {
12210:         next if ($parts[$i] eq '.');
12211:         if ($parts[$i] eq '..') {
12212:             $fullpath =~ s{([^/]+/)$}{};
12213:         } else {
12214:             $fullpath .= $parts[$i].'/';
12215:         }
12216:     }
12217:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12218:         $cleanpath = $1;
12219:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12220:         my $curr_toprel = $1;
12221:         my @parts = split(/\//,$curr_toprel);
12222:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12223:         my @urlparts = split(/\//,$url_toprel);
12224:         my $doubledots;
12225:         my $startdiff = -1;
12226:         for (my $i=0; $i<@urlparts; $i++) {
12227:             if ($startdiff == -1) {
12228:                 unless ($urlparts[$i] eq $parts[$i]) {
12229:                     $startdiff = $i;
12230:                     $doubledots .= '../';
12231:                 }
12232:             } else {
12233:                 $doubledots .= '../';
12234:             }
12235:         }
12236:         if ($startdiff > -1) {
12237:             $cleanpath = $doubledots;
12238:             for (my $i=$startdiff; $i<@parts; $i++) {
12239:                 $cleanpath .= $parts[$i].'/';
12240:             }
12241:         }
12242:     }
12243:     $cleanpath =~ s{(/)$}{};
12244:     return $cleanpath;
12245: }
12246: 
12247: sub is_archive_file {
12248:     my ($mimetype) = @_;
12249:     if (($mimetype eq 'application/octet-stream') ||
12250:         ($mimetype eq 'application/x-stuffit') ||
12251:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12252:         return 1;
12253:     }
12254:     return;
12255: }
12256: 
12257: sub decompress_form {
12258:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12259:     my %lt = &Apache::lonlocal::texthash (
12260:         this => 'This file is an archive file.',
12261:         camt => 'This file is a Camtasia archive file.',
12262:         itsc => 'Its contents are as follows:',
12263:         youm => 'You may wish to extract its contents.',
12264:         extr => 'Extract contents',
12265:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12266:         proa => 'Process automatically?',
12267:         yes  => 'Yes',
12268:         no   => 'No',
12269:         fold => 'Title for folder containing movie',
12270:         movi => 'Title for page containing embedded movie', 
12271:     );
12272:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12273:     my ($is_camtasia,$topdir,%toplevel,@paths);
12274:     my $info = &list_archive_contents($fileloc,\@paths);
12275:     if (@paths) {
12276:         foreach my $path (@paths) {
12277:             $path =~ s{^/}{};
12278:             if ($path =~ m{^([^/]+)/$}) {
12279:                 $topdir = $1;
12280:             }
12281:             if ($path =~ m{^([^/]+)/}) {
12282:                 $toplevel{$1} = $path;
12283:             } else {
12284:                 $toplevel{$path} = $path;
12285:             }
12286:         }
12287:     }
12288:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12289:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12290:                         "$topdir/media/",
12291:                         "$topdir/media/$topdir.mp4",
12292:                         "$topdir/media/FirstFrame.png",
12293:                         "$topdir/media/player.swf",
12294:                         "$topdir/media/swfobject.js",
12295:                         "$topdir/media/expressInstall.swf");
12296:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12297:                          "$topdir/$topdir.mp4",
12298:                          "$topdir/$topdir\_config.xml",
12299:                          "$topdir/$topdir\_controller.swf",
12300:                          "$topdir/$topdir\_embed.css",
12301:                          "$topdir/$topdir\_First_Frame.png",
12302:                          "$topdir/$topdir\_player.html",
12303:                          "$topdir/$topdir\_Thumbnails.png",
12304:                          "$topdir/playerProductInstall.swf",
12305:                          "$topdir/scripts/",
12306:                          "$topdir/scripts/config_xml.js",
12307:                          "$topdir/scripts/handlebars.js",
12308:                          "$topdir/scripts/jquery-1.7.1.min.js",
12309:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12310:                          "$topdir/scripts/modernizr.js",
12311:                          "$topdir/scripts/player-min.js",
12312:                          "$topdir/scripts/swfobject.js",
12313:                          "$topdir/skins/",
12314:                          "$topdir/skins/configuration_express.xml",
12315:                          "$topdir/skins/express_show/",
12316:                          "$topdir/skins/express_show/player-min.css",
12317:                          "$topdir/skins/express_show/spritesheet.png");
12318:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12319:                          "$topdir/$topdir.mp4",
12320:                          "$topdir/$topdir\_config.xml",
12321:                          "$topdir/$topdir\_controller.swf",
12322:                          "$topdir/$topdir\_embed.css",
12323:                          "$topdir/$topdir\_First_Frame.png",
12324:                          "$topdir/$topdir\_player.html",
12325:                          "$topdir/$topdir\_Thumbnails.png",
12326:                          "$topdir/playerProductInstall.swf",
12327:                          "$topdir/scripts/",
12328:                          "$topdir/scripts/config_xml.js",
12329:                          "$topdir/scripts/techsmith-smart-player.min.js",
12330:                          "$topdir/skins/",
12331:                          "$topdir/skins/configuration_express.xml",
12332:                          "$topdir/skins/express_show/",
12333:                          "$topdir/skins/express_show/spritesheet.min.css",
12334:                          "$topdir/skins/express_show/spritesheet.png",
12335:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12336:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12337:         if (@diffs == 0) {
12338:             $is_camtasia = 6;
12339:         } else {
12340:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12341:             if (@diffs == 0) {
12342:                 $is_camtasia = 8;
12343:             } else {
12344:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12345:                 if (@diffs == 0) {
12346:                     $is_camtasia = 8;
12347:                 }
12348:             }
12349:         }
12350:     }
12351:     my $output;
12352:     if ($is_camtasia) {
12353:         $output = <<"ENDCAM";
12354: <script type="text/javascript" language="Javascript">
12355: // <![CDATA[
12356: 
12357: function camtasiaToggle() {
12358:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12359:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12360:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12361:                 document.getElementById('camtasia_titles').style.display='block';
12362:             } else {
12363:                 document.getElementById('camtasia_titles').style.display='none';
12364:             }
12365:         }
12366:     }
12367:     return;
12368: }
12369: 
12370: // ]]>
12371: </script>
12372: <p>$lt{'camt'}</p>
12373: ENDCAM
12374:     } else {
12375:         $output = '<p>'.$lt{'this'};
12376:         if ($info eq '') {
12377:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12378:         } else {
12379:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12380:                        '<div><pre>'.$info.'</pre></div>';
12381:         }
12382:     }
12383:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12384:     my $duplicates;
12385:     my $num = 0;
12386:     if (ref($dirlist) eq 'ARRAY') {
12387:         foreach my $item (@{$dirlist}) {
12388:             if (ref($item) eq 'ARRAY') {
12389:                 if (exists($toplevel{$item->[0]})) {
12390:                     $duplicates .= 
12391:                         &start_data_table_row().
12392:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12393:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12394:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12395:                         'value="1" />'.&mt('Yes').'</label>'.
12396:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12397:                         '<td>'.$item->[0].'</td>';
12398:                     if ($item->[2]) {
12399:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12400:                     } else {
12401:                         $duplicates .= '<td>'.&mt('File').'</td>';
12402:                     }
12403:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12404:                                    '<td>'.
12405:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12406:                                    '</td>'.
12407:                                    &end_data_table_row();
12408:                     $num ++;
12409:                 }
12410:             }
12411:         }
12412:     }
12413:     my $itemcount;
12414:     if (@paths > 0) {
12415:         $itemcount = scalar(@paths);
12416:     } else {
12417:         $itemcount = 1;
12418:     }
12419:     if ($is_camtasia) {
12420:         $output .= $lt{'auto'}.'<br />'.
12421:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12422:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12423:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12424:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12425:                    $lt{'no'}.'</label></span><br />'.
12426:                    '<div id="camtasia_titles" style="display:block">'.
12427:                    &Apache::lonhtmlcommon::start_pick_box().
12428:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12429:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12430:                    &Apache::lonhtmlcommon::row_closure().
12431:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12432:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12433:                    &Apache::lonhtmlcommon::row_closure(1).
12434:                    &Apache::lonhtmlcommon::end_pick_box().
12435:                    '</div>';
12436:     }
12437:     $output .= 
12438:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12439:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12440:         "\n";
12441:     if ($duplicates ne '') {
12442:         $output .= '<p><span class="LC_warning">'.
12443:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12444:                    &start_data_table().
12445:                    &start_data_table_header_row().
12446:                    '<th>'.&mt('Overwrite?').'</th>'.
12447:                    '<th>'.&mt('Name').'</th>'.
12448:                    '<th>'.&mt('Type').'</th>'.
12449:                    '<th>'.&mt('Size').'</th>'.
12450:                    '<th>'.&mt('Last modified').'</th>'.
12451:                    &end_data_table_header_row().
12452:                    $duplicates.
12453:                    &end_data_table().
12454:                    '</p>';
12455:     }
12456:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12457:     if (ref($hiddenelements) eq 'HASH') {
12458:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12459:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12460:         }
12461:     }
12462:     $output .= <<"END";
12463: <br />
12464: <input type="submit" name="decompress" value="$lt{'extr'}" />
12465: </form>
12466: $noextract
12467: END
12468:     return $output;
12469: }
12470: 
12471: sub decompression_utility {
12472:     my ($program) = @_;
12473:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12474:     my $location;
12475:     if (grep(/^\Q$program\E$/,@utilities)) { 
12476:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12477:                          '/usr/sbin/') {
12478:             if (-x $dir.$program) {
12479:                 $location = $dir.$program;
12480:                 last;
12481:             }
12482:         }
12483:     }
12484:     return $location;
12485: }
12486: 
12487: sub list_archive_contents {
12488:     my ($file,$pathsref) = @_;
12489:     my (@cmd,$output);
12490:     my $needsregexp;
12491:     if ($file =~ /\.zip$/) {
12492:         @cmd = (&decompression_utility('unzip'),"-l");
12493:         $needsregexp = 1;
12494:     } elsif (($file =~ m/\.tar\.gz$/) ||
12495:              ($file =~ /\.tgz$/)) {
12496:         @cmd = (&decompression_utility('tar'),"-ztf");
12497:     } elsif ($file =~ /\.tar\.bz2$/) {
12498:         @cmd = (&decompression_utility('tar'),"-jtf");
12499:     } elsif ($file =~ m|\.tar$|) {
12500:         @cmd = (&decompression_utility('tar'),"-tf");
12501:     }
12502:     if (@cmd) {
12503:         undef($!);
12504:         undef($@);
12505:         if (open(my $fh,"-|", @cmd, $file)) {
12506:             while (my $line = <$fh>) {
12507:                 $output .= $line;
12508:                 chomp($line);
12509:                 my $item;
12510:                 if ($needsregexp) {
12511:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12512:                 } else {
12513:                     $item = $line;
12514:                 }
12515:                 if ($item ne '') {
12516:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12517:                         push(@{$pathsref},$item);
12518:                     } 
12519:                 }
12520:             }
12521:             close($fh);
12522:         }
12523:     }
12524:     return $output;
12525: }
12526: 
12527: sub decompress_uploaded_file {
12528:     my ($file,$dir) = @_;
12529:     &Apache::lonnet::appenv({'cgi.file' => $file});
12530:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12531:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12532:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12533:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12534:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12535:     my $decompressed = $env{'cgi.decompressed'};
12536:     &Apache::lonnet::delenv('cgi.file');
12537:     &Apache::lonnet::delenv('cgi.dir');
12538:     &Apache::lonnet::delenv('cgi.decompressed');
12539:     return ($decompressed,$result);
12540: }
12541: 
12542: sub process_decompression {
12543:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12544:     my ($dir,$error,$warning,$output);
12545:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12546:         $error = &mt('Filename not a supported archive file type.').
12547:                  '<br />'.&mt('Filename should end with one of: [_1].',
12548:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12549:     } else {
12550:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12551:         if ($docuhome eq 'no_host') {
12552:             $error = &mt('Could not determine home server for course.');
12553:         } else {
12554:             my @ids=&Apache::lonnet::current_machine_ids();
12555:             my $currdir = "$dir_root/$destination";
12556:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12557:                 $dir = &LONCAPA::propath($docudom,$docuname).
12558:                        "$dir_root/$destination";
12559:             } else {
12560:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12561:                        "$dir_root/$docudom/$docuname/$destination";
12562:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12563:                     $error = &mt('Archive file not found.');
12564:                 }
12565:             }
12566:             my (@to_overwrite,@to_skip);
12567:             if ($env{'form.archive_overwrite_total'} > 0) {
12568:                 my $total = $env{'form.archive_overwrite_total'};
12569:                 for (my $i=0; $i<$total; $i++) {
12570:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12571:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12572:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12573:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12574:                     }
12575:                 }
12576:             }
12577:             my $numskip = scalar(@to_skip);
12578:             if (($numskip > 0) && 
12579:                 ($numskip == $env{'form.archive_itemcount'})) {
12580:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12581:             } elsif ($dir eq '') {
12582:                 $error = &mt('Directory containing archive file unavailable.');
12583:             } elsif (!$error) {
12584:                 my ($decompressed,$display);
12585:                 if ($numskip > 0) {
12586:                     my $tempdir = time.'_'.$$.int(rand(10000));
12587:                     mkdir("$dir/$tempdir",0755);
12588:                     system("mv $dir/$file $dir/$tempdir/$file");
12589:                     ($decompressed,$display) = 
12590:                         &decompress_uploaded_file($file,"$dir/$tempdir");
12591:                     foreach my $item (@to_skip) {
12592:                         if (($item ne '') && ($item !~ /\.\./)) {
12593:                             if (-f "$dir/$tempdir/$item") { 
12594:                                 unlink("$dir/$tempdir/$item");
12595:                             } elsif (-d "$dir/$tempdir/$item") {
12596:                                 system("rm -rf $dir/$tempdir/$item");
12597:                             }
12598:                         }
12599:                     }
12600:                     system("mv $dir/$tempdir/* $dir");
12601:                     rmdir("$dir/$tempdir");   
12602:                 } else {
12603:                     ($decompressed,$display) = 
12604:                         &decompress_uploaded_file($file,$dir);
12605:                 }
12606:                 if ($decompressed eq 'ok') {
12607:                     $output = '<p class="LC_info">'.
12608:                               &mt('Files extracted successfully from archive.').
12609:                               '</p>'."\n";
12610:                     my ($warning,$result,@contents);
12611:                     my ($newdirlistref,$newlisterror) =
12612:                         &Apache::lonnet::dirlist($currdir,$docudom,
12613:                                                  $docuname,1);
12614:                     my (%is_dir,%changes,@newitems);
12615:                     my $dirptr = 16384;
12616:                     if (ref($newdirlistref) eq 'ARRAY') {
12617:                         foreach my $dir_line (@{$newdirlistref}) {
12618:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12619:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12620:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12621:                                 push(@newitems,$item);
12622:                                 if ($dirptr&$testdir) {
12623:                                     $is_dir{$item} = 1;
12624:                                 }
12625:                                 $changes{$item} = 1;
12626:                             }
12627:                         }
12628:                     }
12629:                     if (keys(%changes) > 0) {
12630:                         foreach my $item (sort(@newitems)) {
12631:                             if ($changes{$item}) {
12632:                                 push(@contents,$item);
12633:                             }
12634:                         }
12635:                     }
12636:                     if (@contents > 0) {
12637:                         my $wantform;
12638:                         unless ($env{'form.autoextract_camtasia'}) {
12639:                             $wantform = 1;
12640:                         }
12641:                         my (%children,%parent,%dirorder,%titles);
12642:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12643:                                                                 $currdir,\%is_dir,
12644:                                                                 \%children,\%parent,
12645:                                                                 \@contents,\%dirorder,
12646:                                                                 \%titles,$wantform);
12647:                         if ($datatable ne '') {
12648:                             $output .= &archive_options_form('decompressed',$datatable,
12649:                                                              $count,$hiddenelem);
12650:                             my $startcount = 6;
12651:                             $output .= &archive_javascript($startcount,$count,
12652:                                                            \%titles,\%children);
12653:                         }
12654:                         if ($env{'form.autoextract_camtasia'}) {
12655:                             my $version = $env{'form.autoextract_camtasia'};
12656:                             my %displayed;
12657:                             my $total = 1;
12658:                             $env{'form.archive_directory'} = [];
12659:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12660:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12661:                                 $path =~ s{/$}{};
12662:                                 my $item;
12663:                                 if ($path ne '') {
12664:                                     $item = "$path/$titles{$i}";
12665:                                 } else {
12666:                                     $item = $titles{$i};
12667:                                 }
12668:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12669:                                 if ($item eq $contents[0]) {
12670:                                     push(@{$env{'form.archive_directory'}},$i);
12671:                                     $env{'form.archive_'.$i} = 'display';
12672:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12673:                                     $displayed{'folder'} = $i;
12674:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12675:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
12676:                                     $env{'form.archive_'.$i} = 'display';
12677:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12678:                                     $displayed{'web'} = $i;
12679:                                 } else {
12680:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12681:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12682:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12683:                                         push(@{$env{'form.archive_directory'}},$i);
12684:                                     }
12685:                                     $env{'form.archive_'.$i} = 'dependency';
12686:                                 }
12687:                                 $total ++;
12688:                             }
12689:                             for (my $i=1; $i<$total; $i++) {
12690:                                 next if ($i == $displayed{'web'});
12691:                                 next if ($i == $displayed{'folder'});
12692:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12693:                             }
12694:                             $env{'form.phase'} = 'decompress_cleanup';
12695:                             $env{'form.archivedelete'} = 1;
12696:                             $env{'form.archive_count'} = $total-1;
12697:                             $output .=
12698:                                 &process_extracted_files('coursedocs',$docudom,
12699:                                                          $docuname,$destination,
12700:                                                          $dir_root,$hiddenelem);
12701:                         }
12702:                     } else {
12703:                         $warning = &mt('No new items extracted from archive file.');
12704:                     }
12705:                 } else {
12706:                     $output = $display;
12707:                     $error = &mt('An error occurred during extraction from the archive file.');
12708:                 }
12709:             }
12710:         }
12711:     }
12712:     if ($error) {
12713:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12714:                    $error.'</p>'."\n";
12715:     }
12716:     if ($warning) {
12717:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12718:     }
12719:     return $output;
12720: }
12721: 
12722: sub get_extracted {
12723:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12724:         $titles,$wantform) = @_;
12725:     my $count = 0;
12726:     my $depth = 0;
12727:     my $datatable;
12728:     my @hierarchy;
12729:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12730:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12731:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12732:     foreach my $item (@{$contents}) {
12733:         $count ++;
12734:         @{$dirorder->{$count}} = @hierarchy;
12735:         $titles->{$count} = $item;
12736:         &archive_hierarchy($depth,$count,$parent,$children);
12737:         if ($wantform) {
12738:             $datatable .= &archive_row($is_dir->{$item},$item,
12739:                                        $currdir,$depth,$count);
12740:         }
12741:         if ($is_dir->{$item}) {
12742:             $depth ++;
12743:             push(@hierarchy,$count);
12744:             $parent->{$depth} = $count;
12745:             $datatable .=
12746:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12747:                                            \$depth,\$count,\@hierarchy,$dirorder,
12748:                                            $children,$parent,$titles,$wantform);
12749:             $depth --;
12750:             pop(@hierarchy);
12751:         }
12752:     }
12753:     return ($count,$datatable);
12754: }
12755: 
12756: sub recurse_extracted_archive {
12757:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12758:         $children,$parent,$titles,$wantform) = @_;
12759:     my $result='';
12760:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12761:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12762:             (ref($dirorder) eq 'HASH')) {
12763:         return $result;
12764:     }
12765:     my $dirptr = 16384;
12766:     my ($newdirlistref,$newlisterror) =
12767:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12768:     if (ref($newdirlistref) eq 'ARRAY') {
12769:         foreach my $dir_line (@{$newdirlistref}) {
12770:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12771:             unless ($item =~ /^\.+$/) {
12772:                 $$count ++;
12773:                 @{$dirorder->{$$count}} = @{$hierarchy};
12774:                 $titles->{$$count} = $item;
12775:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12776: 
12777:                 my $is_dir;
12778:                 if ($dirptr&$testdir) {
12779:                     $is_dir = 1;
12780:                 }
12781:                 if ($wantform) {
12782:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12783:                 }
12784:                 if ($is_dir) {
12785:                     $$depth ++;
12786:                     push(@{$hierarchy},$$count);
12787:                     $parent->{$$depth} = $$count;
12788:                     $result .=
12789:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12790:                                                    $docuname,$depth,$count,
12791:                                                    $hierarchy,$dirorder,$children,
12792:                                                    $parent,$titles,$wantform);
12793:                     $$depth --;
12794:                     pop(@{$hierarchy});
12795:                 }
12796:             }
12797:         }
12798:     }
12799:     return $result;
12800: }
12801: 
12802: sub archive_hierarchy {
12803:     my ($depth,$count,$parent,$children) =@_;
12804:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12805:         if (exists($parent->{$depth})) {
12806:              $children->{$parent->{$depth}} .= $count.':';
12807:         }
12808:     }
12809:     return;
12810: }
12811: 
12812: sub archive_row {
12813:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12814:     my ($name) = ($item =~ m{([^/]+)$});
12815:     my %choices = &Apache::lonlocal::texthash (
12816:                                        'display'    => 'Add as file',
12817:                                        'dependency' => 'Include as dependency',
12818:                                        'discard'    => 'Discard',
12819:                                       );
12820:     if ($is_dir) {
12821:         $choices{'display'} = &mt('Add as folder'); 
12822:     }
12823:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12824:     my $offset = 0;
12825:     foreach my $action ('display','dependency','discard') {
12826:         $offset ++;
12827:         if ($action ne 'display') {
12828:             $offset ++;
12829:         }  
12830:         $output .= '<td><span class="LC_nobreak">'.
12831:                    '<label><input type="radio" name="archive_'.$count.
12832:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12833:         my $text = $choices{$action};
12834:         if ($is_dir) {
12835:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12836:             if ($action eq 'display') {
12837:                 $text = &mt('Add as folder');
12838:             }
12839:         } else {
12840:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12841: 
12842:         }
12843:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12844:         if ($action eq 'dependency') {
12845:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12846:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12847:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12848:                        '<option value=""></option>'."\n".
12849:                        '</select>'."\n".
12850:                        '</div>';
12851:         } elsif ($action eq 'display') {
12852:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12853:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12854:                        '</div>';
12855:         }
12856:         $output .= '</td>';
12857:     }
12858:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12859:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12860:     for (my $i=0; $i<$depth; $i++) {
12861:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12862:     }
12863:     if ($is_dir) {
12864:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12865:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12866:     } else {
12867:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12868:     }
12869:     $output .= '&nbsp;'.$name.'</td>'."\n".
12870:                &end_data_table_row();
12871:     return $output;
12872: }
12873: 
12874: sub archive_options_form {
12875:     my ($form,$display,$count,$hiddenelem) = @_;
12876:     my %lt = &Apache::lonlocal::texthash(
12877:                perm => 'Permanently remove archive file?',
12878:                hows => 'How should each extracted item be incorporated in the course?',
12879:                cont => 'Content actions for all',
12880:                addf => 'Add as folder/file',
12881:                incd => 'Include as dependency for a displayed file',
12882:                disc => 'Discard',
12883:                no   => 'No',
12884:                yes  => 'Yes',
12885:                save => 'Save',
12886:     );
12887:     my $output = <<"END";
12888: <form name="$form" method="post" action="">
12889: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12890: <label>
12891:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12892: </label>
12893: &nbsp;
12894: <label>
12895:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12896: </span>
12897: </p>
12898: <input type="hidden" name="phase" value="decompress_cleanup" />
12899: <br />$lt{'hows'}
12900: <div class="LC_columnSection">
12901:   <fieldset>
12902:     <legend>$lt{'cont'}</legend>
12903:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12904:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12905:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12906:   </fieldset>
12907: </div>
12908: END
12909:     return $output.
12910:            &start_data_table()."\n".
12911:            $display."\n".
12912:            &end_data_table()."\n".
12913:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12914:            $hiddenelem.
12915:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12916:            '</form>';
12917: }
12918: 
12919: sub archive_javascript {
12920:     my ($startcount,$numitems,$titles,$children) = @_;
12921:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12922:     my $maintitle = $env{'form.comment'};
12923:     my $scripttag = <<START;
12924: <script type="text/javascript">
12925: // <![CDATA[
12926: 
12927: function checkAll(form,prefix) {
12928:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12929:     for (var i=0; i < form.elements.length; i++) {
12930:         var id = form.elements[i].id;
12931:         if ((id != '') && (id != undefined)) {
12932:             if (idstr.test(id)) {
12933:                 if (form.elements[i].type == 'radio') {
12934:                     form.elements[i].checked = true;
12935:                     var nostart = i-$startcount;
12936:                     var offset = nostart%7;
12937:                     var count = (nostart-offset)/7;    
12938:                     dependencyCheck(form,count,offset);
12939:                 }
12940:             }
12941:         }
12942:     }
12943: }
12944: 
12945: function propagateCheck(form,count) {
12946:     if (count > 0) {
12947:         var startelement = $startcount + ((count-1) * 7);
12948:         for (var j=1; j<6; j++) {
12949:             if ((j != 2) && (j != 4)) {
12950:                 var item = startelement + j; 
12951:                 if (form.elements[item].type == 'radio') {
12952:                     if (form.elements[item].checked) {
12953:                         containerCheck(form,count,j);
12954:                         break;
12955:                     }
12956:                 }
12957:             }
12958:         }
12959:     }
12960: }
12961: 
12962: numitems = $numitems
12963: var titles = new Array(numitems);
12964: var parents = new Array(numitems);
12965: for (var i=0; i<numitems; i++) {
12966:     parents[i] = new Array;
12967: }
12968: var maintitle = '$maintitle';
12969: 
12970: START
12971: 
12972:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12973:         my @contents = split(/:/,$children->{$container});
12974:         for (my $i=0; $i<@contents; $i ++) {
12975:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12976:         }
12977:     }
12978: 
12979:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12980:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12981:     }
12982: 
12983:     $scripttag .= <<END;
12984: 
12985: function containerCheck(form,count,offset) {
12986:     if (count > 0) {
12987:         dependencyCheck(form,count,offset);
12988:         var item = (offset+$startcount)+7*(count-1);
12989:         form.elements[item].checked = true;
12990:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12991:             if (parents[count].length > 0) {
12992:                 for (var j=0; j<parents[count].length; j++) {
12993:                     containerCheck(form,parents[count][j],offset);
12994:                 }
12995:             }
12996:         }
12997:     }
12998: }
12999: 
13000: function dependencyCheck(form,count,offset) {
13001:     if (count > 0) {
13002:         var chosen = (offset+$startcount)+7*(count-1);
13003:         var depitem = $startcount + ((count-1) * 7) + 4;
13004:         var currtype = form.elements[depitem].type;
13005:         if (form.elements[chosen].value == 'dependency') {
13006:             document.getElementById('arc_depon_'+count).style.display='block'; 
13007:             form.elements[depitem].options.length = 0;
13008:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13009:             for (var i=1; i<=numitems; i++) {
13010:                 if (i == count) {
13011:                     continue;
13012:                 }
13013:                 var startelement = $startcount + (i-1) * 7;
13014:                 for (var j=1; j<6; j++) {
13015:                     if ((j != 2) && (j!= 4)) {
13016:                         var item = startelement + j;
13017:                         if (form.elements[item].type == 'radio') {
13018:                             if (form.elements[item].checked) {
13019:                                 if (form.elements[item].value == 'display') {
13020:                                     var n = form.elements[depitem].options.length;
13021:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13022:                                 }
13023:                             }
13024:                         }
13025:                     }
13026:                 }
13027:             }
13028:         } else {
13029:             document.getElementById('arc_depon_'+count).style.display='none';
13030:             form.elements[depitem].options.length = 0;
13031:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13032:         }
13033:         titleCheck(form,count,offset);
13034:     }
13035: }
13036: 
13037: function propagateSelect(form,count,offset) {
13038:     if (count > 0) {
13039:         var item = (1+offset+$startcount)+7*(count-1);
13040:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13041:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13042:             if (parents[count].length > 0) {
13043:                 for (var j=0; j<parents[count].length; j++) {
13044:                     containerSelect(form,parents[count][j],offset,picked);
13045:                 }
13046:             }
13047:         }
13048:     }
13049: }
13050: 
13051: function containerSelect(form,count,offset,picked) {
13052:     if (count > 0) {
13053:         var item = (offset+$startcount)+7*(count-1);
13054:         if (form.elements[item].type == 'radio') {
13055:             if (form.elements[item].value == 'dependency') {
13056:                 if (form.elements[item+1].type == 'select-one') {
13057:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13058:                         if (form.elements[item+1].options[i].value == picked) {
13059:                             form.elements[item+1].selectedIndex = i;
13060:                             break;
13061:                         }
13062:                     }
13063:                 }
13064:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13065:                     if (parents[count].length > 0) {
13066:                         for (var j=0; j<parents[count].length; j++) {
13067:                             containerSelect(form,parents[count][j],offset,picked);
13068:                         }
13069:                     }
13070:                 }
13071:             }
13072:         }
13073:     }
13074: }
13075: 
13076: function titleCheck(form,count,offset) {
13077:     if (count > 0) {
13078:         var chosen = (offset+$startcount)+7*(count-1);
13079:         var depitem = $startcount + ((count-1) * 7) + 2;
13080:         var currtype = form.elements[depitem].type;
13081:         if (form.elements[chosen].value == 'display') {
13082:             document.getElementById('arc_title_'+count).style.display='block';
13083:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13084:                 document.getElementById('archive_title_'+count).value=maintitle;
13085:             }
13086:         } else {
13087:             document.getElementById('arc_title_'+count).style.display='none';
13088:             if (currtype == 'text') { 
13089:                 document.getElementById('archive_title_'+count).value='';
13090:             }
13091:         }
13092:     }
13093:     return;
13094: }
13095: 
13096: // ]]>
13097: </script>
13098: END
13099:     return $scripttag;
13100: }
13101: 
13102: sub process_extracted_files {
13103:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13104:     my $numitems = $env{'form.archive_count'};
13105:     return unless ($numitems);
13106:     my @ids=&Apache::lonnet::current_machine_ids();
13107:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13108:         %folders,%containers,%mapinner,%prompttofetch);
13109:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13110:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13111:         $prefix = &LONCAPA::propath($docudom,$docuname);
13112:         $pathtocheck = "$dir_root/$destination";
13113:         $dir = $dir_root;
13114:         $ishome = 1;
13115:     } else {
13116:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13117:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13118:         $dir = "$dir_root/$docudom/$docuname";    
13119:     }
13120:     my $currdir = "$dir_root/$destination";
13121:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13122:     if ($env{'form.folderpath'}) {
13123:         my @items = split('&',$env{'form.folderpath'});
13124:         $folders{'0'} = $items[-2];
13125:         if ($env{'form.folderpath'} =~ /\:1$/) {
13126:             $containers{'0'}='page';
13127:         } else {  
13128:             $containers{'0'}='sequence';
13129:         }
13130:     }
13131:     my @archdirs = &get_env_multiple('form.archive_directory');
13132:     if ($numitems) {
13133:         for (my $i=1; $i<=$numitems; $i++) {
13134:             my $path = $env{'form.archive_content_'.$i};
13135:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13136:                 my $item = $1;
13137:                 $toplevelitems{$item} = $i;
13138:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13139:                     $is_dir{$item} = 1;
13140:                 }
13141:             }
13142:         }
13143:     }
13144:     my ($output,%children,%parent,%titles,%dirorder,$result);
13145:     if (keys(%toplevelitems) > 0) {
13146:         my @contents = sort(keys(%toplevelitems));
13147:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13148:                                            \%parent,\@contents,\%dirorder,\%titles);
13149:     }
13150:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13151:     if ($numitems) {
13152:         for (my $i=1; $i<=$numitems; $i++) {
13153:             next if ($env{'form.archive_'.$i} eq 'dependency');
13154:             my $path = $env{'form.archive_content_'.$i};
13155:             if ($path =~ /^\Q$pathtocheck\E/) {
13156:                 if ($env{'form.archive_'.$i} eq 'discard') {
13157:                     if ($prefix ne '' && $path ne '') {
13158:                         if (-e $prefix.$path) {
13159:                             if ((@archdirs > 0) && 
13160:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13161:                                 $todeletedir{$prefix.$path} = 1;
13162:                             } else {
13163:                                 $todelete{$prefix.$path} = 1;
13164:                             }
13165:                         }
13166:                     }
13167:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13168:                     my ($docstitle,$title,$url,$outer);
13169:                     ($title) = ($path =~ m{/([^/]+)$});
13170:                     $docstitle = $env{'form.archive_title_'.$i};
13171:                     if ($docstitle eq '') {
13172:                         $docstitle = $title;
13173:                     }
13174:                     $outer = 0;
13175:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13176:                         if (@{$dirorder{$i}} > 0) {
13177:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13178:                                 if ($env{'form.archive_'.$item} eq 'display') {
13179:                                     $outer = $item;
13180:                                     last;
13181:                                 }
13182:                             }
13183:                         }
13184:                     }
13185:                     my ($errtext,$fatal) = 
13186:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13187:                                                '/'.$folders{$outer}.'.'.
13188:                                                $containers{$outer});
13189:                     next if ($fatal);
13190:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13191:                         if ($context eq 'coursedocs') {
13192:                             $mapinner{$i} = time;
13193:                             $folders{$i} = 'default_'.$mapinner{$i};
13194:                             $containers{$i} = 'sequence';
13195:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13196:                                       $folders{$i}.'.'.$containers{$i};
13197:                             my $newidx = &LONCAPA::map::getresidx();
13198:                             $LONCAPA::map::resources[$newidx]=
13199:                                 $docstitle.':'.$url.':false:normal:res';
13200:                             push(@LONCAPA::map::order,$newidx);
13201:                             my ($outtext,$errtext) =
13202:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13203:                                                         $docuname.'/'.$folders{$outer}.
13204:                                                         '.'.$containers{$outer},1,1);
13205:                             $newseqid{$i} = $newidx;
13206:                             unless ($errtext) {
13207:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
13208:                             }
13209:                         }
13210:                     } else {
13211:                         if ($context eq 'coursedocs') {
13212:                             my $newidx=&LONCAPA::map::getresidx();
13213:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13214:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13215:                                       $title;
13216:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13217:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13218:                             }
13219:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13220:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13221:                             }
13222:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13223:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
13224:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13225:                                 unless ($ishome) {
13226:                                     my $fetch = "$newdest{$i}/$title";
13227:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13228:                                     $prompttofetch{$fetch} = 1;
13229:                                 }
13230:                             }
13231:                             $LONCAPA::map::resources[$newidx]=
13232:                                 $docstitle.':'.$url.':false:normal:res';
13233:                             push(@LONCAPA::map::order, $newidx);
13234:                             my ($outtext,$errtext)=
13235:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13236:                                                         $docuname.'/'.$folders{$outer}.
13237:                                                         '.'.$containers{$outer},1,1);
13238:                             unless ($errtext) {
13239:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13240:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
13241:                                 }
13242:                             }
13243:                         }
13244:                     }
13245:                 }
13246:             } else {
13247:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
13248:             }
13249:         }
13250:         for (my $i=1; $i<=$numitems; $i++) {
13251:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13252:             my $path = $env{'form.archive_content_'.$i};
13253:             if ($path =~ /^\Q$pathtocheck\E/) {
13254:                 my ($title) = ($path =~ m{/([^/]+)$});
13255:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13256:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13257:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13258:                         my ($itemidx,$fullpath,$relpath);
13259:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13260:                             my $container = $dirorder{$referrer{$i}}->[-1];
13261:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13262:                                 if ($dirorder{$i}->[$j] eq $container) {
13263:                                     $itemidx = $j;
13264:                                 }
13265:                             }
13266:                         }
13267:                         if ($itemidx eq '') {
13268:                             $itemidx =  0;
13269:                         } 
13270:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13271:                             if ($mapinner{$referrer{$i}}) {
13272:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13273:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13274:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13275:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13276:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13277:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13278:                                             if (!-e $fullpath) {
13279:                                                 mkdir($fullpath,0755);
13280:                                             }
13281:                                         }
13282:                                     } else {
13283:                                         last;
13284:                                     }
13285:                                 }
13286:                             }
13287:                         } elsif ($newdest{$referrer{$i}}) {
13288:                             $fullpath = $newdest{$referrer{$i}};
13289:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13290:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13291:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13292:                                     last;
13293:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13294:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13295:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13296:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13297:                                         if (!-e $fullpath) {
13298:                                             mkdir($fullpath,0755);
13299:                                         }
13300:                                     }
13301:                                 } else {
13302:                                     last;
13303:                                 }
13304:                             }
13305:                         }
13306:                         if ($fullpath ne '') {
13307:                             if (-e "$prefix$path") {
13308:                                 system("mv $prefix$path $fullpath/$title");
13309:                             }
13310:                             if (-e "$fullpath/$title") {
13311:                                 my $showpath;
13312:                                 if ($relpath ne '') {
13313:                                     $showpath = "$relpath/$title";
13314:                                 } else {
13315:                                     $showpath = "/$title";
13316:                                 } 
13317:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
13318:                             } 
13319:                             unless ($ishome) {
13320:                                 my $fetch = "$fullpath/$title";
13321:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
13322:                                 $prompttofetch{$fetch} = 1;
13323:                             }
13324:                         }
13325:                     }
13326:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13327:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13328:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
13329:                 }
13330:             } else {
13331:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
13332:             }
13333:         }
13334:         if (keys(%todelete)) {
13335:             foreach my $key (keys(%todelete)) {
13336:                 unlink($key);
13337:             }
13338:         }
13339:         if (keys(%todeletedir)) {
13340:             foreach my $key (keys(%todeletedir)) {
13341:                 rmdir($key);
13342:             }
13343:         }
13344:         foreach my $dir (sort(keys(%is_dir))) {
13345:             if (($pathtocheck ne '') && ($dir ne ''))  {
13346:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13347:             }
13348:         }
13349:         if ($result ne '') {
13350:             $output .= '<ul>'."\n".
13351:                        $result."\n".
13352:                        '</ul>';
13353:         }
13354:         unless ($ishome) {
13355:             my $replicationfail;
13356:             foreach my $item (keys(%prompttofetch)) {
13357:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13358:                 unless ($fetchresult eq 'ok') {
13359:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13360:                 }
13361:             }
13362:             if ($replicationfail) {
13363:                 $output .= '<p class="LC_error">'.
13364:                            &mt('Course home server failed to retrieve:').'<ul>'.
13365:                            $replicationfail.
13366:                            '</ul></p>';
13367:             }
13368:         }
13369:     } else {
13370:         $warning = &mt('No items found in archive.');
13371:     }
13372:     if ($error) {
13373:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13374:                    $error.'</p>'."\n";
13375:     }
13376:     if ($warning) {
13377:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13378:     }
13379:     return $output;
13380: }
13381: 
13382: sub cleanup_empty_dirs {
13383:     my ($path) = @_;
13384:     if (($path ne '') && (-d $path)) {
13385:         if (opendir(my $dirh,$path)) {
13386:             my @dircontents = grep(!/^\./,readdir($dirh));
13387:             my $numitems = 0;
13388:             foreach my $item (@dircontents) {
13389:                 if (-d "$path/$item") {
13390:                     &cleanup_empty_dirs("$path/$item");
13391:                     if (-e "$path/$item") {
13392:                         $numitems ++;
13393:                     }
13394:                 } else {
13395:                     $numitems ++;
13396:                 }
13397:             }
13398:             if ($numitems == 0) {
13399:                 rmdir($path);
13400:             }
13401:             closedir($dirh);
13402:         }
13403:     }
13404:     return;
13405: }
13406: 
13407: =pod
13408: 
13409: =item * &get_folder_hierarchy()
13410: 
13411: Provides hierarchy of names of folders/sub-folders containing the current
13412: item,
13413: 
13414: Inputs: 3
13415:      - $navmap - navmaps object
13416: 
13417:      - $map - url for map (either the trigger itself, or map containing
13418:                            the resource, which is the trigger).
13419: 
13420:      - $showitem - 1 => show title for map itself; 0 => do not show.
13421: 
13422: Outputs: 1 @pathitems - array of folder/subfolder names.
13423: 
13424: =cut
13425: 
13426: sub get_folder_hierarchy {
13427:     my ($navmap,$map,$showitem) = @_;
13428:     my @pathitems;
13429:     if (ref($navmap)) {
13430:         my $mapres = $navmap->getResourceByUrl($map);
13431:         if (ref($mapres)) {
13432:             my $pcslist = $mapres->map_hierarchy();
13433:             if ($pcslist ne '') {
13434:                 my @pcs = split(/,/,$pcslist);
13435:                 foreach my $pc (@pcs) {
13436:                     if ($pc == 1) {
13437:                         push(@pathitems,&mt('Main Content'));
13438:                     } else {
13439:                         my $res = $navmap->getByMapPc($pc);
13440:                         if (ref($res)) {
13441:                             my $title = $res->compTitle();
13442:                             $title =~ s/\W+/_/g;
13443:                             if ($title ne '') {
13444:                                 push(@pathitems,$title);
13445:                             }
13446:                         }
13447:                     }
13448:                 }
13449:             }
13450:             if ($showitem) {
13451:                 if ($mapres->{ID} eq '0.0') {
13452:                     push(@pathitems,&mt('Main Content'));
13453:                 } else {
13454:                     my $maptitle = $mapres->compTitle();
13455:                     $maptitle =~ s/\W+/_/g;
13456:                     if ($maptitle ne '') {
13457:                         push(@pathitems,$maptitle);
13458:                     }
13459:                 }
13460:             }
13461:         }
13462:     }
13463:     return @pathitems;
13464: }
13465: 
13466: =pod
13467: 
13468: =item * &get_turnedin_filepath()
13469: 
13470: Determines path in a user's portfolio file for storage of files uploaded
13471: to a specific essayresponse or dropbox item.
13472: 
13473: Inputs: 3 required + 1 optional.
13474: $symb is symb for resource, $uname and $udom are for current user (required).
13475: $caller is optional (can be "submission", if routine is called when storing
13476: an upoaded file when "Submit Answer" button was pressed).
13477: 
13478: Returns array containing $path and $multiresp. 
13479: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13480: than one file upload item.  Callers of routine should append partid as a 
13481: subdirectory to $path in cases where $multiresp is 1.
13482: 
13483: Called by: homework/essayresponse.pm and homework/structuretags.pm
13484: 
13485: =cut
13486: 
13487: sub get_turnedin_filepath {
13488:     my ($symb,$uname,$udom,$caller) = @_;
13489:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13490:     my $turnindir;
13491:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13492:     $turnindir = $userhash{'turnindir'};
13493:     my ($path,$multiresp);
13494:     if ($turnindir eq '') {
13495:         if ($caller eq 'submission') {
13496:             $turnindir = &mt('turned in');
13497:             $turnindir =~ s/\W+/_/g;
13498:             my %newhash = (
13499:                             'turnindir' => $turnindir,
13500:                           );
13501:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13502:         }
13503:     }
13504:     if ($turnindir ne '') {
13505:         $path = '/'.$turnindir.'/';
13506:         my ($multipart,$turnin,@pathitems);
13507:         my $navmap = Apache::lonnavmaps::navmap->new();
13508:         if (defined($navmap)) {
13509:             my $mapres = $navmap->getResourceByUrl($map);
13510:             if (ref($mapres)) {
13511:                 my $pcslist = $mapres->map_hierarchy();
13512:                 if ($pcslist ne '') {
13513:                     foreach my $pc (split(/,/,$pcslist)) {
13514:                         my $res = $navmap->getByMapPc($pc);
13515:                         if (ref($res)) {
13516:                             my $title = $res->compTitle();
13517:                             $title =~ s/\W+/_/g;
13518:                             if ($title ne '') {
13519:                                 if (($pc > 1) && (length($title) > 12)) {
13520:                                     $title = substr($title,0,12);
13521:                                 }
13522:                                 push(@pathitems,$title);
13523:                             }
13524:                         }
13525:                     }
13526:                 }
13527:                 my $maptitle = $mapres->compTitle();
13528:                 $maptitle =~ s/\W+/_/g;
13529:                 if ($maptitle ne '') {
13530:                     if (length($maptitle) > 12) {
13531:                         $maptitle = substr($maptitle,0,12);
13532:                     }
13533:                     push(@pathitems,$maptitle);
13534:                 }
13535:                 unless ($env{'request.state'} eq 'construct') {
13536:                     my $res = $navmap->getBySymb($symb);
13537:                     if (ref($res)) {
13538:                         my $partlist = $res->parts();
13539:                         my $totaluploads = 0;
13540:                         if (ref($partlist) eq 'ARRAY') {
13541:                             foreach my $part (@{$partlist}) {
13542:                                 my @types = $res->responseType($part);
13543:                                 my @ids = $res->responseIds($part);
13544:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13545:                                     if ($types[$i] eq 'essay') {
13546:                                         my $partid = $part.'_'.$ids[$i];
13547:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13548:                                             $totaluploads ++;
13549:                                         }
13550:                                     }
13551:                                 }
13552:                             }
13553:                             if ($totaluploads > 1) {
13554:                                 $multiresp = 1;
13555:                             }
13556:                         }
13557:                     }
13558:                 }
13559:             } else {
13560:                 return;
13561:             }
13562:         } else {
13563:             return;
13564:         }
13565:         my $restitle=&Apache::lonnet::gettitle($symb);
13566:         $restitle =~ s/\W+/_/g;
13567:         if ($restitle eq '') {
13568:             $restitle = ($resurl =~ m{/[^/]+$});
13569:             if ($restitle eq '') {
13570:                 $restitle = time;
13571:             }
13572:         }
13573:         if (length($restitle) > 12) {
13574:             $restitle = substr($restitle,0,12);
13575:         }
13576:         push(@pathitems,$restitle);
13577:         $path .= join('/',@pathitems);
13578:     }
13579:     return ($path,$multiresp);
13580: }
13581: 
13582: =pod
13583: 
13584: =back
13585: 
13586: =head1 CSV Upload/Handling functions
13587: 
13588: =over 4
13589: 
13590: =item * &upfile_store($r)
13591: 
13592: Store uploaded file, $r should be the HTTP Request object,
13593: needs $env{'form.upfile'}
13594: returns $datatoken to be put into hidden field
13595: 
13596: =cut
13597: 
13598: sub upfile_store {
13599:     my $r=shift;
13600:     $env{'form.upfile'}=~s/\r/\n/gs;
13601:     $env{'form.upfile'}=~s/\f/\n/gs;
13602:     $env{'form.upfile'}=~s/\n+/\n/gs;
13603:     $env{'form.upfile'}=~s/\n+$//gs;
13604: 
13605:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13606: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13607:     {
13608:         my $datafile = $r->dir_config('lonDaemons').
13609:                            '/tmp/'.$datatoken.'.tmp';
13610:         if ( open(my $fh,">$datafile") ) {
13611:             print $fh $env{'form.upfile'};
13612:             close($fh);
13613:         }
13614:     }
13615:     return $datatoken;
13616: }
13617: 
13618: =pod
13619: 
13620: =item * &load_tmp_file($r)
13621: 
13622: Load uploaded file from tmp, $r should be the HTTP Request object,
13623: needs $env{'form.datatoken'},
13624: sets $env{'form.upfile'} to the contents of the file
13625: 
13626: =cut
13627: 
13628: sub load_tmp_file {
13629:     my $r=shift;
13630:     my @studentdata=();
13631:     {
13632:         my $studentfile = $r->dir_config('lonDaemons').
13633:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13634:         if ( open(my $fh,"<$studentfile") ) {
13635:             @studentdata=<$fh>;
13636:             close($fh);
13637:         }
13638:     }
13639:     $env{'form.upfile'}=join('',@studentdata);
13640: }
13641: 
13642: =pod
13643: 
13644: =item * &upfile_record_sep()
13645: 
13646: Separate uploaded file into records
13647: returns array of records,
13648: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13649: 
13650: =cut
13651: 
13652: sub upfile_record_sep {
13653:     if ($env{'form.upfiletype'} eq 'xml') {
13654:     } else {
13655: 	my @records;
13656: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13657: 	    if ($line=~/^\s*$/) { next; }
13658: 	    push(@records,$line);
13659: 	}
13660: 	return @records;
13661:     }
13662: }
13663: 
13664: =pod
13665: 
13666: =item * &record_sep($record)
13667: 
13668: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13669: 
13670: =cut
13671: 
13672: sub takeleft {
13673:     my $index=shift;
13674:     return substr('0000'.$index,-4,4);
13675: }
13676: 
13677: sub record_sep {
13678:     my $record=shift;
13679:     my %components=();
13680:     if ($env{'form.upfiletype'} eq 'xml') {
13681:     } elsif ($env{'form.upfiletype'} eq 'space') {
13682:         my $i=0;
13683:         foreach my $field (split(/\s+/,$record)) {
13684:             $field=~s/^(\"|\')//;
13685:             $field=~s/(\"|\')$//;
13686:             $components{&takeleft($i)}=$field;
13687:             $i++;
13688:         }
13689:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13690:         my $i=0;
13691:         foreach my $field (split(/\t/,$record)) {
13692:             $field=~s/^(\"|\')//;
13693:             $field=~s/(\"|\')$//;
13694:             $components{&takeleft($i)}=$field;
13695:             $i++;
13696:         }
13697:     } else {
13698:         my $separator=',';
13699:         if ($env{'form.upfiletype'} eq 'semisv') {
13700:             $separator=';';
13701:         }
13702:         my $i=0;
13703: # the character we are looking for to indicate the end of a quote or a record 
13704:         my $looking_for=$separator;
13705: # do not add the characters to the fields
13706:         my $ignore=0;
13707: # we just encountered a separator (or the beginning of the record)
13708:         my $just_found_separator=1;
13709: # store the field we are working on here
13710:         my $field='';
13711: # work our way through all characters in record
13712:         foreach my $character ($record=~/(.)/g) {
13713:             if ($character eq $looking_for) {
13714:                if ($character ne $separator) {
13715: # Found the end of a quote, again looking for separator
13716:                   $looking_for=$separator;
13717:                   $ignore=1;
13718:                } else {
13719: # Found a separator, store away what we got
13720:                   $components{&takeleft($i)}=$field;
13721: 	          $i++;
13722:                   $just_found_separator=1;
13723:                   $ignore=0;
13724:                   $field='';
13725:                }
13726:                next;
13727:             }
13728: # single or double quotation marks after a separator indicate beginning of a quote
13729: # we are now looking for the end of the quote and need to ignore separators
13730:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13731:                $looking_for=$character;
13732:                next;
13733:             }
13734: # ignore would be true after we reached the end of a quote
13735:             if ($ignore) { next; }
13736:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13737:             $field.=$character;
13738:             $just_found_separator=0; 
13739:         }
13740: # catch the very last entry, since we never encountered the separator
13741:         $components{&takeleft($i)}=$field;
13742:     }
13743:     return %components;
13744: }
13745: 
13746: ######################################################
13747: ######################################################
13748: 
13749: =pod
13750: 
13751: =item * &upfile_select_html()
13752: 
13753: Return HTML code to select a file from the users machine and specify 
13754: the file type.
13755: 
13756: =cut
13757: 
13758: ######################################################
13759: ######################################################
13760: sub upfile_select_html {
13761:     my %Types = (
13762:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13763:                  semisv => &mt('Semicolon separated values'),
13764:                  space => &mt('Space separated'),
13765:                  tab   => &mt('Tabulator separated'),
13766: #                 xml   => &mt('HTML/XML'),
13767:                  );
13768:     my $Str = '<input type="file" name="upfile" size="50" />'.
13769:         '<br />'.&mt('Type').': <select name="upfiletype">';
13770:     foreach my $type (sort(keys(%Types))) {
13771:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13772:     }
13773:     $Str .= "</select>\n";
13774:     return $Str;
13775: }
13776: 
13777: sub get_samples {
13778:     my ($records,$toget) = @_;
13779:     my @samples=({});
13780:     my $got=0;
13781:     foreach my $rec (@$records) {
13782: 	my %temp = &record_sep($rec);
13783: 	if (! grep(/\S/, values(%temp))) { next; }
13784: 	if (%temp) {
13785: 	    $samples[$got]=\%temp;
13786: 	    $got++;
13787: 	    if ($got == $toget) { last; }
13788: 	}
13789:     }
13790:     return \@samples;
13791: }
13792: 
13793: ######################################################
13794: ######################################################
13795: 
13796: =pod
13797: 
13798: =item * &csv_print_samples($r,$records)
13799: 
13800: Prints a table of sample values from each column uploaded $r is an
13801: Apache Request ref, $records is an arrayref from
13802: &Apache::loncommon::upfile_record_sep
13803: 
13804: =cut
13805: 
13806: ######################################################
13807: ######################################################
13808: sub csv_print_samples {
13809:     my ($r,$records) = @_;
13810:     my $samples = &get_samples($records,5);
13811: 
13812:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13813:               &start_data_table_header_row());
13814:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13815:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13816:     $r->print(&end_data_table_header_row());
13817:     foreach my $hash (@$samples) {
13818: 	$r->print(&start_data_table_row());
13819: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13820: 	    $r->print('<td>');
13821: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13822: 	    $r->print('</td>');
13823: 	}
13824: 	$r->print(&end_data_table_row());
13825:     }
13826:     $r->print(&end_data_table().'<br />'."\n");
13827: }
13828: 
13829: ######################################################
13830: ######################################################
13831: 
13832: =pod
13833: 
13834: =item * &csv_print_select_table($r,$records,$d)
13835: 
13836: Prints a table to create associations between values and table columns.
13837: 
13838: $r is an Apache Request ref,
13839: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13840: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13841: 
13842: =cut
13843: 
13844: ######################################################
13845: ######################################################
13846: sub csv_print_select_table {
13847:     my ($r,$records,$d) = @_;
13848:     my $i=0;
13849:     my $samples = &get_samples($records,1);
13850:     $r->print(&mt('Associate columns with student attributes.')."\n".
13851: 	      &start_data_table().&start_data_table_header_row().
13852:               '<th>'.&mt('Attribute').'</th>'.
13853:               '<th>'.&mt('Column').'</th>'.
13854:               &end_data_table_header_row()."\n");
13855:     foreach my $array_ref (@$d) {
13856: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13857: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13858: 
13859: 	$r->print('<td><select name="f'.$i.'"'.
13860: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13861: 	$r->print('<option value="none"></option>');
13862: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13863: 	    $r->print('<option value="'.$sample.'"'.
13864:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13865:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13866: 	}
13867: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13868: 	$i++;
13869:     }
13870:     $r->print(&end_data_table());
13871:     $i--;
13872:     return $i;
13873: }
13874: 
13875: ######################################################
13876: ######################################################
13877: 
13878: =pod
13879: 
13880: =item * &csv_samples_select_table($r,$records,$d)
13881: 
13882: Prints a table of sample values from the upload and can make associate samples to internal names.
13883: 
13884: $r is an Apache Request ref,
13885: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13886: $d is an array of 2 element arrays (internal name, displayed name)
13887: 
13888: =cut
13889: 
13890: ######################################################
13891: ######################################################
13892: sub csv_samples_select_table {
13893:     my ($r,$records,$d) = @_;
13894:     my $i=0;
13895:     #
13896:     my $max_samples = 5;
13897:     my $samples = &get_samples($records,$max_samples);
13898:     $r->print(&start_data_table().
13899:               &start_data_table_header_row().'<th>'.
13900:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13901:               &end_data_table_header_row());
13902: 
13903:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13904: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13905: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13906: 	foreach my $option (@$d) {
13907: 	    my ($value,$display,$defaultcol)=@{ $option };
13908: 	    $r->print('<option value="'.$value.'"'.
13909:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13910:                       $display.'</option>');
13911: 	}
13912: 	$r->print('</select></td><td>');
13913: 	foreach my $line (0..($max_samples-1)) {
13914: 	    if (defined($samples->[$line]{$key})) { 
13915: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13916: 	    }
13917: 	}
13918: 	$r->print('</td>'.&end_data_table_row());
13919: 	$i++;
13920:     }
13921:     $r->print(&end_data_table());
13922:     $i--;
13923:     return($i);
13924: }
13925: 
13926: ######################################################
13927: ######################################################
13928: 
13929: =pod
13930: 
13931: =item * &clean_excel_name($name)
13932: 
13933: Returns a replacement for $name which does not contain any illegal characters.
13934: 
13935: =cut
13936: 
13937: ######################################################
13938: ######################################################
13939: sub clean_excel_name {
13940:     my ($name) = @_;
13941:     $name =~ s/[:\*\?\/\\]//g;
13942:     if (length($name) > 31) {
13943:         $name = substr($name,0,31);
13944:     }
13945:     return $name;
13946: }
13947: 
13948: =pod
13949: 
13950: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13951: 
13952: Returns either 1 or undef
13953: 
13954: 1 if the part is to be hidden, undef if it is to be shown
13955: 
13956: Arguments are:
13957: 
13958: $id the id of the part to be checked
13959: $symb, optional the symb of the resource to check
13960: $udom, optional the domain of the user to check for
13961: $uname, optional the username of the user to check for
13962: 
13963: =cut
13964: 
13965: sub check_if_partid_hidden {
13966:     my ($id,$symb,$udom,$uname) = @_;
13967:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13968: 					 $symb,$udom,$uname);
13969:     my $truth=1;
13970:     #if the string starts with !, then the list is the list to show not hide
13971:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13972:     my @hiddenlist=split(/,/,$hiddenparts);
13973:     foreach my $checkid (@hiddenlist) {
13974: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13975:     }
13976:     return !$truth;
13977: }
13978: 
13979: 
13980: ############################################################
13981: ############################################################
13982: 
13983: =pod
13984: 
13985: =back 
13986: 
13987: =head1 cgi-bin script and graphing routines
13988: 
13989: =over 4
13990: 
13991: =item * &get_cgi_id()
13992: 
13993: Inputs: none
13994: 
13995: Returns an id which can be used to pass environment variables
13996: to various cgi-bin scripts.  These environment variables will
13997: be removed from the users environment after a given time by
13998: the routine &Apache::lonnet::transfer_profile_to_env.
13999: 
14000: =cut
14001: 
14002: ############################################################
14003: ############################################################
14004: my $uniq=0;
14005: sub get_cgi_id {
14006:     $uniq=($uniq+1)%100000;
14007:     return (time.'_'.$$.'_'.$uniq);
14008: }
14009: 
14010: ############################################################
14011: ############################################################
14012: 
14013: =pod
14014: 
14015: =item * &DrawBarGraph()
14016: 
14017: Facilitates the plotting of data in a (stacked) bar graph.
14018: Puts plot definition data into the users environment in order for 
14019: graph.png to plot it.  Returns an <img> tag for the plot.
14020: The bars on the plot are labeled '1','2',...,'n'.
14021: 
14022: Inputs:
14023: 
14024: =over 4
14025: 
14026: =item $Title: string, the title of the plot
14027: 
14028: =item $xlabel: string, text describing the X-axis of the plot
14029: 
14030: =item $ylabel: string, text describing the Y-axis of the plot
14031: 
14032: =item $Max: scalar, the maximum Y value to use in the plot
14033: If $Max is < any data point, the graph will not be rendered.
14034: 
14035: =item $colors: array ref holding the colors to be used for the data sets when
14036: they are plotted.  If undefined, default values will be used.
14037: 
14038: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14039: 
14040: =item @Values: An array of array references.  Each array reference holds data
14041: to be plotted in a stacked bar chart.
14042: 
14043: =item If the final element of @Values is a hash reference the key/value
14044: pairs will be added to the graph definition.
14045: 
14046: =back
14047: 
14048: Returns:
14049: 
14050: An <img> tag which references graph.png and the appropriate identifying
14051: information for the plot.
14052: 
14053: =cut
14054: 
14055: ############################################################
14056: ############################################################
14057: sub DrawBarGraph {
14058:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14059:     #
14060:     if (! defined($colors)) {
14061:         $colors = ['#33ff00', 
14062:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14063:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14064:                   ]; 
14065:     }
14066:     my $extra_settings = {};
14067:     if (ref($Values[-1]) eq 'HASH') {
14068:         $extra_settings = pop(@Values);
14069:     }
14070:     #
14071:     my $identifier = &get_cgi_id();
14072:     my $id = 'cgi.'.$identifier;        
14073:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14074:         return '';
14075:     }
14076:     #
14077:     my @Labels;
14078:     if (defined($labels)) {
14079:         @Labels = @$labels;
14080:     } else {
14081:         for (my $i=0;$i<@{$Values[0]};$i++) {
14082:             push(@Labels,$i+1);
14083:         }
14084:     }
14085:     #
14086:     my $NumBars = scalar(@{$Values[0]});
14087:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14088:     my %ValuesHash;
14089:     my $NumSets=1;
14090:     foreach my $array (@Values) {
14091:         next if (! ref($array));
14092:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14093:             join(',',@$array);
14094:     }
14095:     #
14096:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14097:     if ($NumBars < 3) {
14098:         $width = 120+$NumBars*32;
14099:         $xskip = 1;
14100:         $bar_width = 30;
14101:     } elsif ($NumBars < 5) {
14102:         $width = 120+$NumBars*20;
14103:         $xskip = 1;
14104:         $bar_width = 20;
14105:     } elsif ($NumBars < 10) {
14106:         $width = 120+$NumBars*15;
14107:         $xskip = 1;
14108:         $bar_width = 15;
14109:     } elsif ($NumBars <= 25) {
14110:         $width = 120+$NumBars*11;
14111:         $xskip = 5;
14112:         $bar_width = 8;
14113:     } elsif ($NumBars <= 50) {
14114:         $width = 120+$NumBars*8;
14115:         $xskip = 5;
14116:         $bar_width = 4;
14117:     } else {
14118:         $width = 120+$NumBars*8;
14119:         $xskip = 5;
14120:         $bar_width = 4;
14121:     }
14122:     #
14123:     $Max = 1 if ($Max < 1);
14124:     if ( int($Max) < $Max ) {
14125:         $Max++;
14126:         $Max = int($Max);
14127:     }
14128:     $Title  = '' if (! defined($Title));
14129:     $xlabel = '' if (! defined($xlabel));
14130:     $ylabel = '' if (! defined($ylabel));
14131:     $ValuesHash{$id.'.title'}    = &escape($Title);
14132:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14133:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14134:     $ValuesHash{$id.'.y_max_value'} = $Max;
14135:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14136:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14137:     $ValuesHash{$id.'.PlotType'} = 'bar';
14138:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14139:     $ValuesHash{$id.'.height'}   = $height;
14140:     $ValuesHash{$id.'.width'}    = $width;
14141:     $ValuesHash{$id.'.xskip'}    = $xskip;
14142:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14143:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14144:     #
14145:     # Deal with other parameters
14146:     while (my ($key,$value) = each(%$extra_settings)) {
14147:         $ValuesHash{$id.'.'.$key} = $value;
14148:     }
14149:     #
14150:     &Apache::lonnet::appenv(\%ValuesHash);
14151:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14152: }
14153: 
14154: ############################################################
14155: ############################################################
14156: 
14157: =pod
14158: 
14159: =item * &DrawXYGraph()
14160: 
14161: Facilitates the plotting of data in an XY graph.
14162: Puts plot definition data into the users environment in order for 
14163: graph.png to plot it.  Returns an <img> tag for the plot.
14164: 
14165: Inputs:
14166: 
14167: =over 4
14168: 
14169: =item $Title: string, the title of the plot
14170: 
14171: =item $xlabel: string, text describing the X-axis of the plot
14172: 
14173: =item $ylabel: string, text describing the Y-axis of the plot
14174: 
14175: =item $Max: scalar, the maximum Y value to use in the plot
14176: If $Max is < any data point, the graph will not be rendered.
14177: 
14178: =item $colors: Array ref containing the hex color codes for the data to be 
14179: plotted in.  If undefined, default values will be used.
14180: 
14181: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14182: 
14183: =item $Ydata: Array ref containing Array refs.  
14184: Each of the contained arrays will be plotted as a separate curve.
14185: 
14186: =item %Values: hash indicating or overriding any default values which are 
14187: passed to graph.png.  
14188: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14189: 
14190: =back
14191: 
14192: Returns:
14193: 
14194: An <img> tag which references graph.png and the appropriate identifying
14195: information for the plot.
14196: 
14197: =cut
14198: 
14199: ############################################################
14200: ############################################################
14201: sub DrawXYGraph {
14202:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14203:     #
14204:     # Create the identifier for the graph
14205:     my $identifier = &get_cgi_id();
14206:     my $id = 'cgi.'.$identifier;
14207:     #
14208:     $Title  = '' if (! defined($Title));
14209:     $xlabel = '' if (! defined($xlabel));
14210:     $ylabel = '' if (! defined($ylabel));
14211:     my %ValuesHash = 
14212:         (
14213:          $id.'.title'  => &escape($Title),
14214:          $id.'.xlabel' => &escape($xlabel),
14215:          $id.'.ylabel' => &escape($ylabel),
14216:          $id.'.y_max_value'=> $Max,
14217:          $id.'.labels'     => join(',',@$Xlabels),
14218:          $id.'.PlotType'   => 'XY',
14219:          );
14220:     #
14221:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14222:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14223:     }
14224:     #
14225:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14226:         return '';
14227:     }
14228:     my $NumSets=1;
14229:     foreach my $array (@{$Ydata}){
14230:         next if (! ref($array));
14231:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14232:     }
14233:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14234:     #
14235:     # Deal with other parameters
14236:     while (my ($key,$value) = each(%Values)) {
14237:         $ValuesHash{$id.'.'.$key} = $value;
14238:     }
14239:     #
14240:     &Apache::lonnet::appenv(\%ValuesHash);
14241:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14242: }
14243: 
14244: ############################################################
14245: ############################################################
14246: 
14247: =pod
14248: 
14249: =item * &DrawXYYGraph()
14250: 
14251: Facilitates the plotting of data in an XY graph with two Y axes.
14252: Puts plot definition data into the users environment in order for 
14253: graph.png to plot it.  Returns an <img> tag for the plot.
14254: 
14255: Inputs:
14256: 
14257: =over 4
14258: 
14259: =item $Title: string, the title of the plot
14260: 
14261: =item $xlabel: string, text describing the X-axis of the plot
14262: 
14263: =item $ylabel: string, text describing the Y-axis of the plot
14264: 
14265: =item $colors: Array ref containing the hex color codes for the data to be 
14266: plotted in.  If undefined, default values will be used.
14267: 
14268: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14269: 
14270: =item $Ydata1: The first data set
14271: 
14272: =item $Min1: The minimum value of the left Y-axis
14273: 
14274: =item $Max1: The maximum value of the left Y-axis
14275: 
14276: =item $Ydata2: The second data set
14277: 
14278: =item $Min2: The minimum value of the right Y-axis
14279: 
14280: =item $Max2: The maximum value of the left Y-axis
14281: 
14282: =item %Values: hash indicating or overriding any default values which are 
14283: passed to graph.png.  
14284: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14285: 
14286: =back
14287: 
14288: Returns:
14289: 
14290: An <img> tag which references graph.png and the appropriate identifying
14291: information for the plot.
14292: 
14293: =cut
14294: 
14295: ############################################################
14296: ############################################################
14297: sub DrawXYYGraph {
14298:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14299:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14300:     #
14301:     # Create the identifier for the graph
14302:     my $identifier = &get_cgi_id();
14303:     my $id = 'cgi.'.$identifier;
14304:     #
14305:     $Title  = '' if (! defined($Title));
14306:     $xlabel = '' if (! defined($xlabel));
14307:     $ylabel = '' if (! defined($ylabel));
14308:     my %ValuesHash = 
14309:         (
14310:          $id.'.title'  => &escape($Title),
14311:          $id.'.xlabel' => &escape($xlabel),
14312:          $id.'.ylabel' => &escape($ylabel),
14313:          $id.'.labels' => join(',',@$Xlabels),
14314:          $id.'.PlotType' => 'XY',
14315:          $id.'.NumSets' => 2,
14316:          $id.'.two_axes' => 1,
14317:          $id.'.y1_max_value' => $Max1,
14318:          $id.'.y1_min_value' => $Min1,
14319:          $id.'.y2_max_value' => $Max2,
14320:          $id.'.y2_min_value' => $Min2,
14321:          );
14322:     #
14323:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14324:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14325:     }
14326:     #
14327:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14328:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14329:         return '';
14330:     }
14331:     my $NumSets=1;
14332:     foreach my $array ($Ydata1,$Ydata2){
14333:         next if (! ref($array));
14334:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14335:     }
14336:     #
14337:     # Deal with other parameters
14338:     while (my ($key,$value) = each(%Values)) {
14339:         $ValuesHash{$id.'.'.$key} = $value;
14340:     }
14341:     #
14342:     &Apache::lonnet::appenv(\%ValuesHash);
14343:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14344: }
14345: 
14346: ############################################################
14347: ############################################################
14348: 
14349: =pod
14350: 
14351: =back 
14352: 
14353: =head1 Statistics helper routines?  
14354: 
14355: Bad place for them but what the hell.
14356: 
14357: =over 4
14358: 
14359: =item * &chartlink()
14360: 
14361: Returns a link to the chart for a specific student.  
14362: 
14363: Inputs:
14364: 
14365: =over 4
14366: 
14367: =item $linktext: The text of the link
14368: 
14369: =item $sname: The students username
14370: 
14371: =item $sdomain: The students domain
14372: 
14373: =back
14374: 
14375: =back
14376: 
14377: =cut
14378: 
14379: ############################################################
14380: ############################################################
14381: sub chartlink {
14382:     my ($linktext, $sname, $sdomain) = @_;
14383:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14384:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14385:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14386:        '">'.$linktext.'</a>';
14387: }
14388: 
14389: #######################################################
14390: #######################################################
14391: 
14392: =pod
14393: 
14394: =head1 Course Environment Routines
14395: 
14396: =over 4
14397: 
14398: =item * &restore_course_settings()
14399: 
14400: =item * &store_course_settings()
14401: 
14402: Restores/Store indicated form parameters from the course environment.
14403: Will not overwrite existing values of the form parameters.
14404: 
14405: Inputs: 
14406: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14407: 
14408: a hash ref describing the data to be stored.  For example:
14409:    
14410: %Save_Parameters = ('Status' => 'scalar',
14411:     'chartoutputmode' => 'scalar',
14412:     'chartoutputdata' => 'scalar',
14413:     'Section' => 'array',
14414:     'Group' => 'array',
14415:     'StudentData' => 'array',
14416:     'Maps' => 'array');
14417: 
14418: Returns: both routines return nothing
14419: 
14420: =back
14421: 
14422: =cut
14423: 
14424: #######################################################
14425: #######################################################
14426: sub store_course_settings {
14427:     return &store_settings($env{'request.course.id'},@_);
14428: }
14429: 
14430: sub store_settings {
14431:     # save to the environment
14432:     # appenv the same items, just to be safe
14433:     my $udom  = $env{'user.domain'};
14434:     my $uname = $env{'user.name'};
14435:     my ($context,$prefix,$Settings) = @_;
14436:     my %SaveHash;
14437:     my %AppHash;
14438:     while (my ($setting,$type) = each(%$Settings)) {
14439:         my $basename = join('.','internal',$context,$prefix,$setting);
14440:         my $envname = 'environment.'.$basename;
14441:         if (exists($env{'form.'.$setting})) {
14442:             # Save this value away
14443:             if ($type eq 'scalar' &&
14444:                 (! exists($env{$envname}) || 
14445:                  $env{$envname} ne $env{'form.'.$setting})) {
14446:                 $SaveHash{$basename} = $env{'form.'.$setting};
14447:                 $AppHash{$envname}   = $env{'form.'.$setting};
14448:             } elsif ($type eq 'array') {
14449:                 my $stored_form;
14450:                 if (ref($env{'form.'.$setting})) {
14451:                     $stored_form = join(',',
14452:                                         map {
14453:                                             &escape($_);
14454:                                         } sort(@{$env{'form.'.$setting}}));
14455:                 } else {
14456:                     $stored_form = 
14457:                         &escape($env{'form.'.$setting});
14458:                 }
14459:                 # Determine if the array contents are the same.
14460:                 if ($stored_form ne $env{$envname}) {
14461:                     $SaveHash{$basename} = $stored_form;
14462:                     $AppHash{$envname}   = $stored_form;
14463:                 }
14464:             }
14465:         }
14466:     }
14467:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14468:                                           $udom,$uname);
14469:     if ($put_result !~ /^(ok|delayed)/) {
14470:         &Apache::lonnet::logthis('unable to save form parameters, '.
14471:                                  'got error:'.$put_result);
14472:     }
14473:     # Make sure these settings stick around in this session, too
14474:     &Apache::lonnet::appenv(\%AppHash);
14475:     return;
14476: }
14477: 
14478: sub restore_course_settings {
14479:     return &restore_settings($env{'request.course.id'},@_);
14480: }
14481: 
14482: sub restore_settings {
14483:     my ($context,$prefix,$Settings) = @_;
14484:     while (my ($setting,$type) = each(%$Settings)) {
14485:         next if (exists($env{'form.'.$setting}));
14486:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14487:             '.'.$setting;
14488:         if (exists($env{$envname})) {
14489:             if ($type eq 'scalar') {
14490:                 $env{'form.'.$setting} = $env{$envname};
14491:             } elsif ($type eq 'array') {
14492:                 $env{'form.'.$setting} = [ 
14493:                                            map { 
14494:                                                &unescape($_); 
14495:                                            } split(',',$env{$envname})
14496:                                            ];
14497:             }
14498:         }
14499:     }
14500: }
14501: 
14502: #######################################################
14503: #######################################################
14504: 
14505: =pod
14506: 
14507: =head1 Domain E-mail Routines  
14508: 
14509: =over 4
14510: 
14511: =item * &build_recipient_list()
14512: 
14513: Build recipient lists for following types of e-mail:
14514: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14515: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14516: module change checking, student/employee ID conflict checks, as
14517: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14518: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14519: 
14520: Inputs:
14521: defmail (scalar - email address of default recipient), 
14522: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14523: requestsmail, updatesmail, or idconflictsmail).
14524: 
14525: defdom (domain for which to retrieve configuration settings),
14526: 
14527: origmail (scalar - email address of recipient from loncapa.conf, 
14528: i.e., predates configuration by DC via domainprefs.pm 
14529: 
14530: Returns: comma separated list of addresses to which to send e-mail.
14531: 
14532: =back
14533: 
14534: =cut
14535: 
14536: ############################################################
14537: ############################################################
14538: sub build_recipient_list {
14539:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14540:     my @recipients;
14541:     my ($otheremails,$lastresort,$allbcc,$addtext);
14542:     my %domconfig =
14543:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14544:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14545:         if (exists($domconfig{'contacts'}{$mailing})) {
14546:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14547:                 my @contacts = ('adminemail','supportemail');
14548:                 foreach my $item (@contacts) {
14549:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14550:                         my $addr = $domconfig{'contacts'}{$item}; 
14551:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14552:                             push(@recipients,$addr);
14553:                         }
14554:                     }
14555:                 }
14556:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14557:                 if ($mailing eq 'helpdeskmail') {
14558:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14559:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14560:                         my @ok_bccs;
14561:                         foreach my $bcc (@bccs) {
14562:                             $bcc =~ s/^\s+//g;
14563:                             $bcc =~ s/\s+$//g;
14564:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14565:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14566:                                     push(@ok_bccs,$bcc);
14567:                                 }
14568:                             }
14569:                         }
14570:                         if (@ok_bccs > 0) {
14571:                             $allbcc = join(', ',@ok_bccs);
14572:                         }
14573:                     }
14574:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14575:                 }
14576:             }
14577:         } elsif ($origmail ne '') {
14578:             $lastresort = $origmail;
14579:         }
14580:     } elsif ($origmail ne '') {
14581:         $lastresort = $origmail;
14582:     }
14583: 
14584:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
14585:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14586:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14587:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14588:             my %what = (
14589:                           perlvar => 1,
14590:                        );
14591:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14592:             if ($primary) {
14593:                 my $gotaddr;
14594:                 my ($result,$returnhash) =
14595:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14596:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14597:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14598:                         $lastresort = $returnhash->{'lonSupportEMail'};
14599:                         $gotaddr = 1;
14600:                     }
14601:                 }
14602:                 unless ($gotaddr) {
14603:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14604:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14605:                     unless ($uintdom eq $intdom) {
14606:                         my %domconfig =
14607:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14608:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14609:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14610:                                 my @contacts = ('adminemail','supportemail');
14611:                                 foreach my $item (@contacts) {
14612:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14613:                                         my $addr = $domconfig{'contacts'}{$item};
14614:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14615:                                             push(@recipients,$addr);
14616:                                         }
14617:                                     }
14618:                                 }
14619:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14620:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14621:                                 }
14622:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14623:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14624:                                     my @ok_bccs;
14625:                                     foreach my $bcc (@bccs) {
14626:                                         $bcc =~ s/^\s+//g;
14627:                                         $bcc =~ s/\s+$//g;
14628:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14629:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14630:                                                 push(@ok_bccs,$bcc);
14631:                                             }
14632:                                         }
14633:                                     }
14634:                                     if (@ok_bccs > 0) {
14635:                                         $allbcc = join(', ',@ok_bccs);
14636:                                     }
14637:                                 }
14638:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14639:                             }
14640:                         }
14641:                     }
14642:                 }
14643:             }
14644:         }
14645:     }
14646:     if (defined($defmail)) {
14647:         if ($defmail ne '') {
14648:             push(@recipients,$defmail);
14649:         }
14650:     }
14651:     if ($otheremails) {
14652:         my @others;
14653:         if ($otheremails =~ /,/) {
14654:             @others = split(/,/,$otheremails);
14655:         } else {
14656:             push(@others,$otheremails);
14657:         }
14658:         foreach my $addr (@others) {
14659:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14660:                 push(@recipients,$addr);
14661:             }
14662:         }
14663:     }
14664:     if ($mailing eq 'helpdesk') {
14665:         if ((!@recipients) && ($lastresort ne '')) {
14666:             push(@recipients,$lastresort);
14667:         }
14668:     } elsif ($lastresort ne '') {
14669:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14670:             push(@recipients,$lastresort);
14671:         }
14672:     }
14673:     my $recipientlist = join(',',@recipients);
14674:     if (wantarray) {
14675:         return ($recipientlist,$allbcc,$addtext);
14676:     } else {
14677:         return $recipientlist;
14678:     }
14679: }
14680: 
14681: ############################################################
14682: ############################################################
14683: 
14684: =pod
14685: 
14686: =over 4
14687: 
14688: =item * &mime_email()
14689: 
14690: Sends an email with a possible attachment
14691: 
14692: Inputs:
14693: 
14694: =over 4
14695: 
14696: from -              Sender's email address
14697: 
14698: to -                Email address of recipient
14699: 
14700: subject -           Subject of email
14701: 
14702: body -              Body of email
14703: 
14704: cc_string -         Carbon copy email address
14705: 
14706: bcc -               Blind carbon copy email address
14707: 
14708: type -              File type of attachment
14709: 
14710: attachment_path -   Path of file to be attached
14711: 
14712: file_name -         Name of file to be attached
14713: 
14714: attachment_text -   The body of an attachment of type "TEXT"
14715: 
14716: =back
14717: 
14718: =back
14719: 
14720: =cut
14721: 
14722: ############################################################
14723: ############################################################
14724: 
14725: sub mime_email {
14726:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
14727:         $file_name, $attachment_text) = @_;
14728:     my $msg = MIME::Lite->new(
14729:              From    => $from,
14730:              To      => $to,
14731:              Subject => $subject,
14732:              Type    =>'TEXT',
14733:              Data    => $body,
14734:              );
14735:     if ($cc_string ne '') {
14736:         $msg->add("Cc" => $cc_string);
14737:     }
14738:     if ($bcc ne '') {
14739:         $msg->add("Bcc" => $bcc);
14740:     }
14741:     $msg->attr("content-type"         => "text/plain");
14742:     $msg->attr("content-type.charset" => "UTF-8");
14743:     # Attach file if given
14744:     if ($attachment_path) {
14745:         unless ($file_name) {
14746:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14747:         }
14748:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14749:         $msg->attach(Type     => $type,
14750:                      Path     => $attachment_path,
14751:                      Filename => $file_name
14752:                      );
14753:     # Otherwise attach text if given
14754:     } elsif ($attachment_text) {
14755:         $msg->attach(Type => 'TEXT',
14756:                      Data => $attachment_text);
14757:     }
14758:     # Send it
14759:     $msg->send('sendmail');
14760: }
14761: 
14762: ############################################################
14763: ############################################################
14764: 
14765: =pod
14766: 
14767: =head1 Course Catalog Routines
14768: 
14769: =over 4
14770: 
14771: =item * &gather_categories()
14772: 
14773: Converts category definitions - keys of categories hash stored in  
14774: coursecategories in configuration.db on the primary library server in a 
14775: domain - to an array.  Also generates javascript and idx hash used to 
14776: generate Domain Coordinator interface for editing Course Categories.
14777: 
14778: Inputs:
14779: 
14780: categories (reference to hash of category definitions).
14781: 
14782: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14783:       categories and subcategories).
14784: 
14785: idx (reference to hash of counters used in Domain Coordinator interface for 
14786:       editing Course Categories).
14787: 
14788: jsarray (reference to array of categories used to create Javascript arrays for
14789:          Domain Coordinator interface for editing Course Categories).
14790: 
14791: Returns: nothing
14792: 
14793: Side effects: populates cats, idx and jsarray. 
14794: 
14795: =cut
14796: 
14797: sub gather_categories {
14798:     my ($categories,$cats,$idx,$jsarray) = @_;
14799:     my %counters;
14800:     my $num = 0;
14801:     foreach my $item (keys(%{$categories})) {
14802:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14803:         if ($container eq '' && $depth == 0) {
14804:             $cats->[$depth][$categories->{$item}] = $cat;
14805:         } else {
14806:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14807:         }
14808:         my ($escitem,$tail) = split(/:/,$item,2);
14809:         if ($counters{$tail} eq '') {
14810:             $counters{$tail} = $num;
14811:             $num ++;
14812:         }
14813:         if (ref($idx) eq 'HASH') {
14814:             $idx->{$item} = $counters{$tail};
14815:         }
14816:         if (ref($jsarray) eq 'ARRAY') {
14817:             push(@{$jsarray->[$counters{$tail}]},$item);
14818:         }
14819:     }
14820:     return;
14821: }
14822: 
14823: =pod
14824: 
14825: =item * &extract_categories()
14826: 
14827: Used to generate breadcrumb trails for course categories.
14828: 
14829: Inputs:
14830: 
14831: categories (reference to hash of category definitions).
14832: 
14833: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14834:       categories and subcategories).
14835: 
14836: trails (reference to array of breacrumb trails for each category).
14837: 
14838: allitems (reference to hash - key is category key 
14839:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14840: 
14841: idx (reference to hash of counters used in Domain Coordinator interface for
14842:       editing Course Categories).
14843: 
14844: jsarray (reference to array of categories used to create Javascript arrays for
14845:          Domain Coordinator interface for editing Course Categories).
14846: 
14847: subcats (reference to hash of arrays containing all subcategories within each 
14848:          category, -recursive)
14849: 
14850: Returns: nothing
14851: 
14852: Side effects: populates trails and allitems hash references.
14853: 
14854: =cut
14855: 
14856: sub extract_categories {
14857:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14858:     if (ref($categories) eq 'HASH') {
14859:         &gather_categories($categories,$cats,$idx,$jsarray);
14860:         if (ref($cats->[0]) eq 'ARRAY') {
14861:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14862:                 my $name = $cats->[0][$i];
14863:                 my $item = &escape($name).'::0';
14864:                 my $trailstr;
14865:                 if ($name eq 'instcode') {
14866:                     $trailstr = &mt('Official courses (with institutional codes)');
14867:                 } elsif ($name eq 'communities') {
14868:                     $trailstr = &mt('Communities');
14869:                 } elsif ($name eq 'placement') {
14870:                     $trailstr = &mt('Placement Tests');
14871:                 } else {
14872:                     $trailstr = $name;
14873:                 }
14874:                 if ($allitems->{$item} eq '') {
14875:                     push(@{$trails},$trailstr);
14876:                     $allitems->{$item} = scalar(@{$trails})-1;
14877:                 }
14878:                 my @parents = ($name);
14879:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14880:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14881:                         my $category = $cats->[1]{$name}[$j];
14882:                         if (ref($subcats) eq 'HASH') {
14883:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14884:                         }
14885:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14886:                     }
14887:                 } else {
14888:                     if (ref($subcats) eq 'HASH') {
14889:                         $subcats->{$item} = [];
14890:                     }
14891:                 }
14892:             }
14893:         }
14894:     }
14895:     return;
14896: }
14897: 
14898: =pod
14899: 
14900: =item * &recurse_categories()
14901: 
14902: Recursively used to generate breadcrumb trails for course categories.
14903: 
14904: Inputs:
14905: 
14906: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14907:       categories and subcategories).
14908: 
14909: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14910: 
14911: category (current course category, for which breadcrumb trail is being generated).
14912: 
14913: trails (reference to array of breadcrumb trails for each category).
14914: 
14915: allitems (reference to hash - key is category key
14916:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14917: 
14918: parents (array containing containers directories for current category, 
14919:          back to top level). 
14920: 
14921: Returns: nothing
14922: 
14923: Side effects: populates trails and allitems hash references
14924: 
14925: =cut
14926: 
14927: sub recurse_categories {
14928:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14929:     my $shallower = $depth - 1;
14930:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14931:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14932:             my $name = $cats->[$depth]{$category}[$k];
14933:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14934:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14935:             if ($allitems->{$item} eq '') {
14936:                 push(@{$trails},$trailstr);
14937:                 $allitems->{$item} = scalar(@{$trails})-1;
14938:             }
14939:             my $deeper = $depth+1;
14940:             push(@{$parents},$category);
14941:             if (ref($subcats) eq 'HASH') {
14942:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14943:                 for (my $j=@{$parents}; $j>=0; $j--) {
14944:                     my $higher;
14945:                     if ($j > 0) {
14946:                         $higher = &escape($parents->[$j]).':'.
14947:                                   &escape($parents->[$j-1]).':'.$j;
14948:                     } else {
14949:                         $higher = &escape($parents->[$j]).'::'.$j;
14950:                     }
14951:                     push(@{$subcats->{$higher}},$subcat);
14952:                 }
14953:             }
14954:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14955:                                 $subcats);
14956:             pop(@{$parents});
14957:         }
14958:     } else {
14959:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14960:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14961:         if ($allitems->{$item} eq '') {
14962:             push(@{$trails},$trailstr);
14963:             $allitems->{$item} = scalar(@{$trails})-1;
14964:         }
14965:     }
14966:     return;
14967: }
14968: 
14969: =pod
14970: 
14971: =item * &assign_categories_table()
14972: 
14973: Create a datatable for display of hierarchical categories in a domain,
14974: with checkboxes to allow a course to be categorized. 
14975: 
14976: Inputs:
14977: 
14978: cathash - reference to hash of categories defined for the domain (from
14979:           configuration.db)
14980: 
14981: currcat - scalar with an & separated list of categories assigned to a course. 
14982: 
14983: type    - scalar contains course type (Course or Community).
14984: 
14985: disabled - scalar (optional) contains disabled="disabled" if input elements are
14986:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14987: 
14988: Returns: $output (markup to be displayed) 
14989: 
14990: =cut
14991: 
14992: sub assign_categories_table {
14993:     my ($cathash,$currcat,$type,$disabled) = @_;
14994:     my $output;
14995:     if (ref($cathash) eq 'HASH') {
14996:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14997:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14998:         $maxdepth = scalar(@cats);
14999:         if (@cats > 0) {
15000:             my $itemcount = 0;
15001:             if (ref($cats[0]) eq 'ARRAY') {
15002:                 my @currcategories;
15003:                 if ($currcat ne '') {
15004:                     @currcategories = split('&',$currcat);
15005:                 }
15006:                 my $table;
15007:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15008:                     my $parent = $cats[0][$i];
15009:                     next if ($parent eq 'instcode');
15010:                     if ($type eq 'Community') {
15011:                         next unless ($parent eq 'communities');
15012:                     } elsif ($type eq 'Placement') {
15013:                         next unless ($parent eq 'placement');
15014:                     } else {
15015:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15016:                     }
15017:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15018:                     my $item = &escape($parent).'::0';
15019:                     my $checked = '';
15020:                     if (@currcategories > 0) {
15021:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15022:                             $checked = ' checked="checked"';
15023:                         }
15024:                     }
15025:                     my $parent_title = $parent;
15026:                     if ($parent eq 'communities') {
15027:                         $parent_title = &mt('Communities');
15028:                     } elsif ($parent eq 'placement') {
15029:                         $parent_title = &mt('Placement Tests');
15030:                     }
15031:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15032:                               '<input type="checkbox" name="usecategory" value="'.
15033:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15034:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15035:                     my $depth = 1;
15036:                     push(@path,$parent);
15037:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15038:                     pop(@path);
15039:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15040:                     $itemcount ++;
15041:                 }
15042:                 if ($itemcount) {
15043:                     $output = &Apache::loncommon::start_data_table().
15044:                               $table.
15045:                               &Apache::loncommon::end_data_table();
15046:                 }
15047:             }
15048:         }
15049:     }
15050:     return $output;
15051: }
15052: 
15053: =pod
15054: 
15055: =item * &assign_category_rows()
15056: 
15057: Create a datatable row for display of nested categories in a domain,
15058: with checkboxes to allow a course to be categorized,called recursively.
15059: 
15060: Inputs:
15061: 
15062: itemcount - track row number for alternating colors
15063: 
15064: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15065:       categories and subcategories.
15066: 
15067: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15068: 
15069: parent - parent of current category item
15070: 
15071: path - Array containing all categories back up through the hierarchy from the
15072:        current category to the top level.
15073: 
15074: currcategories - reference to array of current categories assigned to the course
15075: 
15076: disabled - scalar (optional) contains disabled="disabled" if input elements are
15077:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15078: 
15079: Returns: $output (markup to be displayed).
15080: 
15081: =cut
15082: 
15083: sub assign_category_rows {
15084:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15085:     my ($text,$name,$item,$chgstr);
15086:     if (ref($cats) eq 'ARRAY') {
15087:         my $maxdepth = scalar(@{$cats});
15088:         if (ref($cats->[$depth]) eq 'HASH') {
15089:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15090:                 my $numchildren = @{$cats->[$depth]{$parent}};
15091:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15092:                 $text .= '<td><table class="LC_data_table">';
15093:                 for (my $j=0; $j<$numchildren; $j++) {
15094:                     $name = $cats->[$depth]{$parent}[$j];
15095:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15096:                     my $deeper = $depth+1;
15097:                     my $checked = '';
15098:                     if (ref($currcategories) eq 'ARRAY') {
15099:                         if (@{$currcategories} > 0) {
15100:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15101:                                 $checked = ' checked="checked"';
15102:                             }
15103:                         }
15104:                     }
15105:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15106:                              '<input type="checkbox" name="usecategory" value="'.
15107:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15108:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15109:                              '</td><td>';
15110:                     if (ref($path) eq 'ARRAY') {
15111:                         push(@{$path},$name);
15112:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15113:                         pop(@{$path});
15114:                     }
15115:                     $text .= '</td></tr>';
15116:                 }
15117:                 $text .= '</table></td>';
15118:             }
15119:         }
15120:     }
15121:     return $text;
15122: }
15123: 
15124: =pod
15125: 
15126: =back
15127: 
15128: =cut
15129: 
15130: ############################################################
15131: ############################################################
15132: 
15133: 
15134: sub commit_customrole {
15135:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15136:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15137:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15138:                          ($end?', ending '.localtime($end):'').': <b>'.
15139:               &Apache::lonnet::assigncustomrole(
15140:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15141:                  '</b><br />';
15142:     return $output;
15143: }
15144: 
15145: sub commit_standardrole {
15146:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15147:     my ($output,$logmsg,$linefeed);
15148:     if ($context eq 'auto') {
15149:         $linefeed = "\n";
15150:     } else {
15151:         $linefeed = "<br />\n";
15152:     }  
15153:     if ($three eq 'st') {
15154:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15155:                                          $one,$two,$sec,$context,$credits);
15156:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15157:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15158:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15159:         } else {
15160:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15161:                ($start?', '.&mt('starting').' '.localtime($start):'').
15162:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15163:             if ($context eq 'auto') {
15164:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15165:             } else {
15166:                $output .= '<b>'.$result.'</b>'.$linefeed.
15167:                &mt('Add to classlist').': <b>ok</b>';
15168:             }
15169:             $output .= $linefeed;
15170:         }
15171:     } else {
15172:         $output = &mt('Assigning').' '.$three.' in '.$url.
15173:                ($start?', '.&mt('starting').' '.localtime($start):'').
15174:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15175:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15176:         if ($context eq 'auto') {
15177:             $output .= $result.$linefeed;
15178:         } else {
15179:             $output .= '<b>'.$result.'</b>'.$linefeed;
15180:         }
15181:     }
15182:     return $output;
15183: }
15184: 
15185: sub commit_studentrole {
15186:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15187:         $credits) = @_;
15188:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15189:     if ($context eq 'auto') {
15190:         $linefeed = "\n";
15191:     } else {
15192:         $linefeed = '<br />'."\n";
15193:     }
15194:     if (defined($one) && defined($two)) {
15195:         my $cid=$one.'_'.$two;
15196:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15197:         my $secchange = 0;
15198:         my $expire_role_result;
15199:         my $modify_section_result;
15200:         if ($oldsec ne '-1') { 
15201:             if ($oldsec ne $sec) {
15202:                 $secchange = 1;
15203:                 my $now = time;
15204:                 my $uurl='/'.$cid;
15205:                 $uurl=~s/\_/\//g;
15206:                 if ($oldsec) {
15207:                     $uurl.='/'.$oldsec;
15208:                 }
15209:                 $oldsecurl = $uurl;
15210:                 $expire_role_result = 
15211:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15212:                 if ($env{'request.course.sec'} ne '') { 
15213:                     if ($expire_role_result eq 'refused') {
15214:                         my @roles = ('st');
15215:                         my @statuses = ('previous');
15216:                         my @roledoms = ($one);
15217:                         my $withsec = 1;
15218:                         my %roleshash = 
15219:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15220:                                               \@statuses,\@roles,\@roledoms,$withsec);
15221:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15222:                             my ($oldstart,$oldend) = 
15223:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15224:                             if ($oldend > 0 && $oldend <= $now) {
15225:                                 $expire_role_result = 'ok';
15226:                             }
15227:                         }
15228:                     }
15229:                 }
15230:                 $result = $expire_role_result;
15231:             }
15232:         }
15233:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15234:             $modify_section_result = 
15235:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15236:                                                            undef,undef,undef,$sec,
15237:                                                            $end,$start,'','',$cid,
15238:                                                            '',$context,$credits);
15239:             if ($modify_section_result =~ /^ok/) {
15240:                 if ($secchange == 1) {
15241:                     if ($sec eq '') {
15242:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15243:                     } else {
15244:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15245:                     }
15246:                 } elsif ($oldsec eq '-1') {
15247:                     if ($sec eq '') {
15248:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15249:                     } else {
15250:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15251:                     }
15252:                 } else {
15253:                     if ($sec eq '') {
15254:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15255:                     } else {
15256:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15257:                     }
15258:                 }
15259:             } else {
15260:                 if ($secchange) { 
15261:                     $$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;
15262:                 } else {
15263:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15264:                 }
15265:             }
15266:             $result = $modify_section_result;
15267:         } elsif ($secchange == 1) {
15268:             if ($oldsec eq '') {
15269:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15270:             } else {
15271:                 $$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;
15272:             }
15273:             if ($expire_role_result eq 'refused') {
15274:                 my $newsecurl = '/'.$cid;
15275:                 $newsecurl =~ s/\_/\//g;
15276:                 if ($sec ne '') {
15277:                     $newsecurl.='/'.$sec;
15278:                 }
15279:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15280:                     if ($sec eq '') {
15281:                         $$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;
15282:                     } else {
15283:                         $$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;
15284:                     }
15285:                 }
15286:             }
15287:         }
15288:     } else {
15289:         $$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;
15290:         $result = "error: incomplete course id\n";
15291:     }
15292:     return $result;
15293: }
15294: 
15295: sub show_role_extent {
15296:     my ($scope,$context,$role) = @_;
15297:     $scope =~ s{^/}{};
15298:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15299:     push(@courseroles,'co');
15300:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15301:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15302:         $scope =~ s{/}{_};
15303:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15304:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15305:         my ($audom,$auname) = split(/\//,$scope);
15306:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15307:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15308:     } else {
15309:         $scope =~ s{/$}{};
15310:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15311:                    &Apache::lonnet::domain($scope,'description').'</span>');
15312:     }
15313: }
15314: 
15315: ############################################################
15316: ############################################################
15317: 
15318: sub check_clone {
15319:     my ($args,$linefeed) = @_;
15320:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15321:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15322:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15323:     my $clonemsg;
15324:     my $can_clone = 0;
15325:     my $lctype = lc($args->{'crstype'});
15326:     if ($lctype ne 'community') {
15327:         $lctype = 'course';
15328:     }
15329:     if ($clonehome eq 'no_host') {
15330:         if ($args->{'crstype'} eq 'Community') {
15331:             $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'});
15332:         } else {
15333:             $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'});
15334:         }     
15335:     } else {
15336: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15337:         if ($args->{'crstype'} eq 'Community') {
15338:             if ($clonedesc{'type'} ne 'Community') {
15339:                 $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'});
15340:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15341:             }
15342:         }
15343: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15344:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15345: 	    $can_clone = 1;
15346: 	} else {
15347: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15348: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15349:             if ($clonehash{'cloners'} eq '') {
15350:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15351:                 if ($domdefs{'canclone'}) {
15352:                     unless ($domdefs{'canclone'} eq 'none') {
15353:                         if ($domdefs{'canclone'} eq 'domain') {
15354:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15355:                                 $can_clone = 1;
15356:                             }
15357:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15358:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15359:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15360:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15361:                                 $can_clone = 1;
15362:                             }
15363:                         }
15364:                     }
15365:                 }
15366:             } else {
15367: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15368:                 if (grep(/^\*$/,@cloners)) {
15369:                     $can_clone = 1;
15370:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15371:                     $can_clone = 1;
15372:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15373:                     $can_clone = 1;
15374:                 }
15375:                 unless ($can_clone) {
15376:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15377:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15378:                         my (%gotdomdefaults,%gotcodedefaults);
15379:                         foreach my $cloner (@cloners) {
15380:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15381:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15382:                                 my (%codedefaults,@code_order);
15383:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15384:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15385:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15386:                                     }
15387:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15388:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15389:                                     }
15390:                                 } else {
15391:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15392:                                                                             \%codedefaults,
15393:                                                                             \@code_order);
15394:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15395:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15396:                                 }
15397:                                 if (@code_order > 0) {
15398:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15399:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15400:                                                                                 $args->{'crscode'})) {
15401:                                         $can_clone = 1;
15402:                                         last;
15403:                                     }
15404:                                 }
15405:                             }
15406:                         }
15407:                     }
15408:                 }
15409:             }
15410:             unless ($can_clone) {
15411:                 my $ccrole = 'cc';
15412:                 if ($args->{'crstype'} eq 'Community') {
15413:                     $ccrole = 'co';
15414:                 }
15415: 	        my %roleshash =
15416: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
15417: 					          $args->{'ccdomain'},
15418:                                                   'userroles',['active'],[$ccrole],
15419: 					          [$args->{'clonedomain'}]);
15420: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15421:                     $can_clone = 1;
15422:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15423:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15424:                     $can_clone = 1;
15425:                 }
15426:             }
15427:             unless ($can_clone) {
15428:                 if ($args->{'crstype'} eq 'Community') {
15429:                     $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'});
15430:                 } else {
15431:                     $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'});
15432:                 }
15433: 	    }
15434:         }
15435:     }
15436:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15437: }
15438: 
15439: sub construct_course {
15440:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15441:         $cnum,$category,$coderef) = @_;
15442:     my $outcome;
15443:     my $linefeed =  '<br />'."\n";
15444:     if ($context eq 'auto') {
15445:         $linefeed = "\n";
15446:     }
15447: 
15448: #
15449: # Are we cloning?
15450: #
15451:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15452:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15453: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15454: 	if ($context ne 'auto') {
15455:             if ($clonemsg ne '') {
15456: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15457:             }
15458: 	}
15459: 	$outcome .= $clonemsg.$linefeed;
15460: 
15461:         if (!$can_clone) {
15462: 	    return (0,$outcome);
15463: 	}
15464:     }
15465: 
15466: #
15467: # Open course
15468: #
15469:     my $showncrstype;
15470:     if ($args->{'crstype'} eq 'Placement') {
15471:         $showncrstype = 'placement test'; 
15472:     } else {  
15473:         $showncrstype = lc($args->{'crstype'});
15474:     }
15475:     my %cenv=();
15476:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15477:                                              $args->{'cdescr'},
15478:                                              $args->{'curl'},
15479:                                              $args->{'course_home'},
15480:                                              $args->{'nonstandard'},
15481:                                              $args->{'crscode'},
15482:                                              $args->{'ccuname'}.':'.
15483:                                              $args->{'ccdomain'},
15484:                                              $args->{'crstype'},
15485:                                              $cnum,$context,$category);
15486: 
15487:     # Note: The testing routines depend on this being output; see 
15488:     # Utils::Course. This needs to at least be output as a comment
15489:     # if anyone ever decides to not show this, and Utils::Course::new
15490:     # will need to be suitably modified.
15491:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15492:     if ($$courseid =~ /^error:/) {
15493:         return (0,$outcome);
15494:     }
15495: 
15496: #
15497: # Check if created correctly
15498: #
15499:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15500:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15501:     if ($crsuhome eq 'no_host') {
15502:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15503:         return (0,$outcome);
15504:     }
15505:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15506: 
15507: #
15508: # Do the cloning
15509: #   
15510:     if ($can_clone && $cloneid) {
15511: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15512: 	if ($context ne 'auto') {
15513: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15514: 	}
15515: 	$outcome .= $clonemsg.$linefeed;
15516: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15517: # Copy all files
15518: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15519: # Restore URL
15520: 	$cenv{'url'}=$oldcenv{'url'};
15521: # Restore title
15522: 	$cenv{'description'}=$oldcenv{'description'};
15523: # Restore creation date, creator and creation context.
15524:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15525:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15526:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15527: # Mark as cloned
15528: 	$cenv{'clonedfrom'}=$cloneid;
15529: # Need to clone grading mode
15530:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15531:         $cenv{'grading'}=$newenv{'grading'};
15532: # Do not clone these environment entries
15533:         &Apache::lonnet::del('environment',
15534:                   ['default_enrollment_start_date',
15535:                    'default_enrollment_end_date',
15536:                    'question.email',
15537:                    'policy.email',
15538:                    'comment.email',
15539:                    'pch.users.denied',
15540:                    'plc.users.denied',
15541:                    'hidefromcat',
15542:                    'checkforpriv',
15543:                    'categories',
15544:                    'internal.uniquecode'],
15545:                    $$crsudom,$$crsunum);
15546:         if ($args->{'textbook'}) {
15547:             $cenv{'internal.textbook'} = $args->{'textbook'};
15548:         }
15549:     }
15550: 
15551: #
15552: # Set environment (will override cloned, if existing)
15553: #
15554:     my @sections = ();
15555:     my @xlists = ();
15556:     if ($args->{'crstype'}) {
15557:         $cenv{'type'}=$args->{'crstype'};
15558:     }
15559:     if ($args->{'crsid'}) {
15560:         $cenv{'courseid'}=$args->{'crsid'};
15561:     }
15562:     if ($args->{'crscode'}) {
15563:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15564:     }
15565:     if ($args->{'crsquota'} ne '') {
15566:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15567:     } else {
15568:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15569:     }
15570:     if ($args->{'ccuname'}) {
15571:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15572:                                         ':'.$args->{'ccdomain'};
15573:     } else {
15574:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15575:     }
15576:     if ($args->{'defaultcredits'}) {
15577:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15578:     }
15579:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15580:     if ($args->{'crssections'}) {
15581:         $cenv{'internal.sectionnums'} = '';
15582:         if ($args->{'crssections'} =~ m/,/) {
15583:             @sections = split/,/,$args->{'crssections'};
15584:         } else {
15585:             $sections[0] = $args->{'crssections'};
15586:         }
15587:         if (@sections > 0) {
15588:             foreach my $item (@sections) {
15589:                 my ($sec,$gp) = split/:/,$item;
15590:                 my $class = $args->{'crscode'}.$sec;
15591:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15592:                 $cenv{'internal.sectionnums'} .= $item.',';
15593:                 unless ($addcheck eq 'ok') {
15594:                     push(@badclasses,$class);
15595:                 }
15596:             }
15597:             $cenv{'internal.sectionnums'} =~ s/,$//;
15598:         }
15599:     }
15600: # do not hide course coordinator from staff listing, 
15601: # even if privileged
15602:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15603: # add course coordinator's domain to domains to check for privileged users
15604: # if different to course domain
15605:     if ($$crsudom ne $args->{'ccdomain'}) {
15606:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15607:     }
15608: # add crosslistings
15609:     if ($args->{'crsxlist'}) {
15610:         $cenv{'internal.crosslistings'}='';
15611:         if ($args->{'crsxlist'} =~ m/,/) {
15612:             @xlists = split/,/,$args->{'crsxlist'};
15613:         } else {
15614:             $xlists[0] = $args->{'crsxlist'};
15615:         }
15616:         if (@xlists > 0) {
15617:             foreach my $item (@xlists) {
15618:                 my ($xl,$gp) = split/:/,$item;
15619:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15620:                 $cenv{'internal.crosslistings'} .= $item.',';
15621:                 unless ($addcheck eq 'ok') {
15622:                     push(@badclasses,$xl);
15623:                 }
15624:             }
15625:             $cenv{'internal.crosslistings'} =~ s/,$//;
15626:         }
15627:     }
15628:     if ($args->{'autoadds'}) {
15629:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15630:     }
15631:     if ($args->{'autodrops'}) {
15632:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15633:     }
15634: # check for notification of enrollment changes
15635:     my @notified = ();
15636:     if ($args->{'notify_owner'}) {
15637:         if ($args->{'ccuname'} ne '') {
15638:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15639:         }
15640:     }
15641:     if ($args->{'notify_dc'}) {
15642:         if ($uname ne '') { 
15643:             push(@notified,$uname.':'.$udom);
15644:         }
15645:     }
15646:     if (@notified > 0) {
15647:         my $notifylist;
15648:         if (@notified > 1) {
15649:             $notifylist = join(',',@notified);
15650:         } else {
15651:             $notifylist = $notified[0];
15652:         }
15653:         $cenv{'internal.notifylist'} = $notifylist;
15654:     }
15655:     if (@badclasses > 0) {
15656:         my %lt=&Apache::lonlocal::texthash(
15657:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15658:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15659:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15660:         );
15661:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15662:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
15663:         if ($context eq 'auto') {
15664:             $outcome .= $badclass_msg.$linefeed;
15665:         } else {
15666:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15667:         }
15668:         foreach my $item (@badclasses) {
15669:             if ($context eq 'auto') {
15670:                 $outcome .= " - $item\n";
15671:             } else {
15672:                 $outcome .= "<li>$item</li>\n";
15673:             }
15674:         }
15675:         if ($context eq 'auto') {
15676:             $outcome .= $linefeed;
15677:         } else {
15678:             $outcome .= "</ul><br /><br /></div>\n";
15679:         } 
15680:     }
15681:     if ($args->{'no_end_date'}) {
15682:         $args->{'endaccess'} = 0;
15683:     }
15684:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15685:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15686:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15687:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15688:     if ($args->{'showphotos'}) {
15689:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15690:     }
15691:     $cenv{'internal.authtype'} = $args->{'authtype'};
15692:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15693:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15694:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15695:             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'); 
15696:             if ($context eq 'auto') {
15697:                 $outcome .= $krb_msg;
15698:             } else {
15699:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15700:             }
15701:             $outcome .= $linefeed;
15702:         }
15703:     }
15704:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15705:        if ($args->{'setpolicy'}) {
15706:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15707:        }
15708:        if ($args->{'setcontent'}) {
15709:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15710:        }
15711:        if ($args->{'setcomment'}) {
15712:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15713:        }
15714:     }
15715:     if ($args->{'reshome'}) {
15716: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15717: 	$cenv{'reshome'}=~s/\/+$/\//;
15718:     }
15719: #
15720: # course has keyed access
15721: #
15722:     if ($args->{'setkeys'}) {
15723:        $cenv{'keyaccess'}='yes';
15724:     }
15725: # if specified, key authority is not course, but user
15726: # only active if keyaccess is yes
15727:     if ($args->{'keyauth'}) {
15728: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15729: 	$user = &LONCAPA::clean_username($user);
15730: 	$domain = &LONCAPA::clean_username($domain);
15731: 	if ($user ne '' && $domain ne '') {
15732: 	    $cenv{'keyauth'}=$user.':'.$domain;
15733: 	}
15734:     }
15735: 
15736: #
15737: #  generate and store uniquecode (available to course requester), if course should have one.
15738: #
15739:     if ($args->{'uniquecode'}) {
15740:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15741:         if ($code) {
15742:             $cenv{'internal.uniquecode'} = $code;
15743:             my %crsinfo =
15744:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15745:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15746:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15747:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15748:             } 
15749:             if (ref($coderef)) {
15750:                 $$coderef = $code;
15751:             }
15752:         }
15753:     }
15754: 
15755:     if ($args->{'disresdis'}) {
15756:         $cenv{'pch.roles.denied'}='st';
15757:     }
15758:     if ($args->{'disablechat'}) {
15759:         $cenv{'plc.roles.denied'}='st';
15760:     }
15761: 
15762:     # Record we've not yet viewed the Course Initialization Helper for this 
15763:     # course
15764:     $cenv{'course.helper.not.run'} = 1;
15765:     #
15766:     # Use new Randomseed
15767:     #
15768:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15769:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15770:     #
15771:     # The encryption code and receipt prefix for this course
15772:     #
15773:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15774:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15775:     #
15776:     # By default, use standard grading
15777:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15778: 
15779:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15780:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15781: #
15782: # Open all assignments
15783: #
15784:     if ($args->{'openall'}) {
15785:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15786:        my %storecontent = ($storeunder         => time,
15787:                            $storeunder.'.type' => 'date_start');
15788:        
15789:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15790:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15791:    }
15792: #
15793: # Set first page
15794: #
15795:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15796: 	    || ($cloneid)) {
15797: 	use LONCAPA::map;
15798: 	$outcome .= &mt('Setting first resource').': ';
15799: 
15800: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15801:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15802: 
15803:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15804:         my $title; my $url;
15805:         if ($args->{'firstres'} eq 'syl') {
15806: 	    $title=&mt('Syllabus');
15807:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15808:         } else {
15809:             $title=&mt('Table of Contents');
15810:             $url='/adm/navmaps';
15811:         }
15812: 
15813:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15814: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15815: 
15816: 	if ($errtext) { $fatal=2; }
15817:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15818:     }
15819: 
15820: # 
15821: # Set params for Placement Tests
15822: #
15823:     if ($args->{'crstype'} eq 'Placement') {
15824:        my %storecontent; 
15825:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
15826:        my %defaults = (
15827:                         buttonshide   => { value => 'yes',
15828:                                            type => 'string_yesno',},
15829:                         type          => { value => 'randomizetry',
15830:                                            type  => 'string_questiontype',},
15831:                         maxtries      => { value => 1,
15832:                                            type => 'int_pos',},
15833:                         problemstatus => { value => 'no',
15834:                                            type  => 'string_problemstatus',},
15835:                       );
15836:        foreach my $key (keys(%defaults)) {
15837:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
15838:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
15839:        }
15840:        &Apache::lonnet::cput
15841:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
15842:     }
15843: 
15844:     return (1,$outcome);
15845: }
15846: 
15847: sub make_unique_code {
15848:     my ($cdom,$cnum) = @_;
15849:     # get lock on uniquecodes db
15850:     my $lockhash = {
15851:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15852:                                                   ':'.$env{'user.domain'},
15853:                    };
15854:     my $tries = 0;
15855:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15856:     my ($code,$error);
15857:   
15858:     while (($gotlock ne 'ok') && ($tries<3)) {
15859:         $tries ++;
15860:         sleep 1;
15861:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15862:     }
15863:     if ($gotlock eq 'ok') {
15864:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15865:         my $gotcode;
15866:         my $attempts = 0;
15867:         while ((!$gotcode) && ($attempts < 100)) {
15868:             $code = &generate_code();
15869:             if (!exists($currcodes{$code})) {
15870:                 $gotcode = 1;
15871:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15872:                     $error = 'nostore';
15873:                 }
15874:             }
15875:             $attempts ++;
15876:         }
15877:         my @del_lock = ($cnum."\0".'uniquecodes');
15878:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15879:     } else {
15880:         $error = 'nolock';
15881:     }
15882:     return ($code,$error);
15883: }
15884: 
15885: sub generate_code {
15886:     my $code;
15887:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15888:     for (my $i=0; $i<6; $i++) {
15889:         my $lettnum = int (rand 2);
15890:         my $item = '';
15891:         if ($lettnum) {
15892:             $item = $letts[int( rand(18) )];
15893:         } else {
15894:             $item = 1+int( rand(8) );
15895:         }
15896:         $code .= $item;
15897:     }
15898:     return $code;
15899: }
15900: 
15901: ############################################################
15902: ############################################################
15903: 
15904: # Community, Course and Placement Test
15905: sub course_type {
15906:     my ($cid) = @_;
15907:     if (!defined($cid)) {
15908:         $cid = $env{'request.course.id'};
15909:     }
15910:     if (defined($env{'course.'.$cid.'.type'})) {
15911:         return $env{'course.'.$cid.'.type'};
15912:     } else {
15913:         return 'Course';
15914:     }
15915: }
15916: 
15917: sub group_term {
15918:     my $crstype = &course_type();
15919:     my %names = (
15920:                   'Course' => 'group',
15921:                   'Community' => 'group',
15922:                   'Placement' => 'group',
15923:                 );
15924:     return $names{$crstype};
15925: }
15926: 
15927: sub course_types {
15928:     my @types = ('official','unofficial','community','textbook','placement');
15929:     my %typename = (
15930:                          official   => 'Official course',
15931:                          unofficial => 'Unofficial course',
15932:                          community  => 'Community',
15933:                          textbook   => 'Textbook course',
15934:                          placement  => 'Placement test',
15935:                    );
15936:     return (\@types,\%typename);
15937: }
15938: 
15939: sub icon {
15940:     my ($file)=@_;
15941:     my $curfext = lc((split(/\./,$file))[-1]);
15942:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15943:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15944:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15945: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15946: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15947: 	            $curfext.".gif") {
15948: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15949: 		$curfext.".gif";
15950: 	}
15951:     }
15952:     return &lonhttpdurl($iconname);
15953: } 
15954: 
15955: sub lonhttpdurl {
15956: #
15957: # Had been used for "small fry" static images on separate port 8080.
15958: # Modify here if lightweight http functionality desired again.
15959: # Currently eliminated due to increasing firewall issues.
15960: #
15961:     my ($url)=@_;
15962:     return $url;
15963: }
15964: 
15965: sub connection_aborted {
15966:     my ($r)=@_;
15967:     $r->print(" ");$r->rflush();
15968:     my $c = $r->connection;
15969:     return $c->aborted();
15970: }
15971: 
15972: #    Escapes strings that may have embedded 's that will be put into
15973: #    strings as 'strings'.
15974: sub escape_single {
15975:     my ($input) = @_;
15976:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15977:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15978:     return $input;
15979: }
15980: 
15981: #  Same as escape_single, but escape's "'s  This 
15982: #  can be used for  "strings"
15983: sub escape_double {
15984:     my ($input) = @_;
15985:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15986:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15987:     return $input;
15988: }
15989:  
15990: #   Escapes the last element of a full URL.
15991: sub escape_url {
15992:     my ($url)   = @_;
15993:     my @urlslices = split(/\//, $url,-1);
15994:     my $lastitem = &escape(pop(@urlslices));
15995:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15996: }
15997: 
15998: sub compare_arrays {
15999:     my ($arrayref1,$arrayref2) = @_;
16000:     my (@difference,%count);
16001:     @difference = ();
16002:     %count = ();
16003:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16004:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16005:         foreach my $element (keys(%count)) {
16006:             if ($count{$element} == 1) {
16007:                 push(@difference,$element);
16008:             }
16009:         }
16010:     }
16011:     return @difference;
16012: }
16013: 
16014: # -------------------------------------------------------- Initialize user login
16015: sub init_user_environment {
16016:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16017:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16018: 
16019:     my $public=($username eq 'public' && $domain eq 'public');
16020: 
16021:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16022:     my $now=time;
16023: 
16024:     if ($public) {
16025: 	my $max_public=100;
16026: 	my $oldest;
16027: 	my $oldest_time=0;
16028: 	for(my $next=1;$next<=$max_public;$next++) {
16029: 	    if (-e $lonids."/publicuser_$next.id") {
16030: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16031: 		if ($mtime<$oldest_time || !$oldest_time) {
16032: 		    $oldest_time=$mtime;
16033: 		    $oldest=$next;
16034: 		}
16035: 	    } else {
16036: 		$cookie="publicuser_$next";
16037: 		last;
16038: 	    }
16039: 	}
16040: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16041:     } else {
16042: 	# See if old ID present, if so, remove if this isn't a robot,
16043: 	# killing any existing non-robot sessions
16044: 	if (!$args->{'robot'}) {
16045: 	    opendir(DIR,$lonids);
16046: 	    while ($filename=readdir(DIR)) {
16047: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16048: 		    unlink($lonids.'/'.$filename);
16049: 		}
16050: 	    }
16051: 	    closedir(DIR);
16052: # If there is a undeleted lockfile for the user's paste buffer remove it.
16053:             my $namespace = 'nohist_courseeditor';
16054:             my $lockingkey = 'paste'."\0".'locked_num';
16055:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16056:                                                 $domain,$username);
16057:             if (exists($lockhash{$lockingkey})) {
16058:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16059:                 unless ($delresult eq 'ok') {
16060:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16061:                 }
16062:             }
16063: 	}
16064: # Give them a new cookie
16065: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16066: 		                   : $now.$$.int(rand(10000)));
16067: 	$cookie="$username\_$id\_$domain\_$authhost";
16068:     
16069: # Initialize roles
16070: 
16071: 	($userroles,$firstaccenv,$timerintenv) = 
16072:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16073:     }
16074: # ------------------------------------ Check browser type and MathML capability
16075: 
16076:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16077:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16078: 
16079: # ------------------------------------------------------------- Get environment
16080: 
16081:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16082:     my ($tmp) = keys(%userenv);
16083:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16084: 	undef(%userenv);
16085:     }
16086:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16087: 	$form->{'interface'}=$userenv{'interface'};
16088:     }
16089:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16090: 
16091: # --------------- Do not trust query string to be put directly into environment
16092:     foreach my $option ('interface','localpath','localres') {
16093:         $form->{$option}=~s/[\n\r\=]//gs;
16094:     }
16095: # --------------------------------------------------------- Write first profile
16096: 
16097:     {
16098: 	my %initial_env = 
16099: 	    ("user.name"          => $username,
16100: 	     "user.domain"        => $domain,
16101: 	     "user.home"          => $authhost,
16102: 	     "browser.type"       => $clientbrowser,
16103: 	     "browser.version"    => $clientversion,
16104: 	     "browser.mathml"     => $clientmathml,
16105: 	     "browser.unicode"    => $clientunicode,
16106: 	     "browser.os"         => $clientos,
16107:              "browser.mobile"     => $clientmobile,
16108:              "browser.info"       => $clientinfo,
16109:              "browser.osversion"  => $clientosversion,
16110: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16111: 	     "request.course.fn"  => '',
16112: 	     "request.course.uri" => '',
16113: 	     "request.course.sec" => '',
16114: 	     "request.role"       => 'cm',
16115: 	     "request.role.adv"   => $env{'user.adv'},
16116: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
16117: 
16118:         if ($form->{'localpath'}) {
16119: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16120: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16121:         }
16122: 	
16123: 	if ($form->{'interface'}) {
16124: 	    $form->{'interface'}=~s/\W//gs;
16125: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16126: 	    $env{'browser.interface'}=$form->{'interface'};
16127: 	}
16128: 
16129:         if ($form->{'iptoken'}) {
16130:             my $lonhost = $r->dir_config('lonHostID');
16131:             $initial_env{"user.noloadbalance"} = $lonhost;
16132:             $env{'user.noloadbalance'} = $lonhost;
16133:         }
16134: 
16135:         if ($form->{'noloadbalance'}) {
16136:             my @hosts = &Apache::lonnet::current_machine_ids();
16137:             my $hosthere = $form->{'noloadbalance'};
16138:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16139:                 $initial_env{"user.noloadbalance"} = $hosthere;
16140:                 $env{'user.noloadbalance'} = $hosthere;
16141:             }
16142:         }
16143: 
16144:         unless ($domain eq 'public') {
16145:             my %is_adv = ( is_adv => $env{'user.adv'} );
16146:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16147: 
16148:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16149:                 $userenv{'availabletools.'.$tool} = 
16150:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16151:                                                       undef,\%userenv,\%domdef,\%is_adv);
16152:             }
16153: 
16154:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
16155:                 $userenv{'canrequest.'.$crstype} =
16156:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16157:                                                       'reload','requestcourses',
16158:                                                       \%userenv,\%domdef,\%is_adv);
16159:             }
16160: 
16161:             $userenv{'canrequest.author'} =
16162:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16163:                                                   'reload','requestauthor',
16164:                                                   \%userenv,\%domdef,\%is_adv);
16165:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16166:                                                  $domain,$username);
16167:             my $reqstatus = $reqauthor{'author_status'};
16168:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
16169:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16170:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16171:                                                       $reqauthor{'author'}{'timestamp'};
16172:                 }
16173:             }
16174:         }
16175: 
16176: 	$env{'user.environment'} = "$lonids/$cookie.id";
16177: 
16178: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16179: 		 &GDBM_WRCREAT(),0640)) {
16180: 	    &_add_to_env(\%disk_env,\%initial_env);
16181: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16182: 	    &_add_to_env(\%disk_env,$userroles);
16183:             if (ref($firstaccenv) eq 'HASH') {
16184:                 &_add_to_env(\%disk_env,$firstaccenv);
16185:             }
16186:             if (ref($timerintenv) eq 'HASH') {
16187:                 &_add_to_env(\%disk_env,$timerintenv);
16188:             }
16189: 	    if (ref($args->{'extra_env'})) {
16190: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16191: 	    }
16192: 	    untie(%disk_env);
16193: 	} else {
16194: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16195: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16196: 	    return 'error: '.$!;
16197: 	}
16198:     }
16199:     $env{'request.role'}='cm';
16200:     $env{'request.role.adv'}=$env{'user.adv'};
16201:     $env{'browser.type'}=$clientbrowser;
16202: 
16203:     return $cookie;
16204: 
16205: }
16206: 
16207: sub _add_to_env {
16208:     my ($idf,$env_data,$prefix) = @_;
16209:     if (ref($env_data) eq 'HASH') {
16210:         while (my ($key,$value) = each(%$env_data)) {
16211: 	    $idf->{$prefix.$key} = $value;
16212: 	    $env{$prefix.$key}   = $value;
16213:         }
16214:     }
16215: }
16216: 
16217: # --- Get the symbolic name of a problem and the url
16218: sub get_symb {
16219:     my ($request,$silent) = @_;
16220:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16221:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16222:     if ($symb eq '') {
16223:         if (!$silent) {
16224:             if (ref($request)) { 
16225:                 $request->print("Unable to handle ambiguous references:$url:.");
16226:             }
16227:             return ();
16228:         }
16229:     }
16230:     &Apache::lonenc::check_decrypt(\$symb);
16231:     return ($symb);
16232: }
16233: 
16234: # --------------------------------------------------------------Get annotation
16235: 
16236: sub get_annotation {
16237:     my ($symb,$enc) = @_;
16238: 
16239:     my $key = $symb;
16240:     if (!$enc) {
16241:         $key =
16242:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16243:     }
16244:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16245:     return $annotation{$key};
16246: }
16247: 
16248: sub clean_symb {
16249:     my ($symb,$delete_enc) = @_;
16250: 
16251:     &Apache::lonenc::check_decrypt(\$symb);
16252:     my $enc = $env{'request.enc'};
16253:     if ($delete_enc) {
16254:         delete($env{'request.enc'});
16255:     }
16256: 
16257:     return ($symb,$enc);
16258: }
16259: 
16260: ############################################################
16261: ############################################################
16262: 
16263: =pod
16264: 
16265: =head1 Routines for building display used to search for courses
16266: 
16267: 
16268: =over 4
16269: 
16270: =item * &build_filters()
16271: 
16272: Create markup for a table used to set filters to use when selecting
16273: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16274: and quotacheck.pl
16275: 
16276: 
16277: Inputs:
16278: 
16279: filterlist - anonymous array of fields to include as potential filters 
16280: 
16281: crstype - course type
16282: 
16283: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16284:               to pop-open a course selector (will contain "extra element"). 
16285: 
16286: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16287: 
16288: filter - anonymous hash of criteria and their values
16289: 
16290: action - form action
16291: 
16292: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16293: 
16294: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16295: 
16296: cloneruname - username of owner of new course who wants to clone
16297: 
16298: clonerudom - domain of owner of new course who wants to clone
16299: 
16300: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
16301: 
16302: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16303: 
16304: codedom - domain
16305: 
16306: formname - value of form element named "form". 
16307: 
16308: fixeddom - domain, if fixed.
16309: 
16310: prevphase - value to assign to form element named "phase" when going back to the previous screen  
16311: 
16312: cnameelement - name of form element in form on opener page which will receive title of selected course 
16313: 
16314: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16315: 
16316: cdomelement - name of form element in form on opener page which will receive domain of selected course
16317: 
16318: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16319: 
16320: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16321: 
16322: clonewarning - warning message about missing information for intended course owner when DC creates a course
16323: 
16324: 
16325: Returns: $output - HTML for display of search criteria, and hidden form elements.
16326: 
16327: 
16328: Side Effects: None
16329: 
16330: =cut
16331: 
16332: # ---------------------------------------------- search for courses based on last activity etc.
16333: 
16334: sub build_filters {
16335:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16336:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16337:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16338:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16339:         $clonetext,$clonewarning) = @_;
16340:     my ($list,$jscript);
16341:     my $onchange = 'javascript:updateFilters(this)';
16342:     my ($domainselectform,$sincefilterform,$createdfilterform,
16343:         $ownerdomselectform,$persondomselectform,$instcodeform,
16344:         $typeselectform,$instcodetitle);
16345:     if ($formname eq '') {
16346:         $formname = $caller;
16347:     }
16348:     foreach my $item (@{$filterlist}) {
16349:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16350:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16351:             if ($item eq 'domainfilter') {
16352:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16353:             } elsif ($item eq 'coursefilter') {
16354:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16355:             } elsif ($item eq 'ownerfilter') {
16356:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16357:             } elsif ($item eq 'ownerdomfilter') {
16358:                 $filter->{'ownerdomfilter'} =
16359:                     &LONCAPA::clean_domain($filter->{$item});
16360:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16361:                                                        'ownerdomfilter',1);
16362:             } elsif ($item eq 'personfilter') {
16363:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16364:             } elsif ($item eq 'persondomfilter') {
16365:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16366:                                                         'persondomfilter',1);
16367:             } else {
16368:                 $filter->{$item} =~ s/\W//g;
16369:             }
16370:             if (!$filter->{$item}) {
16371:                 $filter->{$item} = '';
16372:             }
16373:         }
16374:         if ($item eq 'domainfilter') {
16375:             my $allow_blank = 1;
16376:             if ($formname eq 'portform') {
16377:                 $allow_blank=0;
16378:             } elsif ($formname eq 'studentform') {
16379:                 $allow_blank=0;
16380:             }
16381:             if ($fixeddom) {
16382:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16383:                                     ' value="'.$codedom.'" />'.
16384:                                     &Apache::lonnet::domain($codedom,'description');
16385:             } else {
16386:                 $domainselectform = &select_dom_form($filter->{$item},
16387:                                                      'domainfilter',
16388:                                                       $allow_blank,'',$onchange);
16389:             }
16390:         } else {
16391:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16392:         }
16393:     }
16394: 
16395:     # last course activity filter and selection
16396:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16397: 
16398:     # course created filter and selection
16399:     if (exists($filter->{'createdfilter'})) {
16400:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16401:     }
16402: 
16403:     my $prefix = $crstype;
16404:     if ($crstype eq 'Placement') {
16405:         $prefix = 'Placement Test'
16406:     }
16407:     my %lt = &Apache::lonlocal::texthash(
16408:                 'cac' => "$prefix Activity",
16409:                 'ccr' => "$prefix Created",
16410:                 'cde' => "$prefix Title",
16411:                 'cdo' => "$prefix Domain",
16412:                 'ins' => 'Institutional Code',
16413:                 'inc' => 'Institutional Categorization',
16414:                 'cow' => "$prefix Owner/Co-owner",
16415:                 'cop' => "$prefix Personnel Includes",
16416:                 'cog' => 'Type',
16417:              );
16418: 
16419:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16420:         my $typeval = 'Course';
16421:         if ($crstype eq 'Community') {
16422:             $typeval = 'Community';
16423:         } elsif ($crstype eq 'Placement') {
16424:             $typeval = 'Placement';
16425:         }
16426:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16427:     } else {
16428:         $typeselectform =  '<select name="type" size="1"';
16429:         if ($onchange) {
16430:             $typeselectform .= ' onchange="'.$onchange.'"';
16431:         }
16432:         $typeselectform .= '>'."\n";
16433:         foreach my $posstype ('Course','Community','Placement') {
16434:             my $shown;
16435:             if ($posstype eq 'Placement') {
16436:                 $shown = &mt('Placement Test');
16437:             } else {
16438:                 $shown = &mt($posstype);
16439:             }
16440:             $typeselectform.='<option value="'.$posstype.'"'.
16441:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16442:         }
16443:         $typeselectform.="</select>";
16444:     }
16445: 
16446:     my ($cloneableonlyform,$cloneabletitle);
16447:     if (exists($filter->{'cloneableonly'})) {
16448:         my $cloneableon = '';
16449:         my $cloneableoff = ' checked="checked"';
16450:         if ($filter->{'cloneableonly'}) {
16451:             $cloneableon = $cloneableoff;
16452:             $cloneableoff = '';
16453:         }
16454:         $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>';
16455:         if ($formname eq 'ccrs') {
16456:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16457:         } else {
16458:             $cloneabletitle = &mt('Cloneable by you');
16459:         }
16460:     }
16461:     my $officialjs;
16462:     if ($crstype eq 'Course') {
16463:         if (exists($filter->{'instcodefilter'})) {
16464: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16465: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16466:             if ($codedom) { 
16467:                 $officialjs = 1;
16468:                 ($instcodeform,$jscript,$$numtitlesref) =
16469:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16470:                                                                   $officialjs,$codetitlesref);
16471:                 if ($jscript) {
16472:                     $jscript = '<script type="text/javascript">'."\n".
16473:                                '// <![CDATA['."\n".
16474:                                $jscript."\n".
16475:                                '// ]]>'."\n".
16476:                                '</script>'."\n";
16477:                 }
16478:             }
16479:             if ($instcodeform eq '') {
16480:                 $instcodeform =
16481:                     '<input type="text" name="instcodefilter" size="10" value="'.
16482:                     $list->{'instcodefilter'}.'" />';
16483:                 $instcodetitle = $lt{'ins'};
16484:             } else {
16485:                 $instcodetitle = $lt{'inc'};
16486:             }
16487:             if ($fixeddom) {
16488:                 $instcodetitle .= '<br />('.$codedom.')';
16489:             }
16490:         }
16491:     }
16492:     my $output = qq|
16493: <form method="post" name="filterpicker" action="$action">
16494: <input type="hidden" name="form" value="$formname" />
16495: |;
16496:     if ($formname eq 'modifycourse') {
16497:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16498:                    '<input type="hidden" name="prevphase" value="'.
16499:                    $prevphase.'" />'."\n";
16500:     } elsif ($formname eq 'quotacheck') {
16501:         $output .= qq|
16502: <input type="hidden" name="sortby" value="" />
16503: <input type="hidden" name="sortorder" value="" />
16504: |;
16505:     } else {
16506:         my $name_input;
16507:         if ($cnameelement ne '') {
16508:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16509:                           $cnameelement.'" />';
16510:         }
16511:         $output .= qq|
16512: <input type="hidden" name="cnumelement" value="$cnumelement" />
16513: <input type="hidden" name="cdomelement" value="$cdomelement" />
16514: $name_input
16515: $roleelement
16516: $multelement
16517: $typeelement
16518: |;
16519:         if ($formname eq 'portform') {
16520:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16521:         }
16522:     }
16523:     if ($fixeddom) {
16524:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16525:     }
16526:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16527:     if ($sincefilterform) {
16528:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16529:                   .$sincefilterform
16530:                   .&Apache::lonhtmlcommon::row_closure();
16531:     }
16532:     if ($createdfilterform) {
16533:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16534:                   .$createdfilterform
16535:                   .&Apache::lonhtmlcommon::row_closure();
16536:     }
16537:     if ($domainselectform) {
16538:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16539:                   .$domainselectform
16540:                   .&Apache::lonhtmlcommon::row_closure();
16541:     }
16542:     if ($typeselectform) {
16543:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16544:             $output .= $typeselectform;
16545:         } else {
16546:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16547:                       .$typeselectform
16548:                       .&Apache::lonhtmlcommon::row_closure();
16549:         }
16550:     }
16551:     if ($instcodeform) {
16552:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16553:                   .$instcodeform
16554:                   .&Apache::lonhtmlcommon::row_closure();
16555:     }
16556:     if (exists($filter->{'ownerfilter'})) {
16557:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16558:                    '<table><tr><td>'.&mt('Username').'<br />'.
16559:                    '<input type="text" name="ownerfilter" size="20" value="'.
16560:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16561:                    $ownerdomselectform.'</td></tr></table>'.
16562:                    &Apache::lonhtmlcommon::row_closure();
16563:     }
16564:     if (exists($filter->{'personfilter'})) {
16565:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16566:                    '<table><tr><td>'.&mt('Username').'<br />'.
16567:                    '<input type="text" name="personfilter" size="20" value="'.
16568:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16569:                    $persondomselectform.'</td></tr></table>'.
16570:                    &Apache::lonhtmlcommon::row_closure();
16571:     }
16572:     if (exists($filter->{'coursefilter'})) {
16573:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16574:                   .'<input type="text" name="coursefilter" size="25" value="'
16575:                   .$list->{'coursefilter'}.'" />'
16576:                   .&Apache::lonhtmlcommon::row_closure();
16577:     }
16578:     if ($cloneableonlyform) {
16579:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16580:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16581:     }
16582:     if (exists($filter->{'descriptfilter'})) {
16583:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16584:                   .'<input type="text" name="descriptfilter" size="40" value="'
16585:                   .$list->{'descriptfilter'}.'" />'
16586:                   .&Apache::lonhtmlcommon::row_closure(1);
16587:     }
16588:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16589:                '<input type="hidden" name="updater" value="" />'."\n".
16590:                '<input type="submit" name="gosearch" value="'.
16591:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16592:     return $jscript.$clonewarning.$output;
16593: }
16594: 
16595: =pod 
16596: 
16597: =item * &timebased_select_form()
16598: 
16599: Create markup for a dropdown list used to select a time-based
16600: filter e.g., Course Activity, Course Created, when searching for courses
16601: or communities
16602: 
16603: Inputs:
16604: 
16605: item - name of form element (sincefilter or createdfilter)
16606: 
16607: filter - anonymous hash of criteria and their values
16608: 
16609: Returns: HTML for a select box contained a blank, then six time selections,
16610:          with value set in incoming form variables currently selected. 
16611: 
16612: Side Effects: None
16613: 
16614: =cut
16615: 
16616: sub timebased_select_form {
16617:     my ($item,$filter) = @_;
16618:     if (ref($filter) eq 'HASH') {
16619:         $filter->{$item} =~ s/[^\d-]//g;
16620:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16621:         return &select_form(
16622:                             $filter->{$item},
16623:                             $item,
16624:                             {      '-1' => '',
16625:                                 '86400' => &mt('today'),
16626:                                '604800' => &mt('last week'),
16627:                               '2592000' => &mt('last month'),
16628:                               '7776000' => &mt('last three months'),
16629:                              '15552000' => &mt('last six months'),
16630:                              '31104000' => &mt('last year'),
16631:                     'select_form_order' =>
16632:                            ['-1','86400','604800','2592000','7776000',
16633:                             '15552000','31104000']});
16634:     }
16635: }
16636: 
16637: =pod
16638: 
16639: =item * &js_changer()
16640: 
16641: Create script tag containing Javascript used to submit course search form
16642: when course type or domain is changed, and also to hide 'Searching ...' on
16643: page load completion for page showing search result.
16644: 
16645: Inputs: None
16646: 
16647: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
16648: 
16649: Side Effects: None
16650: 
16651: =cut
16652: 
16653: sub js_changer {
16654:     return <<ENDJS;
16655: <script type="text/javascript">
16656: // <![CDATA[
16657: function updateFilters(caller) {
16658:     if (typeof(caller) != "undefined") {
16659:         document.filterpicker.updater.value = caller.name;
16660:     }
16661:     document.filterpicker.submit();
16662: }
16663: 
16664: function hideSearching() {
16665:     if (document.getElementById('searching')) {
16666:         document.getElementById('searching').style.display = 'none';
16667:     }
16668:     return;
16669: }
16670: 
16671: // ]]>
16672: </script>
16673: 
16674: ENDJS
16675: }
16676: 
16677: =pod
16678: 
16679: =item * &search_courses()
16680: 
16681: Process selected filters form course search form and pass to lonnet::courseiddump
16682: to retrieve a hash for which keys are courseIDs which match the selected filters.
16683: 
16684: Inputs:
16685: 
16686: dom - domain being searched 
16687: 
16688: type - course type ('Course' or 'Community' or '.' if any).
16689: 
16690: filter - anonymous hash of criteria and their values
16691: 
16692: numtitles - for institutional codes - number of categories
16693: 
16694: cloneruname - optional username of new course owner
16695: 
16696: clonerudom - optional domain of new course owner
16697: 
16698: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
16699:             (used when DC is using course creation form)
16700: 
16701: codetitles - reference to array of titles of components in institutional codes (official courses).
16702: 
16703: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16704:            (and so can clone automatically)
16705: 
16706: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16707: 
16708: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
16709:               courses to clone 
16710: 
16711: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16712: 
16713: 
16714: Side Effects: None
16715: 
16716: =cut
16717: 
16718: 
16719: sub search_courses {
16720:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16721:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16722:     my (%courses,%showcourses,$cloner);
16723:     if (($filter->{'ownerfilter'} ne '') ||
16724:         ($filter->{'ownerdomfilter'} ne '')) {
16725:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16726:                                        $filter->{'ownerdomfilter'};
16727:     }
16728:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16729:         if (!$filter->{$item}) {
16730:             $filter->{$item}='.';
16731:         }
16732:     }
16733:     my $now = time;
16734:     my $timefilter =
16735:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16736:     my ($createdbefore,$createdafter);
16737:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16738:         $createdbefore = $now;
16739:         $createdafter = $now-$filter->{'createdfilter'};
16740:     }
16741:     my ($instcodefilter,$regexpok);
16742:     if ($numtitles) {
16743:         if ($env{'form.official'} eq 'on') {
16744:             $instcodefilter =
16745:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16746:             $regexpok = 1;
16747:         } elsif ($env{'form.official'} eq 'off') {
16748:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16749:             unless ($instcodefilter eq '') {
16750:                 $regexpok = -1;
16751:             }
16752:         }
16753:     } else {
16754:         $instcodefilter = $filter->{'instcodefilter'};
16755:     }
16756:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16757:     if ($type eq '') { $type = '.'; }
16758: 
16759:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16760:         $cloner = $cloneruname.':'.$clonerudom;
16761:     }
16762:     %courses = &Apache::lonnet::courseiddump($dom,
16763:                                              $filter->{'descriptfilter'},
16764:                                              $timefilter,
16765:                                              $instcodefilter,
16766:                                              $filter->{'combownerfilter'},
16767:                                              $filter->{'coursefilter'},
16768:                                              undef,undef,$type,$regexpok,undef,undef,
16769:                                              undef,undef,$cloner,$cc_clone,
16770:                                              $filter->{'cloneableonly'},
16771:                                              $createdbefore,$createdafter,undef,
16772:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16773:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16774:         my $ccrole;
16775:         if ($type eq 'Community') {
16776:             $ccrole = 'co';
16777:         } else {
16778:             $ccrole = 'cc';
16779:         }
16780:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16781:                                                      $filter->{'persondomfilter'},
16782:                                                      'userroles',undef,
16783:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16784:                                                      $dom);
16785:         foreach my $role (keys(%rolehash)) {
16786:             my ($cnum,$cdom,$courserole) = split(':',$role);
16787:             my $cid = $cdom.'_'.$cnum;
16788:             if (exists($courses{$cid})) {
16789:                 if (ref($courses{$cid}) eq 'HASH') {
16790:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16791:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16792:                             push(@{$courses{$cid}{roles}},$courserole);
16793:                         }
16794:                     } else {
16795:                         $courses{$cid}{roles} = [$courserole];
16796:                     }
16797:                     $showcourses{$cid} = $courses{$cid};
16798:                 }
16799:             }
16800:         }
16801:         %courses = %showcourses;
16802:     }
16803:     return %courses;
16804: }
16805: 
16806: =pod
16807: 
16808: =back
16809: 
16810: =head1 Routines for version requirements for current course.
16811: 
16812: =over 4
16813: 
16814: =item * &check_release_required()
16815: 
16816: Compares required LON-CAPA version with version on server, and
16817: if required version is newer looks for a server with the required version.
16818: 
16819: Looks first at servers in user's owen domain; if none suitable, looks at
16820: servers in course's domain are permitted to host sessions for user's domain.
16821: 
16822: Inputs:
16823: 
16824: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16825: 
16826: $courseid - Course ID of current course
16827: 
16828: $rolecode - User's current role in course (for switchserver query string).
16829: 
16830: $required - LON-CAPA version needed by course (format: Major.Minor).
16831: 
16832: 
16833: Returns:
16834: 
16835: $switchserver - query string tp append to /adm/switchserver call (if 
16836:                 current server's LON-CAPA version is too old. 
16837: 
16838: $warning - Message is displayed if no suitable server could be found.
16839: 
16840: =cut
16841: 
16842: sub check_release_required {
16843:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16844:     my ($switchserver,$warning);
16845:     if ($required ne '') {
16846:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16847:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16848:         if ($reqdmajor ne '' && $reqdminor ne '') {
16849:             my $otherserver;
16850:             if (($major eq '' && $minor eq '') ||
16851:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16852:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16853:                 my $switchlcrev =
16854:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16855:                                                            $userdomserver);
16856:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16857:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16858:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16859:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16860:                     if ($cdom ne $env{'user.domain'}) {
16861:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16862:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16863:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16864:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16865:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16866:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16867:                         my $canhost =
16868:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16869:                                                               $coursedomserver,
16870:                                                               $remoterev,
16871:                                                               $udomdefaults{'remotesessions'},
16872:                                                               $defdomdefaults{'hostedsessions'});
16873: 
16874:                         if ($canhost) {
16875:                             $otherserver = $coursedomserver;
16876:                         } else {
16877:                             $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.");
16878:                         }
16879:                     } else {
16880:                         $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).");
16881:                     }
16882:                 } else {
16883:                     $otherserver = $userdomserver;
16884:                 }
16885:             }
16886:             if ($otherserver ne '') {
16887:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16888:             }
16889:         }
16890:     }
16891:     return ($switchserver,$warning);
16892: }
16893: 
16894: =pod
16895: 
16896: =item * &check_release_result()
16897: 
16898: Inputs:
16899: 
16900: $switchwarning - Warning message if no suitable server found to host session.
16901: 
16902: $switchserver - query string to append to /adm/switchserver containing lonHostID
16903:                 and current role.
16904: 
16905: Returns: HTML to display with information about requirement to switch server.
16906:          Either displaying warning with link to Roles/Courses screen or
16907:          display link to switchserver.
16908: 
16909: =cut
16910: 
16911: sub check_release_result {
16912:     my ($switchwarning,$switchserver) = @_;
16913:     my $output = &start_page('Selected course unavailable on this server').
16914:                  '<p class="LC_warning">';
16915:     if ($switchwarning) {
16916:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16917:         if (&show_course()) {
16918:             $output .= &mt('Display courses');
16919:         } else {
16920:             $output .= &mt('Display roles');
16921:         }
16922:         $output .= '</a>';
16923:     } elsif ($switchserver) {
16924:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16925:                    '<br />'.
16926:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16927:                    &mt('Switch Server').
16928:                    '</a>';
16929:     }
16930:     $output .= '</p>'.&end_page();
16931:     return $output;
16932: }
16933: 
16934: =pod
16935: 
16936: =item * &needs_coursereinit()
16937: 
16938: Determine if course contents stored for user's session needs to be
16939: refreshed, because content has changed since "Big Hash" last tied.
16940: 
16941: Check for change is made if time last checked is more than 10 minutes ago
16942: (by default).
16943: 
16944: Inputs:
16945: 
16946: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16947: 
16948: $interval (optional) - Time which may elapse (in s) between last check for content
16949:                        change in current course. (default: 600 s).  
16950: 
16951: Returns: an array; first element is:
16952: 
16953: =over 4
16954: 
16955: 'switch' - if content updates mean user's session
16956:            needs to be switched to a server running a newer LON-CAPA version
16957:  
16958: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16959:            on current server hosting user's session                
16960: 
16961: ''       - if no action required.
16962: 
16963: =back
16964: 
16965: If first item element is 'switch':
16966: 
16967: second item is $switchwarning - Warning message if no suitable server found to host session. 
16968: 
16969: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16970:                               and current role. 
16971: 
16972: otherwise: no other elements returned.
16973: 
16974: =back
16975: 
16976: =cut
16977: 
16978: sub needs_coursereinit {
16979:     my ($loncaparev,$interval) = @_;
16980:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16981:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16982:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16983:     my $now = time;
16984:     if ($interval eq '') {
16985:         $interval = 600;
16986:     }
16987:     if (($now-$env{'request.course.timechecked'})>$interval) {
16988:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16989:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16990:         if ($lastchange > $env{'request.course.tied'}) {
16991:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16992:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16993:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16994:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16995:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16996:                                              $curr_reqd_hash{'internal.releaserequired'}});
16997:                     my ($switchserver,$switchwarning) =
16998:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16999:                                                 $curr_reqd_hash{'internal.releaserequired'});
17000:                     if ($switchwarning ne '' || $switchserver ne '') {
17001:                         return ('switch',$switchwarning,$switchserver);
17002:                     }
17003:                 }
17004:             }
17005:             return ('update');
17006:         }
17007:     }
17008:     return ();
17009: }
17010: 
17011: sub update_content_constraints {
17012:     my ($cdom,$cnum,$chome,$cid) = @_;
17013:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17014:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17015:     my %checkresponsetypes;
17016:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17017:         my ($item,$name,$value) = split(/:/,$key);
17018:         if ($item eq 'resourcetag') {
17019:             if ($name eq 'responsetype') {
17020:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17021:             }
17022:         }
17023:     }
17024:     my $navmap = Apache::lonnavmaps::navmap->new();
17025:     if (defined($navmap)) {
17026:         my %allresponses;
17027:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17028:             my %responses = $res->responseTypes();
17029:             foreach my $key (keys(%responses)) {
17030:                 next unless(exists($checkresponsetypes{$key}));
17031:                 $allresponses{$key} += $responses{$key};
17032:             }
17033:         }
17034:         foreach my $key (keys(%allresponses)) {
17035:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17036:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17037:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17038:             }
17039:         }
17040:         undef($navmap);
17041:     }
17042:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17043:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17044:     }
17045:     return;
17046: }
17047: 
17048: sub allmaps_incourse {
17049:     my ($cdom,$cnum,$chome,$cid) = @_;
17050:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17051:         $cid = $env{'request.course.id'};
17052:         $cdom = $env{'course.'.$cid.'.domain'};
17053:         $cnum = $env{'course.'.$cid.'.num'};
17054:         $chome = $env{'course.'.$cid.'.home'};
17055:     }
17056:     my %allmaps = ();
17057:     my $lastchange =
17058:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17059:     if ($lastchange > $env{'request.course.tied'}) {
17060:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17061:         unless ($ferr) {
17062:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17063:         }
17064:     }
17065:     my $navmap = Apache::lonnavmaps::navmap->new();
17066:     if (defined($navmap)) {
17067:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17068:             $allmaps{$res->src()} = 1;
17069:         }
17070:     }
17071:     return \%allmaps;
17072: }
17073: 
17074: sub parse_supplemental_title {
17075:     my ($title) = @_;
17076: 
17077:     my ($foldertitle,$renametitle);
17078:     if ($title =~ /&amp;&amp;&amp;/) {
17079:         $title = &HTML::Entites::decode($title);
17080:     }
17081:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17082:         $renametitle=$4;
17083:         my ($time,$uname,$udom) = ($1,$2,$3);
17084:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17085:         my $name =  &plainname($uname,$udom);
17086:         $name = &HTML::Entities::encode($name,'"<>&\'');
17087:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17088:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17089:             $name.': <br />'.$foldertitle;
17090:     }
17091:     if (wantarray) {
17092:         return ($title,$foldertitle,$renametitle);
17093:     }
17094:     return $title;
17095: }
17096: 
17097: sub recurse_supplemental {
17098:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17099:     if ($suppmap) {
17100:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17101:         if ($fatal) {
17102:             $errors ++;
17103:         } else {
17104:             if ($#LONCAPA::map::resources > 0) {
17105:                 foreach my $res (@LONCAPA::map::resources) {
17106:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17107:                     if (($src ne '') && ($status eq 'res')) {
17108:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17109:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17110:                         } else {
17111:                             $numfiles ++;
17112:                         }
17113:                     }
17114:                 }
17115:             }
17116:         }
17117:     }
17118:     return ($numfiles,$errors);
17119: }
17120: 
17121: sub symb_to_docspath {
17122:     my ($symb,$navmapref) = @_;
17123:     return unless ($symb && ref($navmapref));
17124:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17125:     if ($resurl=~/\.(sequence|page)$/) {
17126:         $mapurl=$resurl;
17127:     } elsif ($resurl eq 'adm/navmaps') {
17128:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17129:     }
17130:     my $mapresobj;
17131:     unless (ref($$navmapref)) {
17132:         $$navmapref = Apache::lonnavmaps::navmap->new();
17133:     }
17134:     if (ref($$navmapref)) {
17135:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17136:     }
17137:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17138:     my $type=$2;
17139:     my $path;
17140:     if (ref($mapresobj)) {
17141:         my $pcslist = $mapresobj->map_hierarchy();
17142:         if ($pcslist ne '') {
17143:             foreach my $pc (split(/,/,$pcslist)) {
17144:                 next if ($pc <= 1);
17145:                 my $res = $$navmapref->getByMapPc($pc);
17146:                 if (ref($res)) {
17147:                     my $thisurl = $res->src();
17148:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17149:                     my $thistitle = $res->title();
17150:                     $path .= '&'.
17151:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17152:                              &escape($thistitle).
17153:                              ':'.$res->randompick().
17154:                              ':'.$res->randomout().
17155:                              ':'.$res->encrypted().
17156:                              ':'.$res->randomorder().
17157:                              ':'.$res->is_page();
17158:                 }
17159:             }
17160:         }
17161:         $path =~ s/^\&//;
17162:         my $maptitle = $mapresobj->title();
17163:         if ($mapurl eq 'default') {
17164:             $maptitle = 'Main Content';
17165:         }
17166:         $path .= (($path ne '')? '&' : '').
17167:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17168:                  &escape($maptitle).
17169:                  ':'.$mapresobj->randompick().
17170:                  ':'.$mapresobj->randomout().
17171:                  ':'.$mapresobj->encrypted().
17172:                  ':'.$mapresobj->randomorder().
17173:                  ':'.$mapresobj->is_page();
17174:     } else {
17175:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17176:         my $ispage = (($type eq 'page')? 1 : '');
17177:         if ($mapurl eq 'default') {
17178:             $maptitle = 'Main Content';
17179:         }
17180:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17181:                 &escape($maptitle).':::::'.$ispage;
17182:     }
17183:     unless ($mapurl eq 'default') {
17184:         $path = 'default&'.
17185:                 &escape('Main Content').
17186:                 ':::::&'.$path;
17187:     }
17188:     return $path;
17189: }
17190: 
17191: sub captcha_display {
17192:     my ($context,$lonhost) = @_;
17193:     my ($output,$error);
17194:     my ($captcha,$pubkey,$privkey,$version) = 
17195:         &get_captcha_config($context,$lonhost);
17196:     if ($captcha eq 'original') {
17197:         $output = &create_captcha();
17198:         unless ($output) {
17199:             $error = 'captcha';
17200:         }
17201:     } elsif ($captcha eq 'recaptcha') {
17202:         $output = &create_recaptcha($pubkey,$version);
17203:         unless ($output) {
17204:             $error = 'recaptcha';
17205:         }
17206:     }
17207:     return ($output,$error,$captcha,$version);
17208: }
17209: 
17210: sub captcha_response {
17211:     my ($context,$lonhost) = @_;
17212:     my ($captcha_chk,$captcha_error);
17213:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
17214:     if ($captcha eq 'original') {
17215:         ($captcha_chk,$captcha_error) = &check_captcha();
17216:     } elsif ($captcha eq 'recaptcha') {
17217:         $captcha_chk = &check_recaptcha($privkey,$version);
17218:     } else {
17219:         $captcha_chk = 1;
17220:     }
17221:     return ($captcha_chk,$captcha_error);
17222: }
17223: 
17224: sub get_captcha_config {
17225:     my ($context,$lonhost) = @_;
17226:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17227:     my $hostname = &Apache::lonnet::hostname($lonhost);
17228:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17229:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17230:     if ($context eq 'usercreation') {
17231:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17232:         if (ref($domconfig{$context}) eq 'HASH') {
17233:             $hashtocheck = $domconfig{$context}{'cancreate'};
17234:             if (ref($hashtocheck) eq 'HASH') {
17235:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17236:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17237:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17238:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17239:                     }
17240:                     if ($privkey && $pubkey) {
17241:                         $captcha = 'recaptcha';
17242:                         $version = $hashtocheck->{'recaptchaversion'};
17243:                         if ($version ne '2') {
17244:                             $version = 1;
17245:                         }
17246:                     } else {
17247:                         $captcha = 'original';
17248:                     }
17249:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17250:                     $captcha = 'original';
17251:                 }
17252:             }
17253:         } else {
17254:             $captcha = 'captcha';
17255:         }
17256:     } elsif ($context eq 'login') {
17257:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17258:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17259:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17260:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17261:             if ($privkey && $pubkey) {
17262:                 $captcha = 'recaptcha';
17263:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17264:                 if ($version ne '2') {
17265:                     $version = 1; 
17266:                 }
17267:             } else {
17268:                 $captcha = 'original';
17269:             }
17270:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17271:             $captcha = 'original';
17272:         }
17273:     }
17274:     return ($captcha,$pubkey,$privkey,$version);
17275: }
17276: 
17277: sub create_captcha {
17278:     my %captcha_params = &captcha_settings();
17279:     my ($output,$maxtries,$tries) = ('',10,0);
17280:     while ($tries < $maxtries) {
17281:         $tries ++;
17282:         my $captcha = Authen::Captcha->new (
17283:                                            output_folder => $captcha_params{'output_dir'},
17284:                                            data_folder   => $captcha_params{'db_dir'},
17285:                                           );
17286:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17287: 
17288:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17289:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17290:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17291:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17292:                       '<br />'.
17293:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17294:             last;
17295:         }
17296:     }
17297:     return $output;
17298: }
17299: 
17300: sub captcha_settings {
17301:     my %captcha_params = (
17302:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17303:                            www_output_dir => "/captchaspool",
17304:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17305:                            numchars       => '5',
17306:                          );
17307:     return %captcha_params;
17308: }
17309: 
17310: sub check_captcha {
17311:     my ($captcha_chk,$captcha_error);
17312:     my $code = $env{'form.code'};
17313:     my $md5sum = $env{'form.crypt'};
17314:     my %captcha_params = &captcha_settings();
17315:     my $captcha = Authen::Captcha->new(
17316:                       output_folder => $captcha_params{'output_dir'},
17317:                       data_folder   => $captcha_params{'db_dir'},
17318:                   );
17319:     $captcha_chk = $captcha->check_code($code,$md5sum);
17320:     my %captcha_hash = (
17321:                         0       => 'Code not checked (file error)',
17322:                        -1      => 'Failed: code expired',
17323:                        -2      => 'Failed: invalid code (not in database)',
17324:                        -3      => 'Failed: invalid code (code does not match crypt)',
17325:     );
17326:     if ($captcha_chk != 1) {
17327:         $captcha_error = $captcha_hash{$captcha_chk}
17328:     }
17329:     return ($captcha_chk,$captcha_error);
17330: }
17331: 
17332: sub create_recaptcha {
17333:     my ($pubkey,$version) = @_;
17334:     if ($version >= 2) {
17335:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17336:     } else {
17337:         my $use_ssl;
17338:         if ($ENV{'SERVER_PORT'} == 443) {
17339:             $use_ssl = 1;
17340:         }
17341:         my $captcha = Captcha::reCAPTCHA->new;
17342:         return $captcha->get_options_setter({theme => 'white'})."\n".
17343:                $captcha->get_html($pubkey,undef,$use_ssl).
17344:                &mt('If the text is hard to read, [_1] will replace them.',
17345:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17346:                '<br /><br />';
17347:     }
17348: }
17349: 
17350: sub check_recaptcha {
17351:     my ($privkey,$version) = @_;
17352:     my $captcha_chk;
17353:     if ($version >= 2) {
17354:         my $ua = LWP::UserAgent->new;
17355:         $ua->timeout(10);
17356:         my %info = (
17357:                      secret   => $privkey, 
17358:                      response => $env{'form.g-recaptcha-response'},
17359:                      remoteip => $ENV{'REMOTE_ADDR'},
17360:                    );
17361:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17362:         if ($response->is_success)  {
17363:             my $data = JSON::DWIW->from_json($response->decoded_content);
17364:             if (ref($data) eq 'HASH') {
17365:                 if ($data->{'success'}) {
17366:                     $captcha_chk = 1;
17367:                 }
17368:             }
17369:         }
17370:     } else {
17371:         my $captcha = Captcha::reCAPTCHA->new;
17372:         my $captcha_result =
17373:             $captcha->check_answer(
17374:                                     $privkey,
17375:                                     $ENV{'REMOTE_ADDR'},
17376:                                     $env{'form.recaptcha_challenge_field'},
17377:                                     $env{'form.recaptcha_response_field'},
17378:                                   );
17379:         if ($captcha_result->{is_valid}) {
17380:             $captcha_chk = 1;
17381:         }
17382:     }
17383:     return $captcha_chk;
17384: }
17385: 
17386: sub emailusername_info {
17387:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17388:     my %titles = &Apache::lonlocal::texthash (
17389:                      lastname      => 'Last Name',
17390:                      firstname     => 'First Name',
17391:                      institution   => 'School/college/university',
17392:                      location      => "School's city, state/province, country",
17393:                      web           => "School's web address",
17394:                      officialemail => 'E-mail address at institution (if different)',
17395:                      id            => 'Student/Employee ID',
17396:                  );
17397:     return (\@fields,\%titles);
17398: }
17399: 
17400: sub cleanup_html {
17401:     my ($incoming) = @_;
17402:     my $outgoing;
17403:     if ($incoming ne '') {
17404:         $outgoing = $incoming;
17405:         $outgoing =~ s/;/&#059;/g;
17406:         $outgoing =~ s/\#/&#035;/g;
17407:         $outgoing =~ s/\&/&#038;/g;
17408:         $outgoing =~ s/</&#060;/g;
17409:         $outgoing =~ s/>/&#062;/g;
17410:         $outgoing =~ s/\(/&#040/g;
17411:         $outgoing =~ s/\)/&#041;/g;
17412:         $outgoing =~ s/"/&#034;/g;
17413:         $outgoing =~ s/'/&#039;/g;
17414:         $outgoing =~ s/\$/&#036;/g;
17415:         $outgoing =~ s{/}{&#047;}g;
17416:         $outgoing =~ s/=/&#061;/g;
17417:         $outgoing =~ s/\\/&#092;/g
17418:     }
17419:     return $outgoing;
17420: }
17421: 
17422: # Checks for critical messages and returns a redirect url if one exists.
17423: # $interval indicates how often to check for messages.
17424: sub critical_redirect {
17425:     my ($interval) = @_;
17426:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17427:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
17428:                                         $env{'user.name'});
17429:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17430:         my $redirecturl;
17431:         if ($what[0]) {
17432: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17433: 	        $redirecturl='/adm/email?critical=display';
17434: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
17435:                 return (1, $url);
17436:             }
17437:         }
17438:     } 
17439:     return ();
17440: }
17441: 
17442: # Use:
17443: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17444: #
17445: ##################################################
17446: #          password associated functions         #
17447: ##################################################
17448: sub des_keys {
17449:     # Make a new key for DES encryption.
17450:     # Each key has two parts which are returned separately.
17451:     # Please note:  Each key must be passed through the &hex function
17452:     # before it is output to the web browser.  The hex versions cannot
17453:     # be used to decrypt.
17454:     my @hexstr=('0','1','2','3','4','5','6','7',
17455:                 '8','9','a','b','c','d','e','f');
17456:     my $lkey='';
17457:     for (0..7) {
17458:         $lkey.=$hexstr[rand(15)];
17459:     }
17460:     my $ukey='';
17461:     for (0..7) {
17462:         $ukey.=$hexstr[rand(15)];
17463:     }
17464:     return ($lkey,$ukey);
17465: }
17466: 
17467: sub des_decrypt {
17468:     my ($key,$cyphertext) = @_;
17469:     my $keybin=pack("H16",$key);
17470:     my $cypher;
17471:     if ($Crypt::DES::VERSION>=2.03) {
17472:         $cypher=new Crypt::DES $keybin;
17473:     } else {
17474:         $cypher=new DES $keybin;
17475:     }
17476:     my $plaintext='';
17477:     my $cypherlength = length($cyphertext);
17478:     my $numchunks = int($cypherlength/32);
17479:     for (my $j=0; $j<$numchunks; $j++) {
17480:         my $start = $j*32;
17481:         my $cypherblock = substr($cyphertext,$start,32);
17482:         my $chunk =
17483:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17484:         $chunk .=
17485:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17486:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17487:         $plaintext .= $chunk;
17488:     }
17489:     return $plaintext;
17490: }
17491: 
17492: 1;
17493: __END__;
17494: 

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