File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.66: download - view: text, annotated - select for diffs
Wed Feb 19 19:49:30 2014 UTC (10 years, 3 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.1172, 1.1176

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.66 2014/02/19 19:49:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use LONCAPA qw(:DEFAULT :match);
   73: use DateTime::TimeZone;
   74: use DateTime::Locale::Catalog;
   75: use Authen::Captcha;
   76: use Captcha::reCAPTCHA;
   77: use Crypt::DES;
   78: use DynaLoader; # for Crypt::DES version
   79: 
   80: # ---------------------------------------------- Designs
   81: use vars qw(%defaultdesign);
   82: 
   83: my $readit;
   84: 
   85: 
   86: ##
   87: ## Global Variables
   88: ##
   89: 
   90: 
   91: # ----------------------------------------------- SSI with retries:
   92: #
   93: 
   94: =pod
   95: 
   96: =head1 Server Side include with retries:
   97: 
   98: =over 4
   99: 
  100: =item * &ssi_with_retries(resource,retries form)
  101: 
  102: Performs an ssi with some number of retries.  Retries continue either
  103: until the result is ok or until the retry count supplied by the
  104: caller is exhausted.  
  105: 
  106: Inputs:
  107: 
  108: =over 4
  109: 
  110: resource   - Identifies the resource to insert.
  111: 
  112: retries    - Count of the number of retries allowed.
  113: 
  114: form       - Hash that identifies the rendering options.
  115: 
  116: =back
  117: 
  118: Returns:
  119: 
  120: =over 4
  121: 
  122: content    - The content of the response.  If retries were exhausted this is empty.
  123: 
  124: response   - The response from the last attempt (which may or may not have been successful.
  125: 
  126: =back
  127: 
  128: =back
  129: 
  130: =cut
  131: 
  132: sub ssi_with_retries {
  133:     my ($resource, $retries, %form) = @_;
  134: 
  135: 
  136:     my $ok = 0;			# True if we got a good response.
  137:     my $content;
  138:     my $response;
  139: 
  140:     # Try to get the ssi done. within the retries count:
  141: 
  142:     do {
  143: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  144: 	$ok      = $response->is_success;
  145:         if (!$ok) {
  146:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  147:         }
  148: 	$retries--;
  149:     } while (!$ok && ($retries > 0));
  150: 
  151:     if (!$ok) {
  152: 	$content = '';		# On error return an empty content.
  153:     }
  154:     return ($content, $response);
  155: 
  156: }
  157: 
  158: 
  159: 
  160: # ----------------------------------------------- Filetypes/Languages/Copyright
  161: my %language;
  162: my %supported_language;
  163: my %latex_language;		# For choosing hyphenation in <transl..>
  164: my %latex_language_bykey;	# for choosing hyphenation from metadata
  165: my %cprtag;
  166: my %scprtag;
  167: my %fe; my %fd; my %fm;
  168: my %category_extensions;
  169: 
  170: # ---------------------------------------------- Thesaurus variables
  171: #
  172: # %Keywords:
  173: #      A hash used by &keyword to determine if a word is considered a keyword.
  174: # $thesaurus_db_file 
  175: #      Scalar containing the full path to the thesaurus database.
  176: 
  177: my %Keywords;
  178: my $thesaurus_db_file;
  179: 
  180: #
  181: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  182: # thesaurus.tab, and filecategories.tab.
  183: #
  184: BEGIN {
  185:     # Variable initialization
  186:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  187:     #
  188:     unless ($readit) {
  189: # ------------------------------------------------------------------- languages
  190:     {
  191:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  192:                                    '/language.tab';
  193:         if ( open(my $fh,"<$langtabfile") ) {
  194:             while (my $line = <$fh>) {
  195:                 next if ($line=~/^\#/);
  196:                 chomp($line);
  197:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  198:                 $language{$key}=$val.' - '.$enc;
  199:                 if ($sup) {
  200:                     $supported_language{$key}=$sup;
  201:                 }
  202: 		if ($latex) {
  203: 		    $latex_language_bykey{$key} = $latex;
  204: 		    $latex_language{$two} = $latex;
  205: 		}
  206:             }
  207:             close($fh);
  208:         }
  209:     }
  210: # ------------------------------------------------------------------ copyrights
  211:     {
  212:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  213:                                   '/copyright.tab';
  214:         if ( open (my $fh,"<$copyrightfile") ) {
  215:             while (my $line = <$fh>) {
  216:                 next if ($line=~/^\#/);
  217:                 chomp($line);
  218:                 my ($key,$val)=(split(/\s+/,$line,2));
  219:                 $cprtag{$key}=$val;
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: # ----------------------------------------------------------- source copyrights
  225:     {
  226:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  227:                                   '/source_copyright.tab';
  228:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  229:             while (my $line = <$fh>) {
  230:                 next if ($line =~ /^\#/);
  231:                 chomp($line);
  232:                 my ($key,$val)=(split(/\s+/,$line,2));
  233:                 $scprtag{$key}=$val;
  234:             }
  235:             close($fh);
  236:         }
  237:     }
  238: 
  239: # -------------------------------------------------------------- default domain designs
  240:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  241:     my $designfile = $designdir.'/default.tab';
  242:     if ( open (my $fh,"<$designfile") ) {
  243:         while (my $line = <$fh>) {
  244:             next if ($line =~ /^\#/);
  245:             chomp($line);
  246:             my ($key,$val)=(split(/\=/,$line));
  247:             if ($val) { $defaultdesign{$key}=$val; }
  248:         }
  249:         close($fh);
  250:     }
  251: 
  252: # ------------------------------------------------------------- file categories
  253:     {
  254:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  255:                                   '/filecategories.tab';
  256:         if ( open (my $fh,"<$categoryfile") ) {
  257: 	    while (my $line = <$fh>) {
  258: 		next if ($line =~ /^\#/);
  259: 		chomp($line);
  260:                 my ($extension,$category)=(split(/\s+/,$line,2));
  261:                 push @{$category_extensions{lc($category)}},$extension;
  262:             }
  263:             close($fh);
  264:         }
  265: 
  266:     }
  267: # ------------------------------------------------------------------ file types
  268:     {
  269:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  270:                '/filetypes.tab';
  271:         if ( open (my $fh,"<$typesfile") ) {
  272:             while (my $line = <$fh>) {
  273: 		next if ($line =~ /^\#/);
  274: 		chomp($line);
  275:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  276:                 if ($descr ne '') {
  277:                     $fe{$ending}=lc($emb);
  278:                     $fd{$ending}=$descr;
  279:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  280:                 }
  281:             }
  282:             close($fh);
  283:         }
  284:     }
  285:     &Apache::lonnet::logthis(
  286:              "<span style='color:yellow;'>INFO: Read file types</span>");
  287:     $readit=1;
  288:     }  # end of unless($readit) 
  289:     
  290: }
  291: 
  292: ###############################################################
  293: ##           HTML and Javascript Helper Functions            ##
  294: ###############################################################
  295: 
  296: =pod 
  297: 
  298: =head1 HTML and Javascript Functions
  299: 
  300: =over 4
  301: 
  302: =item * &browser_and_searcher_javascript()
  303: 
  304: X<browsing, javascript>X<searching, javascript>Returns a string
  305: containing javascript with two functions, C<openbrowser> and
  306: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  307: tags.
  308: 
  309: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  310: 
  311: inputs: formname, elementname, only, omit
  312: 
  313: formname and elementname indicate the name of the html form and name of
  314: the element that the results of the browsing selection are to be placed in. 
  315: 
  316: Specifying 'only' will restrict the browser to displaying only files
  317: with the given extension.  Can be a comma separated list.
  318: 
  319: Specifying 'omit' will restrict the browser to NOT displaying files
  320: with the given extension.  Can be a comma separated list.
  321: 
  322: =item * &opensearcher(formname,elementname) [javascript]
  323: 
  324: Inputs: formname, elementname
  325: 
  326: formname and elementname specify the name of the html form and the name
  327: of the element the selection from the search results will be placed in.
  328: 
  329: =cut
  330: 
  331: sub browser_and_searcher_javascript {
  332:     my ($mode)=@_;
  333:     if (!defined($mode)) { $mode='edit'; }
  334:     my $resurl=&escape_single(&lastresurl());
  335:     return <<END;
  336: // <!-- BEGIN LON-CAPA Internal
  337:     var editbrowser = null;
  338:     function openbrowser(formname,elementname,only,omit,titleelement) {
  339:         var url = '$resurl/?';
  340:         if (editbrowser == null) {
  341:             url += 'launch=1&';
  342:         }
  343:         url += 'catalogmode=interactive&';
  344:         url += 'mode=$mode&';
  345:         url += 'inhibitmenu=yes&';
  346:         url += 'form=' + formname + '&';
  347:         if (only != null) {
  348:             url += 'only=' + only + '&';
  349:         } else {
  350:             url += 'only=&';
  351: 	}
  352:         if (omit != null) {
  353:             url += 'omit=' + omit + '&';
  354:         } else {
  355:             url += 'omit=&';
  356: 	}
  357:         if (titleelement != null) {
  358:             url += 'titleelement=' + titleelement + '&';
  359:         } else {
  360: 	    url += 'titleelement=&';
  361: 	}
  362:         url += 'element=' + elementname + '';
  363:         var title = 'Browser';
  364:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  365:         options += ',width=700,height=600';
  366:         editbrowser = open(url,title,options,'1');
  367:         editbrowser.focus();
  368:     }
  369:     var editsearcher;
  370:     function opensearcher(formname,elementname,titleelement) {
  371:         var url = '/adm/searchcat?';
  372:         if (editsearcher == null) {
  373:             url += 'launch=1&';
  374:         }
  375:         url += 'catalogmode=interactive&';
  376:         url += 'mode=$mode&';
  377:         url += 'form=' + formname + '&';
  378:         if (titleelement != null) {
  379:             url += 'titleelement=' + titleelement + '&';
  380:         } else {
  381: 	    url += 'titleelement=&';
  382: 	}
  383:         url += 'element=' + elementname + '';
  384:         var title = 'Search';
  385:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  386:         options += ',width=700,height=600';
  387:         editsearcher = open(url,title,options,'1');
  388:         editsearcher.focus();
  389:     }
  390: // END LON-CAPA Internal -->
  391: END
  392: }
  393: 
  394: sub lastresurl {
  395:     if ($env{'environment.lastresurl'}) {
  396: 	return $env{'environment.lastresurl'}
  397:     } else {
  398: 	return '/res';
  399:     }
  400: }
  401: 
  402: sub storeresurl {
  403:     my $resurl=&Apache::lonnet::clutter(shift);
  404:     unless ($resurl=~/^\/res/) { return 0; }
  405:     $resurl=~s/\/$//;
  406:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  407:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  408:     return 1;
  409: }
  410: 
  411: sub studentbrowser_javascript {
  412:    unless (
  413:             (($env{'request.course.id'}) && 
  414:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  415: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  416: 					  '/'.$env{'request.course.sec'})
  417: 	      ))
  418:          || ($env{'request.role'}=~/^(au|dc|su)/)
  419:           ) { return ''; }  
  420:    return (<<'ENDSTDBRW');
  421: <script type="text/javascript" language="Javascript">
  422: // <![CDATA[
  423:     var stdeditbrowser;
  424:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  425:         var url = '/adm/pickstudent?';
  426:         var filter;
  427: 	if (!ignorefilter) {
  428: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  429: 	}
  430:         if (filter != null) {
  431:            if (filter != '') {
  432:                url += 'filter='+filter+'&';
  433: 	   }
  434:         }
  435:         url += 'form=' + formname + '&unameelement='+uname+
  436:                                     '&udomelement='+udom+
  437:                                     '&clicker='+clicker;
  438: 	if (roleflag) { url+="&roles=1"; }
  439:         if (courseadvonly) { url+="&courseadvonly=1"; }
  440:         var title = 'Student_Browser';
  441:         var options = 'scrollbars=1,resizable=1,menubar=0';
  442:         options += ',width=700,height=600';
  443:         stdeditbrowser = open(url,title,options,'1');
  444:         stdeditbrowser.focus();
  445:     }
  446: // ]]>
  447: </script>
  448: ENDSTDBRW
  449: }
  450: 
  451: sub resourcebrowser_javascript {
  452:    unless ($env{'request.course.id'}) { return ''; }
  453:    return (<<'ENDRESBRW');
  454: <script type="text/javascript" language="Javascript">
  455: // <![CDATA[
  456:     var reseditbrowser;
  457:     function openresbrowser(formname,reslink) {
  458:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  459:         var title = 'Resource_Browser';
  460:         var options = 'scrollbars=1,resizable=1,menubar=0';
  461:         options += ',width=700,height=500';
  462:         reseditbrowser = open(url,title,options,'1');
  463:         reseditbrowser.focus();
  464:     }
  465: // ]]>
  466: </script>
  467: ENDRESBRW
  468: }
  469: 
  470: sub selectstudent_link {
  471:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  472:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  473:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  474:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  475:    if ($env{'request.course.id'}) {  
  476:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  477: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  478: 					'/'.$env{'request.course.sec'})) {
  479: 	   return '';
  480:        }
  481:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  482:        if ($courseadvonly)  {
  483:            $callargs .= ",'',1,1";
  484:        }
  485:        return '<span class="LC_nobreak">'.
  486:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  487:               &mt('Select User').'</a></span>';
  488:    }
  489:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  490:        $callargs .= ",'',1"; 
  491:        return '<span class="LC_nobreak">'.
  492:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  493:               &mt('Select User').'</a></span>';
  494:    }
  495:    return '';
  496: }
  497: 
  498: sub selectresource_link {
  499:    my ($form,$reslink,$arg)=@_;
  500:    
  501:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  502:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  503:    unless ($env{'request.course.id'}) { return $arg; }
  504:    return '<span class="LC_nobreak">'.
  505:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  506:               $arg.'</a></span>';
  507: }
  508: 
  509: 
  510: 
  511: sub authorbrowser_javascript {
  512:     return <<"ENDAUTHORBRW";
  513: <script type="text/javascript" language="JavaScript">
  514: // <![CDATA[
  515: var stdeditbrowser;
  516: 
  517: function openauthorbrowser(formname,udom) {
  518:     var url = '/adm/pickauthor?';
  519:     url += 'form='+formname+'&roledom='+udom;
  520:     var title = 'Author_Browser';
  521:     var options = 'scrollbars=1,resizable=1,menubar=0';
  522:     options += ',width=700,height=600';
  523:     stdeditbrowser = open(url,title,options,'1');
  524:     stdeditbrowser.focus();
  525: }
  526: 
  527: // ]]>
  528: </script>
  529: ENDAUTHORBRW
  530: }
  531: 
  532: sub coursebrowser_javascript {
  533:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  534:         $credits_element) = @_;
  535:     my $wintitle = 'Course_Browser';
  536:     if ($crstype eq 'Community') {
  537:         $wintitle = 'Community_Browser';
  538:     }
  539:     my $id_functions = &javascript_index_functions();
  540:     my $output = '
  541: <script type="text/javascript" language="JavaScript">
  542: // <![CDATA[
  543:     var stdeditbrowser;'."\n";
  544: 
  545:     $output .= <<"ENDSTDBRW";
  546:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  547:         var url = '/adm/pickcourse?';
  548:         var formid = getFormIdByName(formname);
  549:         var domainfilter = getDomainFromSelectbox(formname,udom);
  550:         if (domainfilter != null) {
  551:            if (domainfilter != '') {
  552:                url += 'domainfilter='+domainfilter+'&';
  553: 	   }
  554:         }
  555:         url += 'form=' + formname + '&cnumelement='+uname+
  556: 	                            '&cdomelement='+udom+
  557:                                     '&cnameelement='+desc;
  558:         if (extra_element !=null && extra_element != '') {
  559:             if (formname == 'rolechoice' || formname == 'studentform') {
  560:                 url += '&roleelement='+extra_element;
  561:                 if (domainfilter == null || domainfilter == '') {
  562:                     url += '&domainfilter='+extra_element;
  563:                 }
  564:             }
  565:             else {
  566:                 if (formname == 'portform') {
  567:                     url += '&setroles='+extra_element;
  568:                 } else {
  569:                     if (formname == 'rules') {
  570:                         url += '&fixeddom='+extra_element; 
  571:                     }
  572:                 }
  573:             }     
  574:         }
  575:         if (type != null && type != '') {
  576:             url += '&type='+type;
  577:         }
  578:         if (type_elem != null && type_elem != '') {
  579:             url += '&typeelement='+type_elem;
  580:         }
  581:         if (formname == 'ccrs') {
  582:             var ownername = document.forms[formid].ccuname.value;
  583:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  584:             url += '&cloner='+ownername+':'+ownerdom;
  585:         }
  586:         if (multflag !=null && multflag != '') {
  587:             url += '&multiple='+multflag;
  588:         }
  589:         var title = '$wintitle';
  590:         var options = 'scrollbars=1,resizable=1,menubar=0';
  591:         options += ',width=700,height=600';
  592:         stdeditbrowser = open(url,title,options,'1');
  593:         stdeditbrowser.focus();
  594:     }
  595: $id_functions
  596: ENDSTDBRW
  597:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  598:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  599:                                       $credits_element);
  600:     }
  601:     $output .= '
  602: // ]]>
  603: </script>';
  604:     return $output;
  605: }
  606: 
  607: sub javascript_index_functions {
  608:     return <<"ENDJS";
  609: 
  610: function getFormIdByName(formname) {
  611:     for (var i=0;i<document.forms.length;i++) {
  612:         if (document.forms[i].name == formname) {
  613:             return i;
  614:         }
  615:     }
  616:     return -1;
  617: }
  618: 
  619: function getIndexByName(formid,item) {
  620:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  621:         if (document.forms[formid].elements[i].name == item) {
  622:             return i;
  623:         }
  624:     }
  625:     return -1;
  626: }
  627: 
  628: function getDomainFromSelectbox(formname,udom) {
  629:     var userdom;
  630:     var formid = getFormIdByName(formname);
  631:     if (formid > -1) {
  632:         var domid = getIndexByName(formid,udom);
  633:         if (domid > -1) {
  634:             if (document.forms[formid].elements[domid].type == 'select-one') {
  635:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  636:             }
  637:             if (document.forms[formid].elements[domid].type == 'hidden') {
  638:                 userdom=document.forms[formid].elements[domid].value;
  639:             }
  640:         }
  641:     }
  642:     return userdom;
  643: }
  644: 
  645: ENDJS
  646: 
  647: }
  648: 
  649: sub javascript_array_indexof {
  650:     return <<ENDJS;
  651: <script type="text/javascript" language="JavaScript">
  652: // <![CDATA[
  653: 
  654: if (!Array.prototype.indexOf) {
  655:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  656:         "use strict";
  657:         if (this === void 0 || this === null) {
  658:             throw new TypeError();
  659:         }
  660:         var t = Object(this);
  661:         var len = t.length >>> 0;
  662:         if (len === 0) {
  663:             return -1;
  664:         }
  665:         var n = 0;
  666:         if (arguments.length > 0) {
  667:             n = Number(arguments[1]);
  668:             if (n !== n) { // shortcut for verifying if it's NaN
  669:                 n = 0;
  670:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  671:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  672:             }
  673:         }
  674:         if (n >= len) {
  675:             return -1;
  676:         }
  677:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  678:         for (; k < len; k++) {
  679:             if (k in t && t[k] === searchElement) {
  680:                 return k;
  681:             }
  682:         }
  683:         return -1;
  684:     }
  685: }
  686: 
  687: // ]]>
  688: </script>
  689: 
  690: ENDJS
  691: 
  692: }
  693: 
  694: sub userbrowser_javascript {
  695:     my $id_functions = &javascript_index_functions();
  696:     return <<"ENDUSERBRW";
  697: 
  698: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  699:     var url = '/adm/pickuser?';
  700:     var userdom = getDomainFromSelectbox(formname,udom);
  701:     if (userdom != null) {
  702:        if (userdom != '') {
  703:            url += 'srchdom='+userdom+'&';
  704:        }
  705:     }
  706:     url += 'form=' + formname + '&unameelement='+uname+
  707:                                 '&udomelement='+udom+
  708:                                 '&ulastelement='+ulast+
  709:                                 '&ufirstelement='+ufirst+
  710:                                 '&uemailelement='+uemail+
  711:                                 '&hideudomelement='+hideudom+
  712:                                 '&coursedom='+crsdom;
  713:     if ((caller != null) && (caller != undefined)) {
  714:         url += '&caller='+caller;
  715:     }
  716:     var title = 'User_Browser';
  717:     var options = 'scrollbars=1,resizable=1,menubar=0';
  718:     options += ',width=700,height=600';
  719:     var stdeditbrowser = open(url,title,options,'1');
  720:     stdeditbrowser.focus();
  721: }
  722: 
  723: function fix_domain (formname,udom,origdom,uname) {
  724:     var formid = getFormIdByName(formname);
  725:     if (formid > -1) {
  726:         var unameid = getIndexByName(formid,uname);
  727:         var domid = getIndexByName(formid,udom);
  728:         var hidedomid = getIndexByName(formid,origdom);
  729:         if (hidedomid > -1) {
  730:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  731:             var unameval = document.forms[formid].elements[unameid].value;
  732:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  733:                 if (domid > -1) {
  734:                     var slct = document.forms[formid].elements[domid];
  735:                     if (slct.type == 'select-one') {
  736:                         var i;
  737:                         for (i=0;i<slct.length;i++) {
  738:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  739:                         }
  740:                     }
  741:                     if (slct.type == 'hidden') {
  742:                         slct.value = fixeddom;
  743:                     }
  744:                 }
  745:             }
  746:         }
  747:     }
  748:     return;
  749: }
  750: 
  751: $id_functions
  752: ENDUSERBRW
  753: }
  754: 
  755: sub setsec_javascript {
  756:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  757:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  758:         $communityrolestr);
  759:     if ($role_element ne '') {
  760:         my @allroles = ('st','ta','ep','in','ad');
  761:         foreach my $crstype ('Course','Community') {
  762:             if ($crstype eq 'Community') {
  763:                 foreach my $role (@allroles) {
  764:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  765:                 }
  766:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  767:             } else {
  768:                 foreach my $role (@allroles) {
  769:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  770:                 }
  771:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  772:             }
  773:         }
  774:         $rolestr = '"'.join('","',@allroles).'"';
  775:         $courserolestr = '"'.join('","',@courserolenames).'"';
  776:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  777:     }
  778:     my $setsections = qq|
  779: function setSect(sectionlist) {
  780:     var sectionsArray = new Array();
  781:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  782:         sectionsArray = sectionlist.split(",");
  783:     }
  784:     var numSections = sectionsArray.length;
  785:     document.$formname.$sec_element.length = 0;
  786:     if (numSections == 0) {
  787:         document.$formname.$sec_element.multiple=false;
  788:         document.$formname.$sec_element.size=1;
  789:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  790:     } else {
  791:         if (numSections == 1) {
  792:             document.$formname.$sec_element.multiple=false;
  793:             document.$formname.$sec_element.size=1;
  794:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  795:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  796:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  797:         } else {
  798:             for (var i=0; i<numSections; i++) {
  799:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  800:             }
  801:             document.$formname.$sec_element.multiple=true
  802:             if (numSections < 3) {
  803:                 document.$formname.$sec_element.size=numSections;
  804:             } else {
  805:                 document.$formname.$sec_element.size=3;
  806:             }
  807:             document.$formname.$sec_element.options[0].selected = false
  808:         }
  809:     }
  810: }
  811: 
  812: function setRole(crstype) {
  813: |;
  814:     if ($role_element eq '') {
  815:         $setsections .= '    return;
  816: }
  817: ';
  818:     } else {
  819:         $setsections .= qq|
  820:     var elementLength = document.$formname.$role_element.length;
  821:     var allroles = Array($rolestr);
  822:     var courserolenames = Array($courserolestr);
  823:     var communityrolenames = Array($communityrolestr);
  824:     if (elementLength != undefined) {
  825:         if (document.$formname.$role_element.options[5].value == 'cc') {
  826:             if (crstype == 'Course') {
  827:                 return;
  828:             } else {
  829:                 allroles[5] = 'co';
  830:                 for (var i=0; i<6; i++) {
  831:                     document.$formname.$role_element.options[i].value = allroles[i];
  832:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  833:                 }
  834:             }
  835:         } else {
  836:             if (crstype == 'Community') {
  837:                 return;
  838:             } else {
  839:                 allroles[5] = 'cc';
  840:                 for (var i=0; i<6; i++) {
  841:                     document.$formname.$role_element.options[i].value = allroles[i];
  842:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  843:                 }
  844:             }
  845:         }
  846:     }
  847:     return;
  848: }
  849: |;
  850:     }
  851:     if ($credits_element) {
  852:         $setsections .= qq|
  853: function setCredits(defaultcredits) {
  854:     document.$formname.$credits_element.value = defaultcredits;
  855:     return;
  856: }
  857: |;
  858:     }
  859:     return $setsections;
  860: }
  861: 
  862: sub selectcourse_link {
  863:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  864:        $typeelement) = @_;
  865:    my $type = $selecttype;
  866:    my $linktext = &mt('Select Course');
  867:    if ($selecttype eq 'Community') {
  868:        $linktext = &mt('Select Community');
  869:    } elsif ($selecttype eq 'Course/Community') {
  870:        $linktext = &mt('Select Course/Community');
  871:        $type = '';
  872:    } elsif ($selecttype eq 'Select') {
  873:        $linktext = &mt('Select');
  874:        $type = '';
  875:    }
  876:    return '<span class="LC_nobreak">'
  877:          ."<a href='"
  878:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  879:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  880:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  881:          ."'>".$linktext.'</a>'
  882:          .'</span>';
  883: }
  884: 
  885: sub selectauthor_link {
  886:    my ($form,$udom)=@_;
  887:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  888:           &mt('Select Author').'</a>';
  889: }
  890: 
  891: sub selectuser_link {
  892:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  893:         $coursedom,$linktext,$caller) = @_;
  894:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  895:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  896:            ');">'.$linktext.'</a>';
  897: }
  898: 
  899: sub check_uncheck_jscript {
  900:     my $jscript = <<"ENDSCRT";
  901: function checkAll(field) {
  902:     if (field.length > 0) {
  903:         for (i = 0; i < field.length; i++) {
  904:             if (!field[i].disabled) {
  905:                 field[i].checked = true;
  906:             }
  907:         }
  908:     } else {
  909:         if (!field.disabled) {
  910:             field.checked = true;
  911:         }
  912:     }
  913: }
  914:  
  915: function uncheckAll(field) {
  916:     if (field.length > 0) {
  917:         for (i = 0; i < field.length; i++) {
  918:             field[i].checked = false ;
  919:         }
  920:     } else {
  921:         field.checked = false ;
  922:     }
  923: }
  924: ENDSCRT
  925:     return $jscript;
  926: }
  927: 
  928: sub select_timezone {
  929:    my ($name,$selected,$onchange,$includeempty)=@_;
  930:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  931:    if ($includeempty) {
  932:        $output .= '<option value=""';
  933:        if (($selected eq '') || ($selected eq 'local')) {
  934:            $output .= ' selected="selected" ';
  935:        }
  936:        $output .= '> </option>';
  937:    }
  938:    my @timezones = DateTime::TimeZone->all_names;
  939:    foreach my $tzone (@timezones) {
  940:        $output.= '<option value="'.$tzone.'"';
  941:        if ($tzone eq $selected) {
  942:            $output.=' selected="selected"';
  943:        }
  944:        $output.=">$tzone</option>\n";
  945:    }
  946:    $output.="</select>";
  947:    return $output;
  948: }
  949: 
  950: sub select_datelocale {
  951:     my ($name,$selected,$onchange,$includeempty)=@_;
  952:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  953:     if ($includeempty) {
  954:         $output .= '<option value=""';
  955:         if ($selected eq '') {
  956:             $output .= ' selected="selected" ';
  957:         }
  958:         $output .= '> </option>';
  959:     }
  960:     my (@possibles,%locale_names);
  961:     my @locales = DateTime::Locale::Catalog::Locales;
  962:     foreach my $locale (@locales) {
  963:         if (ref($locale) eq 'HASH') {
  964:             my $id = $locale->{'id'};
  965:             if ($id ne '') {
  966:                 my $en_terr = $locale->{'en_territory'};
  967:                 my $native_terr = $locale->{'native_territory'};
  968:                 my @languages = &Apache::lonlocal::preferred_languages();
  969:                 if (grep(/^en$/,@languages) || !@languages) {
  970:                     if ($en_terr ne '') {
  971:                         $locale_names{$id} = '('.$en_terr.')';
  972:                     } elsif ($native_terr ne '') {
  973:                         $locale_names{$id} = $native_terr;
  974:                     }
  975:                 } else {
  976:                     if ($native_terr ne '') {
  977:                         $locale_names{$id} = $native_terr.' ';
  978:                     } elsif ($en_terr ne '') {
  979:                         $locale_names{$id} = '('.$en_terr.')';
  980:                     }
  981:                 }
  982:                 push (@possibles,$id);
  983:             }
  984:         }
  985:     }
  986:     foreach my $item (sort(@possibles)) {
  987:         $output.= '<option value="'.$item.'"';
  988:         if ($item eq $selected) {
  989:             $output.=' selected="selected"';
  990:         }
  991:         $output.=">$item";
  992:         if ($locale_names{$item} ne '') {
  993:             $output.="  $locale_names{$item}</option>\n";
  994:         }
  995:         $output.="</option>\n";
  996:     }
  997:     $output.="</select>";
  998:     return $output;
  999: }
 1000: 
 1001: sub select_language {
 1002:     my ($name,$selected,$includeempty) = @_;
 1003:     my %langchoices;
 1004:     if ($includeempty) {
 1005:         %langchoices = ('' => 'No language preference');
 1006:     }
 1007:     foreach my $id (&languageids()) {
 1008:         my $code = &supportedlanguagecode($id);
 1009:         if ($code) {
 1010:             $langchoices{$code} = &plainlanguagedescription($id);
 1011:         }
 1012:     }
 1013:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1014:     return &select_form($selected,$name,\%langchoices);
 1015: }
 1016: 
 1017: =pod
 1018: 
 1019: =item * &linked_select_forms(...)
 1020: 
 1021: linked_select_forms returns a string containing a <script></script> block
 1022: and html for two <select> menus.  The select menus will be linked in that
 1023: changing the value of the first menu will result in new values being placed
 1024: in the second menu.  The values in the select menu will appear in alphabetical
 1025: order unless a defined order is provided.
 1026: 
 1027: linked_select_forms takes the following ordered inputs:
 1028: 
 1029: =over 4
 1030: 
 1031: =item * $formname, the name of the <form> tag
 1032: 
 1033: =item * $middletext, the text which appears between the <select> tags
 1034: 
 1035: =item * $firstdefault, the default value for the first menu
 1036: 
 1037: =item * $firstselectname, the name of the first <select> tag
 1038: 
 1039: =item * $secondselectname, the name of the second <select> tag
 1040: 
 1041: =item * $hashref, a reference to a hash containing the data for the menus.
 1042: 
 1043: =item * $menuorder, the order of values in the first menu
 1044: 
 1045: =item * $onchangefirst, additional javascript call to execute for an onchange
 1046:         event for the first <select> tag
 1047: 
 1048: =item * $onchangesecond, additional javascript call to execute for an onchange
 1049:         event for the second <select> tag
 1050: 
 1051: =back 
 1052: 
 1053: Below is an example of such a hash.  Only the 'text', 'default', and 
 1054: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1055: values for the first select menu.  The text that coincides with the 
 1056: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1057: and text for the second menu are given in the hash pointed to by 
 1058: $menu{$choice1}->{'select2'}.  
 1059: 
 1060:  my %menu = ( A1 => { text =>"Choice A1" ,
 1061:                        default => "B3",
 1062:                        select2 => { 
 1063:                            B1 => "Choice B1",
 1064:                            B2 => "Choice B2",
 1065:                            B3 => "Choice B3",
 1066:                            B4 => "Choice B4"
 1067:                            },
 1068:                        order => ['B4','B3','B1','B2'],
 1069:                    },
 1070:                A2 => { text =>"Choice A2" ,
 1071:                        default => "C2",
 1072:                        select2 => { 
 1073:                            C1 => "Choice C1",
 1074:                            C2 => "Choice C2",
 1075:                            C3 => "Choice C3"
 1076:                            },
 1077:                        order => ['C2','C1','C3'],
 1078:                    },
 1079:                A3 => { text =>"Choice A3" ,
 1080:                        default => "D6",
 1081:                        select2 => { 
 1082:                            D1 => "Choice D1",
 1083:                            D2 => "Choice D2",
 1084:                            D3 => "Choice D3",
 1085:                            D4 => "Choice D4",
 1086:                            D5 => "Choice D5",
 1087:                            D6 => "Choice D6",
 1088:                            D7 => "Choice D7"
 1089:                            },
 1090:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1091:                    }
 1092:                );
 1093: 
 1094: =cut
 1095: 
 1096: sub linked_select_forms {
 1097:     my ($formname,
 1098:         $middletext,
 1099:         $firstdefault,
 1100:         $firstselectname,
 1101:         $secondselectname, 
 1102:         $hashref,
 1103:         $menuorder,
 1104:         $onchangefirst,
 1105:         $onchangesecond
 1106:         ) = @_;
 1107:     my $second = "document.$formname.$secondselectname";
 1108:     my $first = "document.$formname.$firstselectname";
 1109:     # output the javascript to do the changing
 1110:     my $result = '';
 1111:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1112:     $result.="// <![CDATA[\n";
 1113:     $result.="var select2data = new Object();\n";
 1114:     $" = '","';
 1115:     my $debug = '';
 1116:     foreach my $s1 (sort(keys(%$hashref))) {
 1117:         $result.="select2data.d_$s1 = new Object();\n";        
 1118:         $result.="select2data.d_$s1.def = new String('".
 1119:             $hashref->{$s1}->{'default'}."');\n";
 1120:         $result.="select2data.d_$s1.values = new Array(";
 1121:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1122:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1123:             @s2values = @{$hashref->{$s1}->{'order'}};
 1124:         }
 1125:         $result.="\"@s2values\");\n";
 1126:         $result.="select2data.d_$s1.texts = new Array(";        
 1127:         my @s2texts;
 1128:         foreach my $value (@s2values) {
 1129:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1130:         }
 1131:         $result.="\"@s2texts\");\n";
 1132:     }
 1133:     $"=' ';
 1134:     $result.= <<"END";
 1135: 
 1136: function select1_changed() {
 1137:     // Determine new choice
 1138:     var newvalue = "d_" + $first.value;
 1139:     // update select2
 1140:     var values     = select2data[newvalue].values;
 1141:     var texts      = select2data[newvalue].texts;
 1142:     var select2def = select2data[newvalue].def;
 1143:     var i;
 1144:     // out with the old
 1145:     for (i = 0; i < $second.options.length; i++) {
 1146:         $second.options[i] = null;
 1147:     }
 1148:     // in with the nuclear
 1149:     for (i=0;i<values.length; i++) {
 1150:         $second.options[i] = new Option(values[i]);
 1151:         $second.options[i].value = values[i];
 1152:         $second.options[i].text = texts[i];
 1153:         if (values[i] == select2def) {
 1154:             $second.options[i].selected = true;
 1155:         }
 1156:     }
 1157: }
 1158: // ]]>
 1159: </script>
 1160: END
 1161:     # output the initial values for the selection lists
 1162:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1163:     my @order = sort(keys(%{$hashref}));
 1164:     if (ref($menuorder) eq 'ARRAY') {
 1165:         @order = @{$menuorder};
 1166:     }
 1167:     foreach my $value (@order) {
 1168:         $result.="    <option value=\"$value\" ";
 1169:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1170:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1171:     }
 1172:     $result .= "</select>\n";
 1173:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1174:     $result .= $middletext;
 1175:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1176:     if ($onchangesecond) {
 1177:         $result .= ' onchange="'.$onchangesecond.'"';
 1178:     }
 1179:     $result .= ">\n";
 1180:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1181:     
 1182:     my @secondorder = sort(keys(%select2));
 1183:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1184:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1185:     }
 1186:     foreach my $value (@secondorder) {
 1187:         $result.="    <option value=\"$value\" ";        
 1188:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1189:         $result.=">".&mt($select2{$value})."</option>\n";
 1190:     }
 1191:     $result .= "</select>\n";
 1192:     #    return $debug;
 1193:     return $result;
 1194: }   #  end of sub linked_select_forms {
 1195: 
 1196: =pod
 1197: 
 1198: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1199: 
 1200: Returns a string corresponding to an HTML link to the given help
 1201: $topic, where $topic corresponds to the name of a .tex file in
 1202: /home/httpd/html/adm/help/tex, with underscores replaced by
 1203: spaces. 
 1204: 
 1205: $text will optionally be linked to the same topic, allowing you to
 1206: link text in addition to the graphic. If you do not want to link
 1207: text, but wish to specify one of the later parameters, pass an
 1208: empty string. 
 1209: 
 1210: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1211: the link will not open a new window. If false, the link will open
 1212: a new window using Javascript. (Default is false.) 
 1213: 
 1214: $width and $height are optional numerical parameters that will
 1215: override the width and height of the popped up window, which may
 1216: be useful for certain help topics with big pictures included.
 1217: 
 1218: $imgid is the id of the img tag used for the help icon. This may be
 1219: used in a javascript call to switch the image src.  See 
 1220: lonhtmlcommon::htmlareaselectactive() for an example.
 1221: 
 1222: =cut
 1223: 
 1224: sub help_open_topic {
 1225:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1226:     $text = "" if (not defined $text);
 1227:     $stayOnPage = 0 if (not defined $stayOnPage);
 1228:     $width = 500 if (not defined $width);
 1229:     $height = 400 if (not defined $height);
 1230:     my $filename = $topic;
 1231:     $filename =~ s/ /_/g;
 1232: 
 1233:     my $template = "";
 1234:     my $link;
 1235:     
 1236:     $topic=~s/\W/\_/g;
 1237: 
 1238:     if (!$stayOnPage) {
 1239:         if ($env{'browser.mobile'}) {
 1240: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1241:         } else {
 1242:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1243:         }
 1244:     } elsif ($stayOnPage eq 'popup') {
 1245:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1246:     } else {
 1247: 	$link = "/adm/help/${filename}.hlp";
 1248:     }
 1249: 
 1250:     # Add the text
 1251:     if ($text ne "") {	
 1252: 	$template.='<span class="LC_help_open_topic">'
 1253:                   .'<a target="_top" href="'.$link.'">'
 1254:                   .$text.'</a>';
 1255:     }
 1256: 
 1257:     # (Always) Add the graphic
 1258:     my $title = &mt('Online Help');
 1259:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1260:     if ($imgid ne '') {
 1261:         $imgid = ' id="'.$imgid.'"';
 1262:     }
 1263:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1264:               .'<img src="'.$helpicon.'" border="0"'
 1265:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1266:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1267:               .' /></a>';
 1268:     if ($text ne "") {	
 1269:         $template.='</span>';
 1270:     }
 1271:     return $template;
 1272: 
 1273: }
 1274: 
 1275: # This is a quicky function for Latex cheatsheet editing, since it 
 1276: # appears in at least four places
 1277: sub helpLatexCheatsheet {
 1278:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1279:     my $out;
 1280:     my $addOther = '';
 1281:     if ($topic) {
 1282: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1283:     }
 1284:     $out = '<span>' # Start cheatsheet
 1285: 	  .$addOther
 1286:           .'<span>'
 1287: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1288: 	  .'</span> <span>'
 1289: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1290: 	  .'</span>';
 1291:     unless ($not_author) {
 1292:         $out .= ' <span>'
 1293: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1294: 	       .'</span>';
 1295:     }
 1296:     $out .= '</span>'; # End cheatsheet
 1297:     return $out;
 1298: }
 1299: 
 1300: sub general_help {
 1301:     my $helptopic='Student_Intro';
 1302:     if ($env{'request.role'}=~/^(ca|au)/) {
 1303: 	$helptopic='Authoring_Intro';
 1304:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1305: 	$helptopic='Course_Coordination_Intro';
 1306:     } elsif ($env{'request.role'}=~/^dc/) {
 1307:         $helptopic='Domain_Coordination_Intro';
 1308:     }
 1309:     return $helptopic;
 1310: }
 1311: 
 1312: sub update_help_link {
 1313:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1314:     my $origurl = $ENV{'REQUEST_URI'};
 1315:     $origurl=~s|^/~|/priv/|;
 1316:     my $timestamp = time;
 1317:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1318:         $$datum = &escape($$datum);
 1319:     }
 1320: 
 1321:     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";
 1322:     my $output .= <<"ENDOUTPUT";
 1323: <script type="text/javascript">
 1324: // <![CDATA[
 1325: banner_link = '$banner_link';
 1326: // ]]>
 1327: </script>
 1328: ENDOUTPUT
 1329:     return $output;
 1330: }
 1331: 
 1332: # now just updates the help link and generates a blue icon
 1333: sub help_open_menu {
 1334:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1335: 	= @_;    
 1336:     $stayOnPage = 1;
 1337:     my $output;
 1338:     if ($component_help) {
 1339: 	if (!$text) {
 1340: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1341: 				       $width,$height);
 1342: 	} else {
 1343: 	    my $help_text;
 1344: 	    $help_text=&unescape($topic);
 1345: 	    $output='<table><tr><td>'.
 1346: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1347: 				 $width,$height).'</td></tr></table>';
 1348: 	}
 1349:     }
 1350:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1351:     return $output.$banner_link;
 1352: }
 1353: 
 1354: sub top_nav_help {
 1355:     my ($text) = @_;
 1356:     $text = &mt($text);
 1357:     my $stay_on_page;
 1358:     unless ($env{'environment.remote'} eq 'on') {
 1359:         $stay_on_page = 1;
 1360:     }
 1361:     my ($link,$banner_link);
 1362:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1363:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1364: 	                         : "javascript:helpMenu('open')";
 1365:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1366:     }
 1367:     my $title = &mt('Get help');
 1368:     if ($link) {
 1369:         return <<"END";
 1370: $banner_link
 1371: <a href="$link" title="$title">$text</a>
 1372: END
 1373:     } else {
 1374:         return '&nbsp;'.$text.'&nbsp;';
 1375:     }
 1376: }
 1377: 
 1378: sub help_menu_js {
 1379:     my ($httphost) = @_;
 1380:     my $stayOnPage = 1;
 1381:     my $width = 620;
 1382:     my $height = 600;
 1383:     my $helptopic=&general_help();
 1384:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1385:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1386:     my $start_page =
 1387:         &Apache::loncommon::start_page('Help Menu', undef,
 1388: 				       {'frameset'    => 1,
 1389: 					'js_ready'    => 1,
 1390:                                         'use_absolute' => $httphost, 
 1391: 					'add_entries' => {
 1392: 					    'border' => '0',
 1393: 					    'rows'   => "110,*",},});
 1394:     my $end_page =
 1395:         &Apache::loncommon::end_page({'frameset' => 1,
 1396: 				      'js_ready' => 1,});
 1397: 
 1398:     my $template .= <<"ENDTEMPLATE";
 1399: <script type="text/javascript">
 1400: // <![CDATA[
 1401: // <!-- BEGIN LON-CAPA Internal
 1402: var banner_link = '';
 1403: function helpMenu(target) {
 1404:     var caller = this;
 1405:     if (target == 'open') {
 1406:         var newWindow = null;
 1407:         try {
 1408:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1409:         }
 1410:         catch(error) {
 1411:             writeHelp(caller);
 1412:             return;
 1413:         }
 1414:         if (newWindow) {
 1415:             caller = newWindow;
 1416:         }
 1417:     }
 1418:     writeHelp(caller);
 1419:     return;
 1420: }
 1421: function writeHelp(caller) {
 1422:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1423:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1424:     caller.document.close();
 1425:     caller.focus();
 1426: }
 1427: // END LON-CAPA Internal -->
 1428: // ]]>
 1429: </script>
 1430: ENDTEMPLATE
 1431:     return $template;
 1432: }
 1433: 
 1434: sub help_open_bug {
 1435:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1436:     unless ($env{'user.adv'}) { return ''; }
 1437:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1438:     $text = "" if (not defined $text);
 1439: 	$stayOnPage=1;
 1440:     $width = 600 if (not defined $width);
 1441:     $height = 600 if (not defined $height);
 1442: 
 1443:     $topic=~s/\W+/\+/g;
 1444:     my $link='';
 1445:     my $template='';
 1446:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1447: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1448:     if (!$stayOnPage)
 1449:     {
 1450: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1451:     }
 1452:     else
 1453:     {
 1454: 	$link = $url;
 1455:     }
 1456:     # Add the text
 1457:     if ($text ne "")
 1458:     {
 1459: 	$template .= 
 1460:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1461:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1462:     }
 1463: 
 1464:     # Add the graphic
 1465:     my $title = &mt('Report a Bug');
 1466:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1467:     $template .= <<"ENDTEMPLATE";
 1468:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1469: ENDTEMPLATE
 1470:     if ($text ne '') { $template.='</td></tr></table>' };
 1471:     return $template;
 1472: 
 1473: }
 1474: 
 1475: sub help_open_faq {
 1476:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1477:     unless ($env{'user.adv'}) { return ''; }
 1478:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1479:     $text = "" if (not defined $text);
 1480: 	$stayOnPage=1;
 1481:     $width = 350 if (not defined $width);
 1482:     $height = 400 if (not defined $height);
 1483: 
 1484:     $topic=~s/\W+/\+/g;
 1485:     my $link='';
 1486:     my $template='';
 1487:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1488:     if (!$stayOnPage)
 1489:     {
 1490: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1491:     }
 1492:     else
 1493:     {
 1494: 	$link = $url;
 1495:     }
 1496: 
 1497:     # Add the text
 1498:     if ($text ne "")
 1499:     {
 1500: 	$template .= 
 1501:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1502:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1503:     }
 1504: 
 1505:     # Add the graphic
 1506:     my $title = &mt('View the FAQ');
 1507:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1508:     $template .= <<"ENDTEMPLATE";
 1509:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1510: ENDTEMPLATE
 1511:     if ($text ne '') { $template.='</td></tr></table>' };
 1512:     return $template;
 1513: 
 1514: }
 1515: 
 1516: ###############################################################
 1517: ###############################################################
 1518: 
 1519: =pod
 1520: 
 1521: =item * &change_content_javascript():
 1522: 
 1523: This and the next function allow you to create small sections of an
 1524: otherwise static HTML page that you can update on the fly with
 1525: Javascript, even in Netscape 4.
 1526: 
 1527: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1528: must be written to the HTML page once. It will prove the Javascript
 1529: function "change(name, content)". Calling the change function with the
 1530: name of the section 
 1531: you want to update, matching the name passed to C<changable_area>, and
 1532: the new content you want to put in there, will put the content into
 1533: that area.
 1534: 
 1535: B<Note>: Netscape 4 only reserves enough space for the changable area
 1536: to contain room for the original contents. You need to "make space"
 1537: for whatever changes you wish to make, and be B<sure> to check your
 1538: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1539: it's adequate for updating a one-line status display, but little more.
 1540: This script will set the space to 100% width, so you only need to
 1541: worry about height in Netscape 4.
 1542: 
 1543: Modern browsers are much less limiting, and if you can commit to the
 1544: user not using Netscape 4, this feature may be used freely with
 1545: pretty much any HTML.
 1546: 
 1547: =cut
 1548: 
 1549: sub change_content_javascript {
 1550:     # If we're on Netscape 4, we need to use Layer-based code
 1551:     if ($env{'browser.type'} eq 'netscape' &&
 1552: 	$env{'browser.version'} =~ /^4\./) {
 1553: 	return (<<NETSCAPE4);
 1554: 	function change(name, content) {
 1555: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1556: 	    doc.open();
 1557: 	    doc.write(content);
 1558: 	    doc.close();
 1559: 	}
 1560: NETSCAPE4
 1561:     } else {
 1562: 	# Otherwise, we need to use semi-standards-compliant code
 1563: 	# (technically, "innerHTML" isn't standard but the equivalent
 1564: 	# is really scary, and every useful browser supports it
 1565: 	return (<<DOMBASED);
 1566: 	function change(name, content) {
 1567: 	    element = document.getElementById(name);
 1568: 	    element.innerHTML = content;
 1569: 	}
 1570: DOMBASED
 1571:     }
 1572: }
 1573: 
 1574: =pod
 1575: 
 1576: =item * &changable_area($name,$origContent):
 1577: 
 1578: This provides a "changable area" that can be modified on the fly via
 1579: the Javascript code provided in C<change_content_javascript>. $name is
 1580: the name you will use to reference the area later; do not repeat the
 1581: same name on a given HTML page more then once. $origContent is what
 1582: the area will originally contain, which can be left blank.
 1583: 
 1584: =cut
 1585: 
 1586: sub changable_area {
 1587:     my ($name, $origContent) = @_;
 1588: 
 1589:     if ($env{'browser.type'} eq 'netscape' &&
 1590: 	$env{'browser.version'} =~ /^4\./) {
 1591: 	# If this is netscape 4, we need to use the Layer tag
 1592: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1593:     } else {
 1594: 	return "<span id='$name'>$origContent</span>";
 1595:     }
 1596: }
 1597: 
 1598: =pod
 1599: 
 1600: =item * &viewport_geometry_js 
 1601: 
 1602: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1603: 
 1604: =cut
 1605: 
 1606: 
 1607: sub viewport_geometry_js { 
 1608:     return <<"GEOMETRY";
 1609: var Geometry = {};
 1610: function init_geometry() {
 1611:     if (Geometry.init) { return };
 1612:     Geometry.init=1;
 1613:     if (window.innerHeight) {
 1614:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1615:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1616:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1617:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1618:     }
 1619:     else if (document.documentElement && document.documentElement.clientHeight) {
 1620:         Geometry.getViewportHeight =
 1621:             function() { return document.documentElement.clientHeight; };
 1622:         Geometry.getViewportWidth =
 1623:             function() { return document.documentElement.clientWidth; };
 1624: 
 1625:         Geometry.getHorizontalScroll =
 1626:             function() { return document.documentElement.scrollLeft; };
 1627:         Geometry.getVerticalScroll =
 1628:             function() { return document.documentElement.scrollTop; };
 1629:     }
 1630:     else if (document.body.clientHeight) {
 1631:         Geometry.getViewportHeight =
 1632:             function() { return document.body.clientHeight; };
 1633:         Geometry.getViewportWidth =
 1634:             function() { return document.body.clientWidth; };
 1635:         Geometry.getHorizontalScroll =
 1636:             function() { return document.body.scrollLeft; };
 1637:         Geometry.getVerticalScroll =
 1638:             function() { return document.body.scrollTop; };
 1639:     }
 1640: }
 1641: 
 1642: GEOMETRY
 1643: }
 1644: 
 1645: =pod
 1646: 
 1647: =item * &viewport_size_js()
 1648: 
 1649: 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. 
 1650: 
 1651: =cut
 1652: 
 1653: sub viewport_size_js {
 1654:     my $geometry = &viewport_geometry_js();
 1655:     return <<"DIMS";
 1656: 
 1657: $geometry
 1658: 
 1659: function getViewportDims(width,height) {
 1660:     init_geometry();
 1661:     width.value = Geometry.getViewportWidth();
 1662:     height.value = Geometry.getViewportHeight();
 1663:     return;
 1664: }
 1665: 
 1666: DIMS
 1667: }
 1668: 
 1669: =pod
 1670: 
 1671: =item * &resize_textarea_js()
 1672: 
 1673: emits the needed javascript to resize a textarea to be as big as possible
 1674: 
 1675: creates a function resize_textrea that takes two IDs first should be
 1676: the id of the element to resize, second should be the id of a div that
 1677: surrounds everything that comes after the textarea, this routine needs
 1678: to be attached to the <body> for the onload and onresize events.
 1679: 
 1680: =back
 1681: 
 1682: =cut
 1683: 
 1684: sub resize_textarea_js {
 1685:     my $geometry = &viewport_geometry_js();
 1686:     return <<"RESIZE";
 1687:     <script type="text/javascript">
 1688: // <![CDATA[
 1689: $geometry
 1690: 
 1691: function getX(element) {
 1692:     var x = 0;
 1693:     while (element) {
 1694: 	x += element.offsetLeft;
 1695: 	element = element.offsetParent;
 1696:     }
 1697:     return x;
 1698: }
 1699: function getY(element) {
 1700:     var y = 0;
 1701:     while (element) {
 1702: 	y += element.offsetTop;
 1703: 	element = element.offsetParent;
 1704:     }
 1705:     return y;
 1706: }
 1707: 
 1708: 
 1709: function resize_textarea(textarea_id,bottom_id) {
 1710:     init_geometry();
 1711:     var textarea        = document.getElementById(textarea_id);
 1712:     //alert(textarea);
 1713: 
 1714:     var textarea_top    = getY(textarea);
 1715:     var textarea_height = textarea.offsetHeight;
 1716:     var bottom          = document.getElementById(bottom_id);
 1717:     var bottom_top      = getY(bottom);
 1718:     var bottom_height   = bottom.offsetHeight;
 1719:     var window_height   = Geometry.getViewportHeight();
 1720:     var fudge           = 23;
 1721:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1722:     if (new_height < 300) {
 1723: 	new_height = 300;
 1724:     }
 1725:     textarea.style.height=new_height+'px';
 1726: }
 1727: // ]]>
 1728: </script>
 1729: RESIZE
 1730: 
 1731: }
 1732: 
 1733: =pod
 1734: 
 1735: =head1 Excel and CSV file utility routines
 1736: 
 1737: =cut
 1738: 
 1739: ###############################################################
 1740: ###############################################################
 1741: 
 1742: =pod
 1743: 
 1744: =over 4
 1745: 
 1746: =item * &csv_translate($text) 
 1747: 
 1748: Translate $text to allow it to be output as a 'comma separated values' 
 1749: format.
 1750: 
 1751: =cut
 1752: 
 1753: ###############################################################
 1754: ###############################################################
 1755: sub csv_translate {
 1756:     my $text = shift;
 1757:     $text =~ s/\"/\"\"/g;
 1758:     $text =~ s/\n/ /g;
 1759:     return $text;
 1760: }
 1761: 
 1762: ###############################################################
 1763: ###############################################################
 1764: 
 1765: =pod
 1766: 
 1767: =item * &define_excel_formats()
 1768: 
 1769: Define some commonly used Excel cell formats.
 1770: 
 1771: Currently supported formats:
 1772: 
 1773: =over 4
 1774: 
 1775: =item header
 1776: 
 1777: =item bold
 1778: 
 1779: =item h1
 1780: 
 1781: =item h2
 1782: 
 1783: =item h3
 1784: 
 1785: =item h4
 1786: 
 1787: =item i
 1788: 
 1789: =item date
 1790: 
 1791: =back
 1792: 
 1793: Inputs: $workbook
 1794: 
 1795: Returns: $format, a hash reference.
 1796: 
 1797: 
 1798: =cut
 1799: 
 1800: ###############################################################
 1801: ###############################################################
 1802: sub define_excel_formats {
 1803:     my ($workbook) = @_;
 1804:     my $format;
 1805:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1806:                                                 bottom    => 1,
 1807:                                                 align     => 'center');
 1808:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1809:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1810:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1811:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1812:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1813:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1814:     $format->{'date'} = $workbook->add_format(num_format=>
 1815:                                             'mm/dd/yyyy hh:mm:ss');
 1816:     return $format;
 1817: }
 1818: 
 1819: ###############################################################
 1820: ###############################################################
 1821: 
 1822: =pod
 1823: 
 1824: =item * &create_workbook()
 1825: 
 1826: Create an Excel worksheet.  If it fails, output message on the
 1827: request object and return undefs.
 1828: 
 1829: Inputs: Apache request object
 1830: 
 1831: Returns (undef) on failure, 
 1832:     Excel worksheet object, scalar with filename, and formats 
 1833:     from &Apache::loncommon::define_excel_formats on success
 1834: 
 1835: =cut
 1836: 
 1837: ###############################################################
 1838: ###############################################################
 1839: sub create_workbook {
 1840:     my ($r) = @_;
 1841:         #
 1842:     # Create the excel spreadsheet
 1843:     my $filename = '/prtspool/'.
 1844:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1845:         time.'_'.rand(1000000000).'.xls';
 1846:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1847:     if (! defined($workbook)) {
 1848:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1849:         $r->print(
 1850:             '<p class="LC_error">'
 1851:            .&mt('Problems occurred in creating the new Excel file.')
 1852:            .' '.&mt('This error has been logged.')
 1853:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1854:            .'</p>'
 1855:         );
 1856:         return (undef);
 1857:     }
 1858:     #
 1859:     $workbook->set_tempdir(LONCAPA::tempdir());
 1860:     #
 1861:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1862:     return ($workbook,$filename,$format);
 1863: }
 1864: 
 1865: ###############################################################
 1866: ###############################################################
 1867: 
 1868: =pod
 1869: 
 1870: =item * &create_text_file()
 1871: 
 1872: Create a file to write to and eventually make available to the user.
 1873: If file creation fails, outputs an error message on the request object and 
 1874: return undefs.
 1875: 
 1876: Inputs: Apache request object, and file suffix
 1877: 
 1878: Returns (undef) on failure, 
 1879:     Filehandle and filename on success.
 1880: 
 1881: =cut
 1882: 
 1883: ###############################################################
 1884: ###############################################################
 1885: sub create_text_file {
 1886:     my ($r,$suffix) = @_;
 1887:     if (! defined($suffix)) { $suffix = 'txt'; };
 1888:     my $fh;
 1889:     my $filename = '/prtspool/'.
 1890:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1891:         time.'_'.rand(1000000000).'.'.$suffix;
 1892:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1893:     if (! defined($fh)) {
 1894:         $r->log_error("Couldn't open $filename for output $!");
 1895:         $r->print(
 1896:             '<p class="LC_error">'
 1897:            .&mt('Problems occurred in creating the output file.')
 1898:            .' '.&mt('This error has been logged.')
 1899:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1900:            .'</p>'
 1901:         );
 1902:     }
 1903:     return ($fh,$filename)
 1904: }
 1905: 
 1906: 
 1907: =pod 
 1908: 
 1909: =back
 1910: 
 1911: =cut
 1912: 
 1913: ###############################################################
 1914: ##        Home server <option> list generating code          ##
 1915: ###############################################################
 1916: 
 1917: # ------------------------------------------
 1918: 
 1919: sub domain_select {
 1920:     my ($name,$value,$multiple)=@_;
 1921:     my %domains=map { 
 1922: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1923:     } &Apache::lonnet::all_domains();
 1924:     if ($multiple) {
 1925: 	$domains{''}=&mt('Any domain');
 1926: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1927: 	return &multiple_select_form($name,$value,4,\%domains);
 1928:     } else {
 1929: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1930: 	return &select_form($name,$value,\%domains);
 1931:     }
 1932: }
 1933: 
 1934: #-------------------------------------------
 1935: 
 1936: =pod
 1937: 
 1938: =head1 Routines for form select boxes
 1939: 
 1940: =over 4
 1941: 
 1942: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1943: 
 1944: Returns a string containing a <select> element int multiple mode
 1945: 
 1946: 
 1947: Args:
 1948:   $name - name of the <select> element
 1949:   $value - scalar or array ref of values that should already be selected
 1950:   $size - number of rows long the select element is
 1951:   $hash - the elements should be 'option' => 'shown text'
 1952:           (shown text should already have been &mt())
 1953:   $order - (optional) array ref of the order to show the elements in
 1954: 
 1955: =cut
 1956: 
 1957: #-------------------------------------------
 1958: sub multiple_select_form {
 1959:     my ($name,$value,$size,$hash,$order)=@_;
 1960:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1961:     my $output='';
 1962:     if (! defined($size)) {
 1963:         $size = 4;
 1964:         if (scalar(keys(%$hash))<4) {
 1965:             $size = scalar(keys(%$hash));
 1966:         }
 1967:     }
 1968:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1969:     my @order;
 1970:     if (ref($order) eq 'ARRAY')  {
 1971:         @order = @{$order};
 1972:     } else {
 1973:         @order = sort(keys(%$hash));
 1974:     }
 1975:     if (exists($$hash{'select_form_order'})) {
 1976:         @order = @{$$hash{'select_form_order'}};
 1977:     }
 1978:         
 1979:     foreach my $key (@order) {
 1980:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1981:         $output.='selected="selected" ' if ($selected{$key});
 1982:         $output.='>'.$hash->{$key}."</option>\n";
 1983:     }
 1984:     $output.="</select>\n";
 1985:     return $output;
 1986: }
 1987: 
 1988: #-------------------------------------------
 1989: 
 1990: =pod
 1991: 
 1992: =item * &select_form($defdom,$name,$hashref,$onchange)
 1993: 
 1994: Returns a string containing a <select name='$name' size='1'> form to 
 1995: allow a user to select options from a ref to a hash containing:
 1996: option_name => displayed text. An optional $onchange can include
 1997: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1998: 
 1999: See lonrights.pm for an example invocation and use.
 2000: 
 2001: =cut
 2002: 
 2003: #-------------------------------------------
 2004: sub select_form {
 2005:     my ($def,$name,$hashref,$onchange) = @_;
 2006:     return unless (ref($hashref) eq 'HASH');
 2007:     if ($onchange) {
 2008:         $onchange = ' onchange="'.$onchange.'"';
 2009:     }
 2010:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2011:     my @keys;
 2012:     if (exists($hashref->{'select_form_order'})) {
 2013: 	@keys=@{$hashref->{'select_form_order'}};
 2014:     } else {
 2015: 	@keys=sort(keys(%{$hashref}));
 2016:     }
 2017:     foreach my $key (@keys) {
 2018:         $selectform.=
 2019: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2020:             ($key eq $def ? 'selected="selected" ' : '').
 2021:                 ">".$hashref->{$key}."</option>\n";
 2022:     }
 2023:     $selectform.="</select>";
 2024:     return $selectform;
 2025: }
 2026: 
 2027: # For display filters
 2028: 
 2029: sub display_filter {
 2030:     my ($context) = @_;
 2031:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2032:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2033:     my $phraseinput = 'hidden';
 2034:     my $includeinput = 'hidden';
 2035:     my ($checked,$includetypestext);
 2036:     if ($env{'form.displayfilter'} eq 'containing') {
 2037:         $phraseinput = 'text'; 
 2038:         if ($context eq 'parmslog') {
 2039:             $includeinput = 'checkbox';
 2040:             if ($env{'form.includetypes'}) {
 2041:                 $checked = ' checked="checked"';
 2042:             }
 2043:             $includetypestext = &mt('Include parameter types');
 2044:         }
 2045:     } else {
 2046:         $includetypestext = '&nbsp;';
 2047:     }
 2048:     my ($additional,$secondid,$thirdid);
 2049:     if ($context eq 'parmslog') {
 2050:         $additional = 
 2051:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2052:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2053:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2054:             '</label>';
 2055:         $secondid = 'includetypes';
 2056:         $thirdid = 'includetypestext';
 2057:     }
 2058:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2059:                                                     '$secondid','$thirdid')";
 2060:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2061: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2062: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2063: 	   '</label></span> <span class="LC_nobreak">'.
 2064:            &mt('Filter: [_1]',
 2065: 	   &select_form($env{'form.displayfilter'},
 2066: 			'displayfilter',
 2067: 			{'currentfolder' => 'Current folder/page',
 2068: 			 'containing' => 'Containing phrase',
 2069: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2070: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2071:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2072:                          '" />'.$additional;
 2073: }
 2074: 
 2075: sub display_filter_js {
 2076:     my $includetext = &mt('Include parameter types');
 2077:     return <<"ENDJS";
 2078:   
 2079: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2080:     var firstType = 'hidden';
 2081:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2082:         firstType = 'text';
 2083:     }
 2084:     firstObject = document.getElementById(firstid);
 2085:     if (typeof(firstObject) == 'object') {
 2086:         if (firstObject.type != firstType) {
 2087:             changeInputType(firstObject,firstType);
 2088:         }
 2089:     }
 2090:     if (context == 'parmslog') {
 2091:         var secondType = 'hidden';
 2092:         if (firstType == 'text') {
 2093:             secondType = 'checkbox';
 2094:         }
 2095:         secondObject = document.getElementById(secondid);  
 2096:         if (typeof(secondObject) == 'object') {
 2097:             if (secondObject.type != secondType) {
 2098:                 changeInputType(secondObject,secondType);
 2099:             }
 2100:         }
 2101:         var textItem = document.getElementById(thirdid);
 2102:         var currtext = textItem.innerHTML;
 2103:         var newtext;
 2104:         if (firstType == 'text') {
 2105:             newtext = '$includetext';
 2106:         } else {
 2107:             newtext = '&nbsp;';
 2108:         }
 2109:         if (currtext != newtext) {
 2110:             textItem.innerHTML = newtext;
 2111:         }
 2112:     }
 2113:     return;
 2114: }
 2115: 
 2116: function changeInputType(oldObject,newType) {
 2117:     var newObject = document.createElement('input');
 2118:     newObject.type = newType;
 2119:     if (oldObject.size) {
 2120:         newObject.size = oldObject.size;
 2121:     }
 2122:     if (oldObject.value) {
 2123:         newObject.value = oldObject.value;
 2124:     }
 2125:     if (oldObject.name) {
 2126:         newObject.name = oldObject.name;
 2127:     }
 2128:     if (oldObject.id) {
 2129:         newObject.id = oldObject.id;
 2130:     }
 2131:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2132:     return;
 2133: }
 2134: 
 2135: ENDJS
 2136: }
 2137: 
 2138: sub gradeleveldescription {
 2139:     my $gradelevel=shift;
 2140:     my %gradelevels=(0 => 'Not specified',
 2141: 		     1 => 'Grade 1',
 2142: 		     2 => 'Grade 2',
 2143: 		     3 => 'Grade 3',
 2144: 		     4 => 'Grade 4',
 2145: 		     5 => 'Grade 5',
 2146: 		     6 => 'Grade 6',
 2147: 		     7 => 'Grade 7',
 2148: 		     8 => 'Grade 8',
 2149: 		     9 => 'Grade 9',
 2150: 		     10 => 'Grade 10',
 2151: 		     11 => 'Grade 11',
 2152: 		     12 => 'Grade 12',
 2153: 		     13 => 'Grade 13',
 2154: 		     14 => '100 Level',
 2155: 		     15 => '200 Level',
 2156: 		     16 => '300 Level',
 2157: 		     17 => '400 Level',
 2158: 		     18 => 'Graduate Level');
 2159:     return &mt($gradelevels{$gradelevel});
 2160: }
 2161: 
 2162: sub select_level_form {
 2163:     my ($deflevel,$name)=@_;
 2164:     unless ($deflevel) { $deflevel=0; }
 2165:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2166:     for (my $i=0; $i<=18; $i++) {
 2167:         $selectform.="<option value=\"$i\" ".
 2168:             ($i==$deflevel ? 'selected="selected" ' : '').
 2169:                 ">".&gradeleveldescription($i)."</option>\n";
 2170:     }
 2171:     $selectform.="</select>";
 2172:     return $selectform;
 2173: }
 2174: 
 2175: #-------------------------------------------
 2176: 
 2177: =pod
 2178: 
 2179: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2180: 
 2181: Returns a string containing a <select name='$name' size='1'> form to 
 2182: allow a user to select the domain to preform an operation in.  
 2183: See loncreateuser.pm for an example invocation and use.
 2184: 
 2185: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2186: selected");
 2187: 
 2188: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2189: 
 2190: 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.
 2191: 
 2192: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2193: 
 2194: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2195: 
 2196: =cut
 2197: 
 2198: #-------------------------------------------
 2199: sub select_dom_form {
 2200:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2201:     if ($onchange) {
 2202:         $onchange = ' onchange="'.$onchange.'"';
 2203:     }
 2204:     my (@domains,%exclude);
 2205:     if (ref($incdoms) eq 'ARRAY') {
 2206:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2207:     } else {
 2208:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2209:     }
 2210:     if ($includeempty) { @domains=('',@domains); }
 2211:     if (ref($excdoms) eq 'ARRAY') {
 2212:         map { $exclude{$_} = 1; } @{$excdoms};
 2213:     }
 2214:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2215:     foreach my $dom (@domains) {
 2216:         next if ($exclude{$dom});
 2217:         $selectdomain.="<option value=\"$dom\" ".
 2218:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2219:         if ($showdomdesc) {
 2220:             if ($dom ne '') {
 2221:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2222:                 if ($domdesc ne '') {
 2223:                     $selectdomain .= ' ('.$domdesc.')';
 2224:                 }
 2225:             } 
 2226:         }
 2227:         $selectdomain .= "</option>\n";
 2228:     }
 2229:     $selectdomain.="</select>";
 2230:     return $selectdomain;
 2231: }
 2232: 
 2233: #-------------------------------------------
 2234: 
 2235: =pod
 2236: 
 2237: =item * &home_server_form_item($domain,$name,$defaultflag)
 2238: 
 2239: input: 4 arguments (two required, two optional) - 
 2240:     $domain - domain of new user
 2241:     $name - name of form element
 2242:     $default - Value of 'default' causes a default item to be first 
 2243:                             option, and selected by default. 
 2244:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2245:                             if 1 server found, or default, if 0 found.
 2246: output: returns 2 items: 
 2247: (a) form element which contains either:
 2248:    (i) <select name="$name">
 2249:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2250:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2251:        </select>
 2252:        form item if there are multiple library servers in $domain, or
 2253:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2254:        if there is only one library server in $domain.
 2255: 
 2256: (b) number of library servers found.
 2257: 
 2258: See loncreateuser.pm for example of use.
 2259: 
 2260: =cut
 2261: 
 2262: #-------------------------------------------
 2263: sub home_server_form_item {
 2264:     my ($domain,$name,$default,$hide) = @_;
 2265:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2266:     my $result;
 2267:     my $numlib = keys(%servers);
 2268:     if ($numlib > 1) {
 2269:         $result .= '<select name="'.$name.'" />'."\n";
 2270:         if ($default) {
 2271:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2272:                        '</option>'."\n";
 2273:         }
 2274:         foreach my $hostid (sort(keys(%servers))) {
 2275:             $result.= '<option value="'.$hostid.'">'.
 2276: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2277:         }
 2278:         $result .= '</select>'."\n";
 2279:     } elsif ($numlib == 1) {
 2280:         my $hostid;
 2281:         foreach my $item (keys(%servers)) {
 2282:             $hostid = $item;
 2283:         }
 2284:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2285:                    $hostid.'" />';
 2286:                    if (!$hide) {
 2287:                        $result .= $hostid.' '.$servers{$hostid};
 2288:                    }
 2289:                    $result .= "\n";
 2290:     } elsif ($default) {
 2291:         $result .= '<input type="hidden" name="'.$name.
 2292:                    '" value="default" />';
 2293:                    if (!$hide) {
 2294:                        $result .= &mt('default');
 2295:                    }
 2296:                    $result .= "\n";
 2297:     }
 2298:     return ($result,$numlib);
 2299: }
 2300: 
 2301: =pod
 2302: 
 2303: =back 
 2304: 
 2305: =cut
 2306: 
 2307: ###############################################################
 2308: ##                  Decoding User Agent                      ##
 2309: ###############################################################
 2310: 
 2311: =pod
 2312: 
 2313: =head1 Decoding the User Agent
 2314: 
 2315: =over 4
 2316: 
 2317: =item * &decode_user_agent()
 2318: 
 2319: Inputs: $r
 2320: 
 2321: Outputs:
 2322: 
 2323: =over 4
 2324: 
 2325: =item * $httpbrowser
 2326: 
 2327: =item * $clientbrowser
 2328: 
 2329: =item * $clientversion
 2330: 
 2331: =item * $clientmathml
 2332: 
 2333: =item * $clientunicode
 2334: 
 2335: =item * $clientos
 2336: 
 2337: =item * $clientmobile
 2338: 
 2339: =item * $clientinfo
 2340: 
 2341: =back
 2342: 
 2343: =back 
 2344: 
 2345: =cut
 2346: 
 2347: ###############################################################
 2348: ###############################################################
 2349: sub decode_user_agent {
 2350:     my ($r)=@_;
 2351:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2352:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2353:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2354:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2355:     my $clientbrowser='unknown';
 2356:     my $clientversion='0';
 2357:     my $clientmathml='';
 2358:     my $clientunicode='0';
 2359:     my $clientmobile=0;
 2360:     for (my $i=0;$i<=$#browsertype;$i++) {
 2361:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2362: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2363: 	    $clientbrowser=$bname;
 2364:             $httpbrowser=~/$vreg/i;
 2365: 	    $clientversion=$1;
 2366:             $clientmathml=($clientversion>=$minv);
 2367:             $clientunicode=($clientversion>=$univ);
 2368: 	}
 2369:     }
 2370:     my $clientos='unknown';
 2371:     my $clientinfo;
 2372:     if (($httpbrowser=~/linux/i) ||
 2373:         ($httpbrowser=~/unix/i) ||
 2374:         ($httpbrowser=~/ux/i) ||
 2375:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2376:     if (($httpbrowser=~/vax/i) ||
 2377:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2378:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2379:     if (($httpbrowser=~/mac/i) ||
 2380:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2381:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2382:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2383:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2384:         $clientmobile=lc($1);
 2385:     }
 2386:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2387:         $clientinfo = 'firefox-'.$1;
 2388:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2389:         $clientinfo = 'chromeframe-'.$1;
 2390:     }
 2391:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2392:             $clientunicode,$clientos,$clientmobile,$clientinfo);
 2393: }
 2394: 
 2395: ###############################################################
 2396: ##    Authentication changing form generation subroutines    ##
 2397: ###############################################################
 2398: ##
 2399: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2400: ## hash, and have reasonable default values.
 2401: ##
 2402: ##    formname = the name given in the <form> tag.
 2403: #-------------------------------------------
 2404: 
 2405: =pod
 2406: 
 2407: =head1 Authentication Routines
 2408: 
 2409: =over 4
 2410: 
 2411: =item * &authform_xxxxxx()
 2412: 
 2413: The authform_xxxxxx subroutines provide javascript and html forms which 
 2414: handle some of the conveniences required for authentication forms.  
 2415: This is not an optimal method, but it works.  
 2416: 
 2417: =over 4
 2418: 
 2419: =item * authform_header
 2420: 
 2421: =item * authform_authorwarning
 2422: 
 2423: =item * authform_nochange
 2424: 
 2425: =item * authform_kerberos
 2426: 
 2427: =item * authform_internal
 2428: 
 2429: =item * authform_filesystem
 2430: 
 2431: =back
 2432: 
 2433: See loncreateuser.pm for invocation and use examples.
 2434: 
 2435: =cut
 2436: 
 2437: #-------------------------------------------
 2438: sub authform_header{  
 2439:     my %in = (
 2440:         formname => 'cu',
 2441:         kerb_def_dom => '',
 2442:         @_,
 2443:     );
 2444:     $in{'formname'} = 'document.' . $in{'formname'};
 2445:     my $result='';
 2446: 
 2447: #---------------------------------------------- Code for upper case translation
 2448:     my $Javascript_toUpperCase;
 2449:     unless ($in{kerb_def_dom}) {
 2450:         $Javascript_toUpperCase =<<"END";
 2451:         switch (choice) {
 2452:            case 'krb': currentform.elements[choicearg].value =
 2453:                currentform.elements[choicearg].value.toUpperCase();
 2454:                break;
 2455:            default:
 2456:         }
 2457: END
 2458:     } else {
 2459:         $Javascript_toUpperCase = "";
 2460:     }
 2461: 
 2462:     my $radioval = "'nochange'";
 2463:     if (defined($in{'curr_authtype'})) {
 2464:         if ($in{'curr_authtype'} ne '') {
 2465:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2466:         }
 2467:     }
 2468:     my $argfield = 'null';
 2469:     if (defined($in{'mode'})) {
 2470:         if ($in{'mode'} eq 'modifycourse')  {
 2471:             if (defined($in{'curr_autharg'})) {
 2472:                 if ($in{'curr_autharg'} ne '') {
 2473:                     $argfield = "'$in{'curr_autharg'}'";
 2474:                 }
 2475:             }
 2476:         }
 2477:     }
 2478: 
 2479:     $result.=<<"END";
 2480: var current = new Object();
 2481: current.radiovalue = $radioval;
 2482: current.argfield = $argfield;
 2483: 
 2484: function changed_radio(choice,currentform) {
 2485:     var choicearg = choice + 'arg';
 2486:     // If a radio button in changed, we need to change the argfield
 2487:     if (current.radiovalue != choice) {
 2488:         current.radiovalue = choice;
 2489:         if (current.argfield != null) {
 2490:             currentform.elements[current.argfield].value = '';
 2491:         }
 2492:         if (choice == 'nochange') {
 2493:             current.argfield = null;
 2494:         } else {
 2495:             current.argfield = choicearg;
 2496:             switch(choice) {
 2497:                 case 'krb': 
 2498:                     currentform.elements[current.argfield].value = 
 2499:                         "$in{'kerb_def_dom'}";
 2500:                 break;
 2501:               default:
 2502:                 break;
 2503:             }
 2504:         }
 2505:     }
 2506:     return;
 2507: }
 2508: 
 2509: function changed_text(choice,currentform) {
 2510:     var choicearg = choice + 'arg';
 2511:     if (currentform.elements[choicearg].value !='') {
 2512:         $Javascript_toUpperCase
 2513:         // clear old field
 2514:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2515:             currentform.elements[current.argfield].value = '';
 2516:         }
 2517:         current.argfield = choicearg;
 2518:     }
 2519:     set_auth_radio_buttons(choice,currentform);
 2520:     return;
 2521: }
 2522: 
 2523: function set_auth_radio_buttons(newvalue,currentform) {
 2524:     var numauthchoices = currentform.login.length;
 2525:     if (typeof numauthchoices  == "undefined") {
 2526:         return;
 2527:     } 
 2528:     var i=0;
 2529:     while (i < numauthchoices) {
 2530:         if (currentform.login[i].value == newvalue) { break; }
 2531:         i++;
 2532:     }
 2533:     if (i == numauthchoices) {
 2534:         return;
 2535:     }
 2536:     current.radiovalue = newvalue;
 2537:     currentform.login[i].checked = true;
 2538:     return;
 2539: }
 2540: END
 2541:     return $result;
 2542: }
 2543: 
 2544: sub authform_authorwarning {
 2545:     my $result='';
 2546:     $result='<i>'.
 2547:         &mt('As a general rule, only authors or co-authors should be '.
 2548:             'filesystem authenticated '.
 2549:             '(which allows access to the server filesystem).')."</i>\n";
 2550:     return $result;
 2551: }
 2552: 
 2553: sub authform_nochange {
 2554:     my %in = (
 2555:               formname => 'document.cu',
 2556:               kerb_def_dom => 'MSU.EDU',
 2557:               @_,
 2558:           );
 2559:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2560:     my $result;
 2561:     if (!$authnum) {
 2562:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2563:     } else {
 2564:         $result = '<label>'.&mt('[_1] Do not change login data',
 2565:                   '<input type="radio" name="login" value="nochange" '.
 2566:                   'checked="checked" onclick="'.
 2567:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2568: 	    '</label>';
 2569:     }
 2570:     return $result;
 2571: }
 2572: 
 2573: sub authform_kerberos {
 2574:     my %in = (
 2575:               formname => 'document.cu',
 2576:               kerb_def_dom => 'MSU.EDU',
 2577:               kerb_def_auth => 'krb4',
 2578:               @_,
 2579:               );
 2580:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2581:         $autharg,$jscall);
 2582:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2583:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2584:        $check5 = ' checked="checked"';
 2585:     } else {
 2586:        $check4 = ' checked="checked"';
 2587:     }
 2588:     $krbarg = $in{'kerb_def_dom'};
 2589:     if (defined($in{'curr_authtype'})) {
 2590:         if ($in{'curr_authtype'} eq 'krb') {
 2591:             $krbcheck = ' checked="checked"';
 2592:             if (defined($in{'mode'})) {
 2593:                 if ($in{'mode'} eq 'modifyuser') {
 2594:                     $krbcheck = '';
 2595:                 }
 2596:             }
 2597:             if (defined($in{'curr_kerb_ver'})) {
 2598:                 if ($in{'curr_krb_ver'} eq '5') {
 2599:                     $check5 = ' checked="checked"';
 2600:                     $check4 = '';
 2601:                 } else {
 2602:                     $check4 = ' checked="checked"';
 2603:                     $check5 = '';
 2604:                 }
 2605:             }
 2606:             if (defined($in{'curr_autharg'})) {
 2607:                 $krbarg = $in{'curr_autharg'};
 2608:             }
 2609:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2610:                 if (defined($in{'curr_autharg'})) {
 2611:                     $result = 
 2612:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2613:         $in{'curr_autharg'},$krbver);
 2614:                 } else {
 2615:                     $result =
 2616:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2617:                 }
 2618:                 return $result; 
 2619:             }
 2620:         }
 2621:     } else {
 2622:         if ($authnum == 1) {
 2623:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2624:         }
 2625:     }
 2626:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2627:         return;
 2628:     } elsif ($authtype eq '') {
 2629:         if (defined($in{'mode'})) {
 2630:             if ($in{'mode'} eq 'modifycourse') {
 2631:                 if ($authnum == 1) {
 2632:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2633:                 }
 2634:             }
 2635:         }
 2636:     }
 2637:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2638:     if ($authtype eq '') {
 2639:         $authtype = '<input type="radio" name="login" value="krb" '.
 2640:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2641:                     $krbcheck.' />';
 2642:     }
 2643:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2644:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2645:          $in{'curr_authtype'} eq 'krb5') ||
 2646:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2647:          $in{'curr_authtype'} eq 'krb4')) {
 2648:         $result .= &mt
 2649:         ('[_1] Kerberos authenticated with domain [_2] '.
 2650:          '[_3] Version 4 [_4] Version 5 [_5]',
 2651:          '<label>'.$authtype,
 2652:          '</label><input type="text" size="10" name="krbarg" '.
 2653:              'value="'.$krbarg.'" '.
 2654:              'onchange="'.$jscall.'" />',
 2655:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2656:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2657: 	 '</label>');
 2658:     } elsif ($can_assign{'krb4'}) {
 2659:         $result .= &mt
 2660:         ('[_1] Kerberos authenticated with domain [_2] '.
 2661:          '[_3] Version 4 [_4]',
 2662:          '<label>'.$authtype,
 2663:          '</label><input type="text" size="10" name="krbarg" '.
 2664:              'value="'.$krbarg.'" '.
 2665:              'onchange="'.$jscall.'" />',
 2666:          '<label><input type="hidden" name="krbver" value="4" />',
 2667:          '</label>');
 2668:     } elsif ($can_assign{'krb5'}) {
 2669:         $result .= &mt
 2670:         ('[_1] Kerberos authenticated with domain [_2] '.
 2671:          '[_3] Version 5 [_4]',
 2672:          '<label>'.$authtype,
 2673:          '</label><input type="text" size="10" name="krbarg" '.
 2674:              'value="'.$krbarg.'" '.
 2675:              'onchange="'.$jscall.'" />',
 2676:          '<label><input type="hidden" name="krbver" value="5" />',
 2677:          '</label>');
 2678:     }
 2679:     return $result;
 2680: }
 2681: 
 2682: sub authform_internal {
 2683:     my %in = (
 2684:                 formname => 'document.cu',
 2685:                 kerb_def_dom => 'MSU.EDU',
 2686:                 @_,
 2687:                 );
 2688:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2689:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2690:     if (defined($in{'curr_authtype'})) {
 2691:         if ($in{'curr_authtype'} eq 'int') {
 2692:             if ($can_assign{'int'}) {
 2693:                 $intcheck = 'checked="checked" ';
 2694:                 if (defined($in{'mode'})) {
 2695:                     if ($in{'mode'} eq 'modifyuser') {
 2696:                         $intcheck = '';
 2697:                     }
 2698:                 }
 2699:                 if (defined($in{'curr_autharg'})) {
 2700:                     $intarg = $in{'curr_autharg'};
 2701:                 }
 2702:             } else {
 2703:                 $result = &mt('Currently internally authenticated.');
 2704:                 return $result;
 2705:             }
 2706:         }
 2707:     } else {
 2708:         if ($authnum == 1) {
 2709:             $authtype = '<input type="hidden" name="login" value="int" />';
 2710:         }
 2711:     }
 2712:     if (!$can_assign{'int'}) {
 2713:         return;
 2714:     } elsif ($authtype eq '') {
 2715:         if (defined($in{'mode'})) {
 2716:             if ($in{'mode'} eq 'modifycourse') {
 2717:                 if ($authnum == 1) {
 2718:                     $authtype = '<input type="radio" name="login" value="int" />';
 2719:                 }
 2720:             }
 2721:         }
 2722:     }
 2723:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2724:     if ($authtype eq '') {
 2725:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2726:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2727:     }
 2728:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2729:                $intarg.'" onchange="'.$jscall.'" />';
 2730:     $result = &mt
 2731:         ('[_1] Internally authenticated (with initial password [_2])',
 2732:          '<label>'.$authtype,'</label>'.$autharg);
 2733:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2734:     return $result;
 2735: }
 2736: 
 2737: sub authform_local {
 2738:     my %in = (
 2739:               formname => 'document.cu',
 2740:               kerb_def_dom => 'MSU.EDU',
 2741:               @_,
 2742:               );
 2743:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2744:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2745:     if (defined($in{'curr_authtype'})) {
 2746:         if ($in{'curr_authtype'} eq 'loc') {
 2747:             if ($can_assign{'loc'}) {
 2748:                 $loccheck = 'checked="checked" ';
 2749:                 if (defined($in{'mode'})) {
 2750:                     if ($in{'mode'} eq 'modifyuser') {
 2751:                         $loccheck = '';
 2752:                     }
 2753:                 }
 2754:                 if (defined($in{'curr_autharg'})) {
 2755:                     $locarg = $in{'curr_autharg'};
 2756:                 }
 2757:             } else {
 2758:                 $result = &mt('Currently using local (institutional) authentication.');
 2759:                 return $result;
 2760:             }
 2761:         }
 2762:     } else {
 2763:         if ($authnum == 1) {
 2764:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2765:         }
 2766:     }
 2767:     if (!$can_assign{'loc'}) {
 2768:         return;
 2769:     } elsif ($authtype eq '') {
 2770:         if (defined($in{'mode'})) {
 2771:             if ($in{'mode'} eq 'modifycourse') {
 2772:                 if ($authnum == 1) {
 2773:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2774:                 }
 2775:             }
 2776:         }
 2777:     }
 2778:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2779:     if ($authtype eq '') {
 2780:         $authtype = '<input type="radio" name="login" value="loc" '.
 2781:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2782:                     $jscall.'" />';
 2783:     }
 2784:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2785:                $locarg.'" onchange="'.$jscall.'" />';
 2786:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2787:                   '<label>'.$authtype,'</label>'.$autharg);
 2788:     return $result;
 2789: }
 2790: 
 2791: sub authform_filesystem {
 2792:     my %in = (
 2793:               formname => 'document.cu',
 2794:               kerb_def_dom => 'MSU.EDU',
 2795:               @_,
 2796:               );
 2797:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2798:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2799:     if (defined($in{'curr_authtype'})) {
 2800:         if ($in{'curr_authtype'} eq 'fsys') {
 2801:             if ($can_assign{'fsys'}) {
 2802:                 $fsyscheck = 'checked="checked" ';
 2803:                 if (defined($in{'mode'})) {
 2804:                     if ($in{'mode'} eq 'modifyuser') {
 2805:                         $fsyscheck = '';
 2806:                     }
 2807:                 }
 2808:             } else {
 2809:                 $result = &mt('Currently Filesystem Authenticated.');
 2810:                 return $result;
 2811:             }           
 2812:         }
 2813:     } else {
 2814:         if ($authnum == 1) {
 2815:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2816:         }
 2817:     }
 2818:     if (!$can_assign{'fsys'}) {
 2819:         return;
 2820:     } elsif ($authtype eq '') {
 2821:         if (defined($in{'mode'})) {
 2822:             if ($in{'mode'} eq 'modifycourse') {
 2823:                 if ($authnum == 1) {
 2824:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2825:                 }
 2826:             }
 2827:         }
 2828:     }
 2829:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2830:     if ($authtype eq '') {
 2831:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2832:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2833:                     $jscall.'" />';
 2834:     }
 2835:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2836:                ' onchange="'.$jscall.'" />';
 2837:     $result = &mt
 2838:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2839:          '<label><input type="radio" name="login" value="fsys" '.
 2840:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2841:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2842:                   'onchange="'.$jscall.'" />');
 2843:     return $result;
 2844: }
 2845: 
 2846: sub get_assignable_auth {
 2847:     my ($dom) = @_;
 2848:     if ($dom eq '') {
 2849:         $dom = $env{'request.role.domain'};
 2850:     }
 2851:     my %can_assign = (
 2852:                           krb4 => 1,
 2853:                           krb5 => 1,
 2854:                           int  => 1,
 2855:                           loc  => 1,
 2856:                      );
 2857:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2858:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2859:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2860:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2861:             my $context;
 2862:             if ($env{'request.role'} =~ /^au/) {
 2863:                 $context = 'author';
 2864:             } elsif ($env{'request.role'} =~ /^dc/) {
 2865:                 $context = 'domain';
 2866:             } elsif ($env{'request.course.id'}) {
 2867:                 $context = 'course';
 2868:             }
 2869:             if ($context) {
 2870:                 if (ref($authhash->{$context}) eq 'HASH') {
 2871:                    %can_assign = %{$authhash->{$context}}; 
 2872:                 }
 2873:             }
 2874:         }
 2875:     }
 2876:     my $authnum = 0;
 2877:     foreach my $key (keys(%can_assign)) {
 2878:         if ($can_assign{$key}) {
 2879:             $authnum ++;
 2880:         }
 2881:     }
 2882:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2883:         $authnum --;
 2884:     }
 2885:     return ($authnum,%can_assign);
 2886: }
 2887: 
 2888: ###############################################################
 2889: ##    Get Kerberos Defaults for Domain                 ##
 2890: ###############################################################
 2891: ##
 2892: ## Returns default kerberos version and an associated argument
 2893: ## as listed in file domain.tab. If not listed, provides
 2894: ## appropriate default domain and kerberos version.
 2895: ##
 2896: #-------------------------------------------
 2897: 
 2898: =pod
 2899: 
 2900: =item * &get_kerberos_defaults()
 2901: 
 2902: get_kerberos_defaults($target_domain) returns the default kerberos
 2903: version and domain. If not found, it defaults to version 4 and the 
 2904: domain of the server.
 2905: 
 2906: =over 4
 2907: 
 2908: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2909: 
 2910: =back
 2911: 
 2912: =back
 2913: 
 2914: =cut
 2915: 
 2916: #-------------------------------------------
 2917: sub get_kerberos_defaults {
 2918:     my $domain=shift;
 2919:     my ($krbdef,$krbdefdom);
 2920:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2921:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2922:         $krbdef = $domdefaults{'auth_def'};
 2923:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2924:     } else {
 2925:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2926:         my $krbdefdom=$1;
 2927:         $krbdefdom=~tr/a-z/A-Z/;
 2928:         $krbdef = "krb4";
 2929:     }
 2930:     return ($krbdef,$krbdefdom);
 2931: }
 2932: 
 2933: 
 2934: ###############################################################
 2935: ##                Thesaurus Functions                        ##
 2936: ###############################################################
 2937: 
 2938: =pod
 2939: 
 2940: =head1 Thesaurus Functions
 2941: 
 2942: =over 4
 2943: 
 2944: =item * &initialize_keywords()
 2945: 
 2946: Initializes the package variable %Keywords if it is empty.  Uses the
 2947: package variable $thesaurus_db_file.
 2948: 
 2949: =cut
 2950: 
 2951: ###################################################
 2952: 
 2953: sub initialize_keywords {
 2954:     return 1 if (scalar keys(%Keywords));
 2955:     # If we are here, %Keywords is empty, so fill it up
 2956:     #   Make sure the file we need exists...
 2957:     if (! -e $thesaurus_db_file) {
 2958:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2959:                                  " failed because it does not exist");
 2960:         return 0;
 2961:     }
 2962:     #   Set up the hash as a database
 2963:     my %thesaurus_db;
 2964:     if (! tie(%thesaurus_db,'GDBM_File',
 2965:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2966:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2967:                                  $thesaurus_db_file);
 2968:         return 0;
 2969:     } 
 2970:     #  Get the average number of appearances of a word.
 2971:     my $avecount = $thesaurus_db{'average.count'};
 2972:     #  Put keywords (those that appear > average) into %Keywords
 2973:     while (my ($word,$data)=each (%thesaurus_db)) {
 2974:         my ($count,undef) = split /:/,$data;
 2975:         $Keywords{$word}++ if ($count > $avecount);
 2976:     }
 2977:     untie %thesaurus_db;
 2978:     # Remove special values from %Keywords.
 2979:     foreach my $value ('total.count','average.count') {
 2980:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2981:   }
 2982:     return 1;
 2983: }
 2984: 
 2985: ###################################################
 2986: 
 2987: =pod
 2988: 
 2989: =item * &keyword($word)
 2990: 
 2991: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2992: than the average number of times in the thesaurus database.  Calls 
 2993: &initialize_keywords
 2994: 
 2995: =cut
 2996: 
 2997: ###################################################
 2998: 
 2999: sub keyword {
 3000:     return if (!&initialize_keywords());
 3001:     my $word=lc(shift());
 3002:     $word=~s/\W//g;
 3003:     return exists($Keywords{$word});
 3004: }
 3005: 
 3006: ###############################################################
 3007: 
 3008: =pod 
 3009: 
 3010: =item * &get_related_words()
 3011: 
 3012: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3013: an array of words.  If the keyword is not in the thesaurus, an empty array
 3014: will be returned.  The order of the words returned is determined by the
 3015: database which holds them.
 3016: 
 3017: Uses global $thesaurus_db_file.
 3018: 
 3019: 
 3020: =cut
 3021: 
 3022: ###############################################################
 3023: sub get_related_words {
 3024:     my $keyword = shift;
 3025:     my %thesaurus_db;
 3026:     if (! -e $thesaurus_db_file) {
 3027:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3028:                                  "failed because the file does not exist");
 3029:         return ();
 3030:     }
 3031:     if (! tie(%thesaurus_db,'GDBM_File',
 3032:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3033:         return ();
 3034:     } 
 3035:     my @Words=();
 3036:     my $count=0;
 3037:     if (exists($thesaurus_db{$keyword})) {
 3038: 	# The first element is the number of times
 3039: 	# the word appears.  We do not need it now.
 3040: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3041: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3042: 	my $threshold=$mostfrequentcount/10;
 3043:         foreach my $possibleword (@RelatedWords) {
 3044:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3045:             if ($wordcount>$threshold) {
 3046: 		push(@Words,$word);
 3047:                 $count++;
 3048:                 if ($count>10) { last; }
 3049: 	    }
 3050:         }
 3051:     }
 3052:     untie %thesaurus_db;
 3053:     return @Words;
 3054: }
 3055: 
 3056: =pod
 3057: 
 3058: =back
 3059: 
 3060: =cut
 3061: 
 3062: # -------------------------------------------------------------- Plaintext name
 3063: =pod
 3064: 
 3065: =head1 User Name Functions
 3066: 
 3067: =over 4
 3068: 
 3069: =item * &plainname($uname,$udom,$first)
 3070: 
 3071: Takes a users logon name and returns it as a string in
 3072: "first middle last generation" form 
 3073: if $first is set to 'lastname' then it returns it as
 3074: 'lastname generation, firstname middlename' if their is a lastname
 3075: 
 3076: =cut
 3077: 
 3078: 
 3079: ###############################################################
 3080: sub plainname {
 3081:     my ($uname,$udom,$first)=@_;
 3082:     return if (!defined($uname) || !defined($udom));
 3083:     my %names=&getnames($uname,$udom);
 3084:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3085: 					  $names{'middlename'},
 3086: 					  $names{'lastname'},
 3087: 					  $names{'generation'},$first);
 3088:     $name=~s/^\s+//;
 3089:     $name=~s/\s+$//;
 3090:     $name=~s/\s+/ /g;
 3091:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3092:     return $name;
 3093: }
 3094: 
 3095: # -------------------------------------------------------------------- Nickname
 3096: =pod
 3097: 
 3098: =item * &nickname($uname,$udom)
 3099: 
 3100: Gets a users name and returns it as a string as
 3101: 
 3102: "&quot;nickname&quot;"
 3103: 
 3104: if the user has a nickname or
 3105: 
 3106: "first middle last generation"
 3107: 
 3108: if the user does not
 3109: 
 3110: =cut
 3111: 
 3112: sub nickname {
 3113:     my ($uname,$udom)=@_;
 3114:     return if (!defined($uname) || !defined($udom));
 3115:     my %names=&getnames($uname,$udom);
 3116:     my $name=$names{'nickname'};
 3117:     if ($name) {
 3118:        $name='&quot;'.$name.'&quot;'; 
 3119:     } else {
 3120:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3121: 	     $names{'lastname'}.' '.$names{'generation'};
 3122:        $name=~s/\s+$//;
 3123:        $name=~s/\s+/ /g;
 3124:     }
 3125:     return $name;
 3126: }
 3127: 
 3128: sub getnames {
 3129:     my ($uname,$udom)=@_;
 3130:     return if (!defined($uname) || !defined($udom));
 3131:     if ($udom eq 'public' && $uname eq 'public') {
 3132: 	return ('lastname' => &mt('Public'));
 3133:     }
 3134:     my $id=$uname.':'.$udom;
 3135:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3136:     if ($cached) {
 3137: 	return %{$names};
 3138:     } else {
 3139: 	my %loadnames=&Apache::lonnet::get('environment',
 3140:                     ['firstname','middlename','lastname','generation','nickname'],
 3141: 					 $udom,$uname);
 3142: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3143: 	return %loadnames;
 3144:     }
 3145: }
 3146: 
 3147: # -------------------------------------------------------------------- getemails
 3148: 
 3149: =pod
 3150: 
 3151: =item * &getemails($uname,$udom)
 3152: 
 3153: Gets a user's email information and returns it as a hash with keys:
 3154: notification, critnotification, permanentemail
 3155: 
 3156: For notification and critnotification, values are comma-separated lists 
 3157: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3158:  
 3159: 
 3160: =cut
 3161: 
 3162: 
 3163: sub getemails {
 3164:     my ($uname,$udom)=@_;
 3165:     if ($udom eq 'public' && $uname eq 'public') {
 3166: 	return;
 3167:     }
 3168:     if (!$udom) { $udom=$env{'user.domain'}; }
 3169:     if (!$uname) { $uname=$env{'user.name'}; }
 3170:     my $id=$uname.':'.$udom;
 3171:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3172:     if ($cached) {
 3173: 	return %{$names};
 3174:     } else {
 3175: 	my %loadnames=&Apache::lonnet::get('environment',
 3176:                     			   ['notification','critnotification',
 3177: 					    'permanentemail'],
 3178: 					   $udom,$uname);
 3179: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3180: 	return %loadnames;
 3181:     }
 3182: }
 3183: 
 3184: sub flush_email_cache {
 3185:     my ($uname,$udom)=@_;
 3186:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3187:     if (!$uname) { $uname=$env{'user.name'};   }
 3188:     return if ($udom eq 'public' && $uname eq 'public');
 3189:     my $id=$uname.':'.$udom;
 3190:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3191: }
 3192: 
 3193: # -------------------------------------------------------------------- getlangs
 3194: 
 3195: =pod
 3196: 
 3197: =item * &getlangs($uname,$udom)
 3198: 
 3199: Gets a user's language preference and returns it as a hash with key:
 3200: language.
 3201: 
 3202: =cut
 3203: 
 3204: 
 3205: sub getlangs {
 3206:     my ($uname,$udom) = @_;
 3207:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3208:     if (!$uname) { $uname=$env{'user.name'};   }
 3209:     my $id=$uname.':'.$udom;
 3210:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3211:     if ($cached) {
 3212:         return %{$langs};
 3213:     } else {
 3214:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3215:                                            $udom,$uname);
 3216:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3217:         return %loadlangs;
 3218:     }
 3219: }
 3220: 
 3221: sub flush_langs_cache {
 3222:     my ($uname,$udom)=@_;
 3223:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3224:     if (!$uname) { $uname=$env{'user.name'};   }
 3225:     return if ($udom eq 'public' && $uname eq 'public');
 3226:     my $id=$uname.':'.$udom;
 3227:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3228: }
 3229: 
 3230: # ------------------------------------------------------------------ Screenname
 3231: 
 3232: =pod
 3233: 
 3234: =item * &screenname($uname,$udom)
 3235: 
 3236: Gets a users screenname and returns it as a string
 3237: 
 3238: =cut
 3239: 
 3240: sub screenname {
 3241:     my ($uname,$udom)=@_;
 3242:     if ($uname eq $env{'user.name'} &&
 3243: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3244:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3245:     return $names{'screenname'};
 3246: }
 3247: 
 3248: 
 3249: # ------------------------------------------------------------- Confirm Wrapper
 3250: =pod
 3251: 
 3252: =item * &confirmwrapper($message)
 3253: 
 3254: Wrap messages about completion of operation in box
 3255: 
 3256: =cut
 3257: 
 3258: sub confirmwrapper {
 3259:     my ($message)=@_;
 3260:     if ($message) {
 3261:         return "\n".'<div class="LC_confirm_box">'."\n"
 3262:                .$message."\n"
 3263:                .'</div>'."\n";
 3264:     } else {
 3265:         return $message;
 3266:     }
 3267: }
 3268: 
 3269: # ------------------------------------------------------------- Message Wrapper
 3270: 
 3271: sub messagewrapper {
 3272:     my ($link,$username,$domain,$subject,$text)=@_;
 3273:     return 
 3274:         '<a href="/adm/email?compose=individual&amp;'.
 3275:         'recname='.$username.'&amp;recdom='.$domain.
 3276: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3277:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3278: }
 3279: 
 3280: # --------------------------------------------------------------- Notes Wrapper
 3281: 
 3282: sub noteswrapper {
 3283:     my ($link,$un,$do)=@_;
 3284:     return 
 3285: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3286: }
 3287: 
 3288: # ------------------------------------------------------------- Aboutme Wrapper
 3289: 
 3290: sub aboutmewrapper {
 3291:     my ($link,$username,$domain,$target,$class)=@_;
 3292:     if (!defined($username)  && !defined($domain)) {
 3293:         return;
 3294:     }
 3295:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3296: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3297: }
 3298: 
 3299: # ------------------------------------------------------------ Syllabus Wrapper
 3300: 
 3301: sub syllabuswrapper {
 3302:     my ($linktext,$coursedir,$domain)=@_;
 3303:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3304: }
 3305: 
 3306: # -----------------------------------------------------------------------------
 3307: 
 3308: sub track_student_link {
 3309:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3310:     my $link ="/adm/trackstudent?";
 3311:     my $title = 'View recent activity';
 3312:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3313:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3314:         $link .= "selected_student=$sname:$sdom";
 3315:         $title .= ' of this student';
 3316:     } 
 3317:     if (defined($target) && $target !~ /^\s*$/) {
 3318:         $target = qq{target="$target"};
 3319:     } else {
 3320:         $target = '';
 3321:     }
 3322:     if ($start) { $link.='&amp;start='.$start; }
 3323:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3324:     $title = &mt($title);
 3325:     $linktext = &mt($linktext);
 3326:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3327: 	&help_open_topic('View_recent_activity');
 3328: }
 3329: 
 3330: sub slot_reservations_link {
 3331:     my ($linktext,$sname,$sdom,$target) = @_;
 3332:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3333:     my $title = 'View slot reservation history';
 3334:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3335:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3336:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3337:         $title .= ' of this student';
 3338:     }
 3339:     if (defined($target) && $target !~ /^\s*$/) {
 3340:         $target = qq{target="$target"};
 3341:     } else {
 3342:         $target = '';
 3343:     }
 3344:     $title = &mt($title);
 3345:     $linktext = &mt($linktext);
 3346:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3347: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3348: 
 3349: }
 3350: 
 3351: # ===================================================== Display a student photo
 3352: 
 3353: 
 3354: sub student_image_tag {
 3355:     my ($domain,$user)=@_;
 3356:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3357:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3358: 	return '<img src="'.$imgsrc.'" align="right" />';
 3359:     } else {
 3360: 	return '';
 3361:     }
 3362: }
 3363: 
 3364: =pod
 3365: 
 3366: =back
 3367: 
 3368: =head1 Access .tab File Data
 3369: 
 3370: =over 4
 3371: 
 3372: =item * &languageids() 
 3373: 
 3374: returns list of all language ids
 3375: 
 3376: =cut
 3377: 
 3378: sub languageids {
 3379:     return sort(keys(%language));
 3380: }
 3381: 
 3382: =pod
 3383: 
 3384: =item * &languagedescription() 
 3385: 
 3386: returns description of a specified language id
 3387: 
 3388: =cut
 3389: 
 3390: sub languagedescription {
 3391:     my $code=shift;
 3392:     return  ($supported_language{$code}?'* ':'').
 3393:             $language{$code}.
 3394: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3395: }
 3396: 
 3397: =pod
 3398: 
 3399: =item * &plainlanguagedescription
 3400: 
 3401: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3402: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3403: 
 3404: =cut
 3405: 
 3406: sub plainlanguagedescription {
 3407:     my $code=shift;
 3408:     return $language{$code};
 3409: }
 3410: 
 3411: =pod
 3412: 
 3413: =item * &supportedlanguagecode
 3414: 
 3415: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3416: code.
 3417: 
 3418: =cut
 3419: 
 3420: sub supportedlanguagecode {
 3421:     my $code=shift;
 3422:     return $supported_language{$code};
 3423: }
 3424: 
 3425: =pod
 3426: 
 3427: =item * &latexlanguage()
 3428: 
 3429: Given a language key code returns the correspondnig language to use
 3430: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3431: is no supported hyphenation for the language code.
 3432: 
 3433: =cut
 3434: 
 3435: sub latexlanguage {
 3436:     my $code = shift;
 3437:     return $latex_language{$code};
 3438: }
 3439: 
 3440: =pod
 3441: 
 3442: =item * &latexhyphenation()
 3443: 
 3444: Same as above but what's supplied is the language as it might be stored
 3445: in the metadata.
 3446: 
 3447: =cut
 3448: 
 3449: sub latexhyphenation {
 3450:     my $key = shift;
 3451:     return $latex_language_bykey{$key};
 3452: }
 3453: 
 3454: =pod
 3455: 
 3456: =item * &copyrightids() 
 3457: 
 3458: returns list of all copyrights
 3459: 
 3460: =cut
 3461: 
 3462: sub copyrightids {
 3463:     return sort(keys(%cprtag));
 3464: }
 3465: 
 3466: =pod
 3467: 
 3468: =item * &copyrightdescription() 
 3469: 
 3470: returns description of a specified copyright id
 3471: 
 3472: =cut
 3473: 
 3474: sub copyrightdescription {
 3475:     return &mt($cprtag{shift(@_)});
 3476: }
 3477: 
 3478: =pod
 3479: 
 3480: =item * &source_copyrightids() 
 3481: 
 3482: returns list of all source copyrights
 3483: 
 3484: =cut
 3485: 
 3486: sub source_copyrightids {
 3487:     return sort(keys(%scprtag));
 3488: }
 3489: 
 3490: =pod
 3491: 
 3492: =item * &source_copyrightdescription() 
 3493: 
 3494: returns description of a specified source copyright id
 3495: 
 3496: =cut
 3497: 
 3498: sub source_copyrightdescription {
 3499:     return &mt($scprtag{shift(@_)});
 3500: }
 3501: 
 3502: =pod
 3503: 
 3504: =item * &filecategories() 
 3505: 
 3506: returns list of all file categories
 3507: 
 3508: =cut
 3509: 
 3510: sub filecategories {
 3511:     return sort(keys(%category_extensions));
 3512: }
 3513: 
 3514: =pod
 3515: 
 3516: =item * &filecategorytypes() 
 3517: 
 3518: returns list of file types belonging to a given file
 3519: category
 3520: 
 3521: =cut
 3522: 
 3523: sub filecategorytypes {
 3524:     my ($cat) = @_;
 3525:     return @{$category_extensions{lc($cat)}};
 3526: }
 3527: 
 3528: =pod
 3529: 
 3530: =item * &fileembstyle() 
 3531: 
 3532: returns embedding style for a specified file type
 3533: 
 3534: =cut
 3535: 
 3536: sub fileembstyle {
 3537:     return $fe{lc(shift(@_))};
 3538: }
 3539: 
 3540: sub filemimetype {
 3541:     return $fm{lc(shift(@_))};
 3542: }
 3543: 
 3544: 
 3545: sub filecategoryselect {
 3546:     my ($name,$value)=@_;
 3547:     return &select_form($value,$name,
 3548:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3549: }
 3550: 
 3551: =pod
 3552: 
 3553: =item * &filedescription() 
 3554: 
 3555: returns description for a specified file type
 3556: 
 3557: =cut
 3558: 
 3559: sub filedescription {
 3560:     my $file_description = $fd{lc(shift())};
 3561:     $file_description =~ s:([\[\]]):~$1:g;
 3562:     return &mt($file_description);
 3563: }
 3564: 
 3565: =pod
 3566: 
 3567: =item * &filedescriptionex() 
 3568: 
 3569: returns description for a specified file type with
 3570: extra formatting
 3571: 
 3572: =cut
 3573: 
 3574: sub filedescriptionex {
 3575:     my $ex=shift;
 3576:     my $file_description = $fd{lc($ex)};
 3577:     $file_description =~ s:([\[\]]):~$1:g;
 3578:     return '.'.$ex.' '.&mt($file_description);
 3579: }
 3580: 
 3581: # End of .tab access
 3582: =pod
 3583: 
 3584: =back
 3585: 
 3586: =cut
 3587: 
 3588: # ------------------------------------------------------------------ File Types
 3589: sub fileextensions {
 3590:     return sort(keys(%fe));
 3591: }
 3592: 
 3593: # ----------------------------------------------------------- Display Languages
 3594: # returns a hash with all desired display languages
 3595: #
 3596: 
 3597: sub display_languages {
 3598:     my %languages=();
 3599:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3600: 	$languages{$lang}=1;
 3601:     }
 3602:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3603:     if ($env{'form.displaylanguage'}) {
 3604: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3605: 	    $languages{$lang}=1;
 3606:         }
 3607:     }
 3608:     return %languages;
 3609: }
 3610: 
 3611: sub languages {
 3612:     my ($possible_langs) = @_;
 3613:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3614:     if (!ref($possible_langs)) {
 3615: 	if( wantarray ) {
 3616: 	    return @preferred_langs;
 3617: 	} else {
 3618: 	    return $preferred_langs[0];
 3619: 	}
 3620:     }
 3621:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3622:     my @preferred_possibilities;
 3623:     foreach my $preferred_lang (@preferred_langs) {
 3624: 	if (exists($possibilities{$preferred_lang})) {
 3625: 	    push(@preferred_possibilities, $preferred_lang);
 3626: 	}
 3627:     }
 3628:     if( wantarray ) {
 3629: 	return @preferred_possibilities;
 3630:     }
 3631:     return $preferred_possibilities[0];
 3632: }
 3633: 
 3634: sub user_lang {
 3635:     my ($touname,$toudom,$fromcid) = @_;
 3636:     my @userlangs;
 3637:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3638:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3639:                     $env{'course.'.$fromcid.'.languages'}));
 3640:     } else {
 3641:         my %langhash = &getlangs($touname,$toudom);
 3642:         if ($langhash{'languages'} ne '') {
 3643:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3644:         } else {
 3645:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3646:             if ($domdefs{'lang_def'} ne '') {
 3647:                 @userlangs = ($domdefs{'lang_def'});
 3648:             }
 3649:         }
 3650:     }
 3651:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3652:     my $user_lh = Apache::localize->get_handle(@languages);
 3653:     return $user_lh;
 3654: }
 3655: 
 3656: 
 3657: ###############################################################
 3658: ##               Student Answer Attempts                     ##
 3659: ###############################################################
 3660: 
 3661: =pod
 3662: 
 3663: =head1 Alternate Problem Views
 3664: 
 3665: =over 4
 3666: 
 3667: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3668:     $getattempt, $regexp, $gradesub)
 3669: 
 3670: Return string with previous attempt on problem. Arguments:
 3671: 
 3672: =over 4
 3673: 
 3674: =item * $symb: Problem, including path
 3675: 
 3676: =item * $username: username of the desired student
 3677: 
 3678: =item * $domain: domain of the desired student
 3679: 
 3680: =item * $course: Course ID
 3681: 
 3682: =item * $getattempt: Leave blank for all attempts, otherwise put
 3683:     something
 3684: 
 3685: =item * $regexp: if string matches this regexp, the string will be
 3686:     sent to $gradesub
 3687: 
 3688: =item * $gradesub: routine that processes the string if it matches $regexp
 3689: 
 3690: =back
 3691: 
 3692: The output string is a table containing all desired attempts, if any.
 3693: 
 3694: =cut
 3695: 
 3696: sub get_previous_attempt {
 3697:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3698:   my $prevattempts='';
 3699:   no strict 'refs';
 3700:   if ($symb) {
 3701:     my (%returnhash)=
 3702:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3703:     if ($returnhash{'version'}) {
 3704:       my %lasthash=();
 3705:       my $version;
 3706:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3707:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3708: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3709:         }
 3710:       }
 3711:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3712:       $prevattempts.='<th>'.&mt('History').'</th>';
 3713:       my (%typeparts,%lasthidden);
 3714:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3715:       foreach my $key (sort(keys(%lasthash))) {
 3716: 	my ($ign,@parts) = split(/\./,$key);
 3717: 	if ($#parts > 0) {
 3718: 	  my $data=$parts[-1];
 3719:           next if ($data eq 'foilorder');
 3720: 	  pop(@parts);
 3721:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3722:           if ($data eq 'type') {
 3723:               unless ($showsurv) {
 3724:                   my $id = join(',',@parts);
 3725:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3726:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3727:                       $lasthidden{$ign.'.'.$id} = 1;
 3728:                   }
 3729:               }
 3730:           } 
 3731: 	} else {
 3732: 	  if ($#parts == 0) {
 3733: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3734: 	  } else {
 3735: 	    $prevattempts.='<th>'.$ign.'</th>';
 3736: 	  }
 3737: 	}
 3738:       }
 3739:       $prevattempts.=&end_data_table_header_row();
 3740:       if ($getattempt eq '') {
 3741: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3742:             my @hidden;
 3743:             if (%typeparts) {
 3744:                 foreach my $id (keys(%typeparts)) {
 3745:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3746:                         push(@hidden,$id);
 3747:                     }
 3748:                 }
 3749:             }
 3750:             $prevattempts.=&start_data_table_row().
 3751:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3752:             if (@hidden) {
 3753:                 foreach my $key (sort(keys(%lasthash))) {
 3754:                     next if ($key =~ /\.foilorder$/);
 3755:                     my $hide;
 3756:                     foreach my $id (@hidden) {
 3757:                         if ($key =~ /^\Q$id\E/) {
 3758:                             $hide = 1;
 3759:                             last;
 3760:                         }
 3761:                     }
 3762:                     if ($hide) {
 3763:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3764:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3765:                             my $value = &format_previous_attempt_value($key,
 3766:                                              $returnhash{$version.':'.$key});
 3767:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3768:                         } else {
 3769:                             $prevattempts.='<td>&nbsp;</td>';
 3770:                         }
 3771:                     } else {
 3772:                         if ($key =~ /\./) {
 3773:                             my $value = &format_previous_attempt_value($key,
 3774:                                               $returnhash{$version.':'.$key});
 3775:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3776:                         } else {
 3777:                             $prevattempts.='<td>&nbsp;</td>';
 3778:                         }
 3779:                     }
 3780:                 }
 3781:             } else {
 3782: 	        foreach my $key (sort(keys(%lasthash))) {
 3783:                     next if ($key =~ /\.foilorder$/);
 3784: 		    my $value = &format_previous_attempt_value($key,
 3785: 			            $returnhash{$version.':'.$key});
 3786: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3787: 	        }
 3788:             }
 3789: 	    $prevattempts.=&end_data_table_row();
 3790: 	 }
 3791:       }
 3792:       my @currhidden = keys(%lasthidden);
 3793:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3794:       foreach my $key (sort(keys(%lasthash))) {
 3795:           next if ($key =~ /\.foilorder$/);
 3796:           if (%typeparts) {
 3797:               my $hidden;
 3798:               foreach my $id (@currhidden) {
 3799:                   if ($key =~ /^\Q$id\E/) {
 3800:                       $hidden = 1;
 3801:                       last;
 3802:                   }
 3803:               }
 3804:               if ($hidden) {
 3805:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3806:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3807:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3808:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3809:                           $value = &$gradesub($value);
 3810:                       }
 3811:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3812:                   } else {
 3813:                       $prevattempts.='<td>&nbsp;</td>';
 3814:                   }
 3815:               } else {
 3816:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3817:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3818:                       $value = &$gradesub($value);
 3819:                   }
 3820:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3821:               }
 3822:           } else {
 3823: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3824: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3825:                   $value = &$gradesub($value);
 3826:               }
 3827: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3828:           }
 3829:       }
 3830:       $prevattempts.= &end_data_table_row().&end_data_table();
 3831:     } else {
 3832:       $prevattempts=
 3833: 	  &start_data_table().&start_data_table_row().
 3834: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3835: 	  &end_data_table_row().&end_data_table();
 3836:     }
 3837:   } else {
 3838:     $prevattempts=
 3839: 	  &start_data_table().&start_data_table_row().
 3840: 	  '<td>'.&mt('No data.').'</td>'.
 3841: 	  &end_data_table_row().&end_data_table();
 3842:   }
 3843: }
 3844: 
 3845: sub format_previous_attempt_value {
 3846:     my ($key,$value) = @_;
 3847:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3848: 	$value = &Apache::lonlocal::locallocaltime($value);
 3849:     } elsif (ref($value) eq 'ARRAY') {
 3850: 	$value = '('.join(', ', @{ $value }).')';
 3851:     } elsif ($key =~ /answerstring$/) {
 3852:         my %answers = &Apache::lonnet::str2hash($value);
 3853:         my @anskeys = sort(keys(%answers));
 3854:         if (@anskeys == 1) {
 3855:             my $answer = $answers{$anskeys[0]};
 3856:             if ($answer =~ m{\0}) {
 3857:                 $answer =~ s{\0}{,}g;
 3858:             }
 3859:             my $tag_internal_answer_name = 'INTERNAL';
 3860:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3861:                 $value = $answer; 
 3862:             } else {
 3863:                 $value = $anskeys[0].'='.$answer;
 3864:             }
 3865:         } else {
 3866:             foreach my $ans (@anskeys) {
 3867:                 my $answer = $answers{$ans};
 3868:                 if ($answer =~ m{\0}) {
 3869:                     $answer =~ s{\0}{,}g;
 3870:                 }
 3871:                 $value .=  $ans.'='.$answer.'<br />';;
 3872:             } 
 3873:         }
 3874:     } else {
 3875: 	$value = &unescape($value);
 3876:     }
 3877:     return $value;
 3878: }
 3879: 
 3880: 
 3881: sub relative_to_absolute {
 3882:     my ($url,$output)=@_;
 3883:     my $parser=HTML::TokeParser->new(\$output);
 3884:     my $token;
 3885:     my $thisdir=$url;
 3886:     my @rlinks=();
 3887:     while ($token=$parser->get_token) {
 3888: 	if ($token->[0] eq 'S') {
 3889: 	    if ($token->[1] eq 'a') {
 3890: 		if ($token->[2]->{'href'}) {
 3891: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3892: 		}
 3893: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3894: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3895: 	    } elsif ($token->[1] eq 'base') {
 3896: 		$thisdir=$token->[2]->{'href'};
 3897: 	    }
 3898: 	}
 3899:     }
 3900:     $thisdir=~s-/[^/]*$--;
 3901:     foreach my $link (@rlinks) {
 3902: 	unless (($link=~/^https?\:\/\//i) ||
 3903: 		($link=~/^\//) ||
 3904: 		($link=~/^javascript:/i) ||
 3905: 		($link=~/^mailto:/i) ||
 3906: 		($link=~/^\#/)) {
 3907: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3908: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3909: 	}
 3910:     }
 3911: # -------------------------------------------------- Deal with Applet codebases
 3912:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3913:     return $output;
 3914: }
 3915: 
 3916: =pod
 3917: 
 3918: =item * &get_student_view()
 3919: 
 3920: show a snapshot of what student was looking at
 3921: 
 3922: =cut
 3923: 
 3924: sub get_student_view {
 3925:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3926:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3927:   my (%form);
 3928:   my @elements=('symb','courseid','domain','username');
 3929:   foreach my $element (@elements) {
 3930:       $form{'grade_'.$element}=eval '$'.$element #'
 3931:   }
 3932:   if (defined($moreenv)) {
 3933:       %form=(%form,%{$moreenv});
 3934:   }
 3935:   if (defined($target)) { $form{'grade_target'} = $target; }
 3936:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3937:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3938:   $userview=~s/\<body[^\>]*\>//gi;
 3939:   $userview=~s/\<\/body\>//gi;
 3940:   $userview=~s/\<html\>//gi;
 3941:   $userview=~s/\<\/html\>//gi;
 3942:   $userview=~s/\<head\>//gi;
 3943:   $userview=~s/\<\/head\>//gi;
 3944:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3945:   $userview=&relative_to_absolute($feedurl,$userview);
 3946:   if (wantarray) {
 3947:      return ($userview,$response);
 3948:   } else {
 3949:      return $userview;
 3950:   }
 3951: }
 3952: 
 3953: sub get_student_view_with_retries {
 3954:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3955: 
 3956:     my $ok = 0;                 # True if we got a good response.
 3957:     my $content;
 3958:     my $response;
 3959: 
 3960:     # Try to get the student_view done. within the retries count:
 3961:     
 3962:     do {
 3963:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3964:          $ok      = $response->is_success;
 3965:          if (!$ok) {
 3966:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3967:          }
 3968:          $retries--;
 3969:     } while (!$ok && ($retries > 0));
 3970:     
 3971:     if (!$ok) {
 3972:        $content = '';          # On error return an empty content.
 3973:     }
 3974:     if (wantarray) {
 3975:        return ($content, $response);
 3976:     } else {
 3977:        return $content;
 3978:     }
 3979: }
 3980: 
 3981: =pod
 3982: 
 3983: =item * &get_student_answers() 
 3984: 
 3985: show a snapshot of how student was answering problem
 3986: 
 3987: =cut
 3988: 
 3989: sub get_student_answers {
 3990:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3991:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3992:   my (%moreenv);
 3993:   my @elements=('symb','courseid','domain','username');
 3994:   foreach my $element (@elements) {
 3995:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3996:   }
 3997:   $moreenv{'grade_target'}='answer';
 3998:   %moreenv=(%form,%moreenv);
 3999:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4000:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4001:   return $userview;
 4002: }
 4003: 
 4004: =pod
 4005: 
 4006: =item * &submlink()
 4007: 
 4008: Inputs: $text $uname $udom $symb $target
 4009: 
 4010: Returns: A link to grades.pm such as to see the SUBM view of a student
 4011: 
 4012: =cut
 4013: 
 4014: ###############################################
 4015: sub submlink {
 4016:     my ($text,$uname,$udom,$symb,$target)=@_;
 4017:     if (!($uname && $udom)) {
 4018: 	(my $cursymb, my $courseid,$udom,$uname)=
 4019: 	    &Apache::lonnet::whichuser($symb);
 4020: 	if (!$symb) { $symb=$cursymb; }
 4021:     }
 4022:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4023:     $symb=&escape($symb);
 4024:     if ($target) { $target=" target=\"$target\""; }
 4025:     return
 4026:         '<a href="/adm/grades?command=submission'.
 4027:         '&amp;symb='.$symb.
 4028:         '&amp;student='.$uname.
 4029:         '&amp;userdom='.$udom.'"'.
 4030:         $target.'>'.$text.'</a>';
 4031: }
 4032: ##############################################
 4033: 
 4034: =pod
 4035: 
 4036: =item * &pgrdlink()
 4037: 
 4038: Inputs: $text $uname $udom $symb $target
 4039: 
 4040: Returns: A link to grades.pm such as to see the PGRD view of a student
 4041: 
 4042: =cut
 4043: 
 4044: ###############################################
 4045: sub pgrdlink {
 4046:     my $link=&submlink(@_);
 4047:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4048:     return $link;
 4049: }
 4050: ##############################################
 4051: 
 4052: =pod
 4053: 
 4054: =item * &pprmlink()
 4055: 
 4056: Inputs: $text $uname $udom $symb $target
 4057: 
 4058: Returns: A link to parmset.pm such as to see the PPRM view of a
 4059: student and a specific resource
 4060: 
 4061: =cut
 4062: 
 4063: ###############################################
 4064: sub pprmlink {
 4065:     my ($text,$uname,$udom,$symb,$target)=@_;
 4066:     if (!($uname && $udom)) {
 4067: 	(my $cursymb, my $courseid,$udom,$uname)=
 4068: 	    &Apache::lonnet::whichuser($symb);
 4069: 	if (!$symb) { $symb=$cursymb; }
 4070:     }
 4071:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4072:     $symb=&escape($symb);
 4073:     if ($target) { $target="target=\"$target\""; }
 4074:     return '<a href="/adm/parmset?command=set&amp;'.
 4075: 	'symb='.$symb.'&amp;uname='.$uname.
 4076: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4077: }
 4078: ##############################################
 4079: 
 4080: =pod
 4081: 
 4082: =back
 4083: 
 4084: =cut
 4085: 
 4086: ###############################################
 4087: 
 4088: 
 4089: sub timehash {
 4090:     my ($thistime) = @_;
 4091:     my $timezone = &Apache::lonlocal::gettimezone();
 4092:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4093:                      ->set_time_zone($timezone);
 4094:     my $wday = $dt->day_of_week();
 4095:     if ($wday == 7) { $wday = 0; }
 4096:     return ( 'second' => $dt->second(),
 4097:              'minute' => $dt->minute(),
 4098:              'hour'   => $dt->hour(),
 4099:              'day'     => $dt->day_of_month(),
 4100:              'month'   => $dt->month(),
 4101:              'year'    => $dt->year(),
 4102:              'weekday' => $wday,
 4103:              'dayyear' => $dt->day_of_year(),
 4104:              'dlsav'   => $dt->is_dst() );
 4105: }
 4106: 
 4107: sub utc_string {
 4108:     my ($date)=@_;
 4109:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4110: }
 4111: 
 4112: sub maketime {
 4113:     my %th=@_;
 4114:     my ($epoch_time,$timezone,$dt);
 4115:     $timezone = &Apache::lonlocal::gettimezone();
 4116:     eval {
 4117:         $dt = DateTime->new( year   => $th{'year'},
 4118:                              month  => $th{'month'},
 4119:                              day    => $th{'day'},
 4120:                              hour   => $th{'hour'},
 4121:                              minute => $th{'minute'},
 4122:                              second => $th{'second'},
 4123:                              time_zone => $timezone,
 4124:                          );
 4125:     };
 4126:     if (!$@) {
 4127:         $epoch_time = $dt->epoch;
 4128:         if ($epoch_time) {
 4129:             return $epoch_time;
 4130:         }
 4131:     }
 4132:     return POSIX::mktime(
 4133:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4134:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4135: }
 4136: 
 4137: #########################################
 4138: 
 4139: sub findallcourses {
 4140:     my ($roles,$uname,$udom) = @_;
 4141:     my %roles;
 4142:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4143:     my %courses;
 4144:     my $now=time;
 4145:     if (!defined($uname)) {
 4146:         $uname = $env{'user.name'};
 4147:     }
 4148:     if (!defined($udom)) {
 4149:         $udom = $env{'user.domain'};
 4150:     }
 4151:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4152:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4153:         if (!%roles) {
 4154:             %roles = (
 4155:                        cc => 1,
 4156:                        co => 1,
 4157:                        in => 1,
 4158:                        ep => 1,
 4159:                        ta => 1,
 4160:                        cr => 1,
 4161:                        st => 1,
 4162:              );
 4163:         }
 4164:         foreach my $entry (keys(%roleshash)) {
 4165:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4166:             if ($trole =~ /^cr/) { 
 4167:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4168:             } else {
 4169:                 next if (!exists($roles{$trole}));
 4170:             }
 4171:             if ($tend) {
 4172:                 next if ($tend < $now);
 4173:             }
 4174:             if ($tstart) {
 4175:                 next if ($tstart > $now);
 4176:             }
 4177:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4178:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4179:             my $value = $trole.'/'.$cdom.'/';
 4180:             if ($secpart eq '') {
 4181:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4182:                 $sec = 'none';
 4183:                 $value .= $cnum.'/';
 4184:             } else {
 4185:                 $cnum = $cnumpart;
 4186:                 ($sec,$role) = split(/_/,$secpart);
 4187:                 $value .= $cnum.'/'.$sec;
 4188:             }
 4189:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4190:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4191:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4192:                 }
 4193:             } else {
 4194:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4195:             }
 4196:         }
 4197:     } else {
 4198:         foreach my $key (keys(%env)) {
 4199: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4200:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4201: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4202: 	        next if ($role eq 'ca' || $role eq 'aa');
 4203: 	        next if (%roles && !exists($roles{$role}));
 4204: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4205:                 my $active=1;
 4206:                 if ($starttime) {
 4207: 		    if ($now<$starttime) { $active=0; }
 4208:                 }
 4209:                 if ($endtime) {
 4210:                     if ($now>$endtime) { $active=0; }
 4211:                 }
 4212:                 if ($active) {
 4213:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4214:                     if ($sec eq '') {
 4215:                         $sec = 'none';
 4216:                     } else {
 4217:                         $value .= $sec;
 4218:                     }
 4219:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4220:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4221:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4222:                         }
 4223:                     } else {
 4224:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4225:                     }
 4226:                 }
 4227:             }
 4228:         }
 4229:     }
 4230:     return %courses;
 4231: }
 4232: 
 4233: ###############################################
 4234: 
 4235: sub blockcheck {
 4236:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4237: 
 4238:     if (!defined($udom)) {
 4239:         $udom = $env{'user.domain'};
 4240:     }
 4241:     if (!defined($uname)) {
 4242:         $uname = $env{'user.name'};
 4243:     }
 4244: 
 4245:     # If uname and udom are for a course, check for blocks in the course.
 4246: 
 4247:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4248:         my ($startblock,$endblock,$triggerblock) = 
 4249:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4250:         return ($startblock,$endblock,$triggerblock);
 4251:     }
 4252: 
 4253:     my $startblock = 0;
 4254:     my $endblock = 0;
 4255:     my $triggerblock = '';
 4256:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4257: 
 4258:     # If uname is for a user, and activity is course-specific, i.e.,
 4259:     # boards, chat or groups, check for blocking in current course only.
 4260: 
 4261:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4262:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4263:         foreach my $key (keys(%live_courses)) {
 4264:             if ($key ne $env{'request.course.id'}) {
 4265:                 delete($live_courses{$key});
 4266:             }
 4267:         }
 4268:     }
 4269: 
 4270:     my $otheruser = 0;
 4271:     my %own_courses;
 4272:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4273:         # Resource belongs to user other than current user.
 4274:         $otheruser = 1;
 4275:         # Gather courses for current user
 4276:         %own_courses = 
 4277:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4278:     }
 4279: 
 4280:     # Gather active course roles - course coordinator, instructor, 
 4281:     # exam proctor, ta, student, or custom role.
 4282: 
 4283:     foreach my $course (keys(%live_courses)) {
 4284:         my ($cdom,$cnum);
 4285:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4286:             $cdom = $env{'course.'.$course.'.domain'};
 4287:             $cnum = $env{'course.'.$course.'.num'};
 4288:         } else {
 4289:             ($cdom,$cnum) = split(/_/,$course); 
 4290:         }
 4291:         my $no_ownblock = 0;
 4292:         my $no_userblock = 0;
 4293:         if ($otheruser && $activity ne 'com') {
 4294:             # Check if current user has 'evb' priv for this
 4295:             if (defined($own_courses{$course})) {
 4296:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4297:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4298:                     if ($sec ne 'none') {
 4299:                         $checkrole .= '/'.$sec;
 4300:                     }
 4301:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4302:                         $no_ownblock = 1;
 4303:                         last;
 4304:                     }
 4305:                 }
 4306:             }
 4307:             # if they have 'evb' priv and are currently not playing student
 4308:             next if (($no_ownblock) &&
 4309:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4310:         }
 4311:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4312:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4313:             if ($sec ne 'none') {
 4314:                 $checkrole .= '/'.$sec;
 4315:             }
 4316:             if ($otheruser) {
 4317:                 # Resource belongs to user other than current user.
 4318:                 # Assemble privs for that user, and check for 'evb' priv.
 4319:                 my (%allroles,%userroles);
 4320:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4321:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4322:                         my ($trole,$tdom,$tnum,$tsec);
 4323:                         if ($entry =~ /^cr/) {
 4324:                             ($trole,$tdom,$tnum,$tsec) = 
 4325:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4326:                         } else {
 4327:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4328:                         }
 4329:                         my ($spec,$area,$trest);
 4330:                         $area = '/'.$tdom.'/'.$tnum;
 4331:                         $trest = $tnum;
 4332:                         if ($tsec ne '') {
 4333:                             $area .= '/'.$tsec;
 4334:                             $trest .= '/'.$tsec;
 4335:                         }
 4336:                         $spec = $trole.'.'.$area;
 4337:                         if ($trole =~ /^cr/) {
 4338:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4339:                                                               $tdom,$spec,$trest,$area);
 4340:                         } else {
 4341:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4342:                                                                 $tdom,$spec,$trest,$area);
 4343:                         }
 4344:                     }
 4345:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4346:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4347:                         if ($1) {
 4348:                             $no_userblock = 1;
 4349:                             last;
 4350:                         }
 4351:                     }
 4352:                 }
 4353:             } else {
 4354:                 # Resource belongs to current user
 4355:                 # Check for 'evb' priv via lonnet::allowed().
 4356:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4357:                     $no_ownblock = 1;
 4358:                     last;
 4359:                 }
 4360:             }
 4361:         }
 4362:         # if they have the evb priv and are currently not playing student
 4363:         next if (($no_ownblock) &&
 4364:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4365:         next if ($no_userblock);
 4366: 
 4367:         # Retrieve blocking times and identity of locker for course
 4368:         # of specified user, unless user has 'evb' privilege.
 4369:         
 4370:         my ($start,$end,$trigger) = 
 4371:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4372:         if (($start != 0) && 
 4373:             (($startblock == 0) || ($startblock > $start))) {
 4374:             $startblock = $start;
 4375:             if ($trigger ne '') {
 4376:                 $triggerblock = $trigger;
 4377:             }
 4378:         }
 4379:         if (($end != 0)  &&
 4380:             (($endblock == 0) || ($endblock < $end))) {
 4381:             $endblock = $end;
 4382:             if ($trigger ne '') {
 4383:                 $triggerblock = $trigger;
 4384:             }
 4385:         }
 4386:     }
 4387:     return ($startblock,$endblock,$triggerblock);
 4388: }
 4389: 
 4390: sub get_blocks {
 4391:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4392:     my $startblock = 0;
 4393:     my $endblock = 0;
 4394:     my $triggerblock = '';
 4395:     my $course = $cdom.'_'.$cnum;
 4396:     $setters->{$course} = {};
 4397:     $setters->{$course}{'staff'} = [];
 4398:     $setters->{$course}{'times'} = [];
 4399:     $setters->{$course}{'triggers'} = [];
 4400:     my (@blockers,%triggered);
 4401:     my $now = time;
 4402:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4403:     if ($activity eq 'docs') {
 4404:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4405:         foreach my $block (@blockers) {
 4406:             if ($block =~ /^firstaccess____(.+)$/) {
 4407:                 my $item = $1;
 4408:                 my $type = 'map';
 4409:                 my $timersymb = $item;
 4410:                 if ($item eq 'course') {
 4411:                     $type = 'course';
 4412:                 } elsif ($item =~ /___\d+___/) {
 4413:                     $type = 'resource';
 4414:                 } else {
 4415:                     $timersymb = &Apache::lonnet::symbread($item);
 4416:                 }
 4417:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4418:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4419:                 $triggered{$block} = {
 4420:                                        start => $start,
 4421:                                        end   => $end,
 4422:                                        type  => $type,
 4423:                                      };
 4424:             }
 4425:         }
 4426:     } else {
 4427:         foreach my $block (keys(%commblocks)) {
 4428:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4429:                 my ($start,$end) = ($1,$2);
 4430:                 if ($start <= time && $end >= time) {
 4431:                     if (ref($commblocks{$block}) eq 'HASH') {
 4432:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4433:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4434:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4435:                                     push(@blockers,$block);
 4436:                                 }
 4437:                             }
 4438:                         }
 4439:                     }
 4440:                 }
 4441:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4442:                 my $item = $1;
 4443:                 my $timersymb = $item; 
 4444:                 my $type = 'map';
 4445:                 if ($item eq 'course') {
 4446:                     $type = 'course';
 4447:                 } elsif ($item =~ /___\d+___/) {
 4448:                     $type = 'resource';
 4449:                 } else {
 4450:                     $timersymb = &Apache::lonnet::symbread($item);
 4451:                 }
 4452:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4453:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4454:                 if ($start && $end) {
 4455:                     if (($start <= time) && ($end >= time)) {
 4456:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4457:                             push(@blockers,$block);
 4458:                             $triggered{$block} = {
 4459:                                                    start => $start,
 4460:                                                    end   => $end,
 4461:                                                    type  => $type,
 4462:                                                  };
 4463:                         }
 4464:                     }
 4465:                 }
 4466:             }
 4467:         }
 4468:     }
 4469:     foreach my $blocker (@blockers) {
 4470:         my ($staff_name,$staff_dom,$title,$blocks) =
 4471:             &parse_block_record($commblocks{$blocker});
 4472:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4473:         my ($start,$end,$triggertype);
 4474:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4475:             ($start,$end) = ($1,$2);
 4476:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4477:             $start = $triggered{$blocker}{'start'};
 4478:             $end = $triggered{$blocker}{'end'};
 4479:             $triggertype = $triggered{$blocker}{'type'};
 4480:         }
 4481:         if ($start) {
 4482:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4483:             if ($triggertype) {
 4484:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4485:             } else {
 4486:                 push(@{$$setters{$course}{'triggers'}},0);
 4487:             }
 4488:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4489:                 $startblock = $start;
 4490:                 if ($triggertype) {
 4491:                     $triggerblock = $blocker;
 4492:                 }
 4493:             }
 4494:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4495:                $endblock = $end;
 4496:                if ($triggertype) {
 4497:                    $triggerblock = $blocker;
 4498:                }
 4499:             }
 4500:         }
 4501:     }
 4502:     return ($startblock,$endblock,$triggerblock);
 4503: }
 4504: 
 4505: sub parse_block_record {
 4506:     my ($record) = @_;
 4507:     my ($setuname,$setudom,$title,$blocks);
 4508:     if (ref($record) eq 'HASH') {
 4509:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4510:         $title = &unescape($record->{'event'});
 4511:         $blocks = $record->{'blocks'};
 4512:     } else {
 4513:         my @data = split(/:/,$record,3);
 4514:         if (scalar(@data) eq 2) {
 4515:             $title = $data[1];
 4516:             ($setuname,$setudom) = split(/@/,$data[0]);
 4517:         } else {
 4518:             ($setuname,$setudom,$title) = @data;
 4519:         }
 4520:         $blocks = { 'com' => 'on' };
 4521:     }
 4522:     return ($setuname,$setudom,$title,$blocks);
 4523: }
 4524: 
 4525: sub blocking_status {
 4526:     my ($activity,$uname,$udom,$url) = @_;
 4527:     my %setters;
 4528: 
 4529: # check for active blocking
 4530:     my ($startblock,$endblock,$triggerblock) = 
 4531:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4532:     my $blocked = 0;
 4533:     if ($startblock && $endblock) {
 4534:         $blocked = 1;
 4535:     }
 4536: 
 4537: # caller just wants to know whether a block is active
 4538:     if (!wantarray) { return $blocked; }
 4539: 
 4540: # build a link to a popup window containing the details
 4541:     my $querystring  = "?activity=$activity";
 4542: # $uname and $udom decide whose portfolio the user is trying to look at
 4543:     if ($activity eq 'port') {
 4544:         $querystring .= "&amp;udom=$udom"      if $udom;
 4545:         $querystring .= "&amp;uname=$uname"    if $uname;
 4546:     } elsif ($activity eq 'docs') {
 4547:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4548:     }
 4549: 
 4550:     my $output .= <<'END_MYBLOCK';
 4551: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4552:     var options = "width=" + w + ",height=" + h + ",";
 4553:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4554:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4555:     var newWin = window.open(url, wdwName, options);
 4556:     newWin.focus();
 4557: }
 4558: END_MYBLOCK
 4559: 
 4560:     $output = Apache::lonhtmlcommon::scripttag($output);
 4561:   
 4562:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4563:     my $text = &mt('Communication Blocked');
 4564:     if ($activity eq 'docs') {
 4565:         $text = &mt('Content Access Blocked');
 4566:     } elsif ($activity eq 'printout') {
 4567:         $text = &mt('Printing Blocked');
 4568:     }
 4569:     $output .= <<"END_BLOCK";
 4570: <div class='LC_comblock'>
 4571:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4572:   title='$text'>
 4573:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4574:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4575:   title='$text'>$text</a>
 4576: </div>
 4577: 
 4578: END_BLOCK
 4579: 
 4580:     return ($blocked, $output);
 4581: }
 4582: 
 4583: ###############################################
 4584: 
 4585: sub check_ip_acc {
 4586:     my ($acc)=@_;
 4587:     &Apache::lonxml::debug("acc is $acc");
 4588:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4589:         return 1;
 4590:     }
 4591:     my $allowed=0;
 4592:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4593: 
 4594:     my $name;
 4595:     foreach my $pattern (split(',',$acc)) {
 4596:         $pattern =~ s/^\s*//;
 4597:         $pattern =~ s/\s*$//;
 4598:         if ($pattern =~ /\*$/) {
 4599:             #35.8.*
 4600:             $pattern=~s/\*//;
 4601:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4602:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4603:             #35.8.3.[34-56]
 4604:             my $low=$2;
 4605:             my $high=$3;
 4606:             $pattern=$1;
 4607:             if ($ip =~ /^\Q$pattern\E/) {
 4608:                 my $last=(split(/\./,$ip))[3];
 4609:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4610:             }
 4611:         } elsif ($pattern =~ /^\*/) {
 4612:             #*.msu.edu
 4613:             $pattern=~s/\*//;
 4614:             if (!defined($name)) {
 4615:                 use Socket;
 4616:                 my $netaddr=inet_aton($ip);
 4617:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4618:             }
 4619:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4620:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4621:             #127.0.0.1
 4622:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4623:         } else {
 4624:             #some.name.com
 4625:             if (!defined($name)) {
 4626:                 use Socket;
 4627:                 my $netaddr=inet_aton($ip);
 4628:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4629:             }
 4630:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4631:         }
 4632:         if ($allowed) { last; }
 4633:     }
 4634:     return $allowed;
 4635: }
 4636: 
 4637: ###############################################
 4638: 
 4639: =pod
 4640: 
 4641: =head1 Domain Template Functions
 4642: 
 4643: =over 4
 4644: 
 4645: =item * &determinedomain()
 4646: 
 4647: Inputs: $domain (usually will be undef)
 4648: 
 4649: Returns: Determines which domain should be used for designs
 4650: 
 4651: =cut
 4652: 
 4653: ###############################################
 4654: sub determinedomain {
 4655:     my $domain=shift;
 4656:     if (! $domain) {
 4657:         # Determine domain if we have not been given one
 4658:         $domain = &Apache::lonnet::default_login_domain();
 4659:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4660:         if ($env{'request.role.domain'}) { 
 4661:             $domain=$env{'request.role.domain'}; 
 4662:         }
 4663:     }
 4664:     return $domain;
 4665: }
 4666: ###############################################
 4667: 
 4668: sub devalidate_domconfig_cache {
 4669:     my ($udom)=@_;
 4670:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4671: }
 4672: 
 4673: # ---------------------- Get domain configuration for a domain
 4674: sub get_domainconf {
 4675:     my ($udom) = @_;
 4676:     my $cachetime=1800;
 4677:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4678:     if (defined($cached)) { return %{$result}; }
 4679: 
 4680:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4681: 					     ['login','rolecolors','autoenroll'],$udom);
 4682:     my (%designhash,%legacy);
 4683:     if (keys(%domconfig) > 0) {
 4684:         if (ref($domconfig{'login'}) eq 'HASH') {
 4685:             if (keys(%{$domconfig{'login'}})) {
 4686:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4687:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4688:                         if ($key eq 'loginvia') {
 4689:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4690:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4691:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4692:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4693:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4694:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4695:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4696: 
 4697:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4698:                                             } else {
 4699:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4700:                                             }
 4701:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4702:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4703:                                             }
 4704:                                         }
 4705:                                     }
 4706:                                 }
 4707:                             }
 4708:                         } else {
 4709:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4710:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4711:                                     $domconfig{'login'}{$key}{$img};
 4712:                             }
 4713:                         }
 4714:                     } else {
 4715:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4716:                     }
 4717:                 }
 4718:             } else {
 4719:                 $legacy{'login'} = 1;
 4720:             }
 4721:         } else {
 4722:             $legacy{'login'} = 1;
 4723:         }
 4724:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4725:             if (keys(%{$domconfig{'rolecolors'}})) {
 4726:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4727:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4728:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4729:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4730:                         }
 4731:                     }
 4732:                 }
 4733:             } else {
 4734:                 $legacy{'rolecolors'} = 1;
 4735:             }
 4736:         } else {
 4737:             $legacy{'rolecolors'} = 1;
 4738:         }
 4739:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4740:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4741:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4742:             }
 4743:         }
 4744:         if (keys(%legacy) > 0) {
 4745:             my %legacyhash = &get_legacy_domconf($udom);
 4746:             foreach my $item (keys(%legacyhash)) {
 4747:                 if ($item =~ /^\Q$udom\E\.login/) {
 4748:                     if ($legacy{'login'}) { 
 4749:                         $designhash{$item} = $legacyhash{$item};
 4750:                     }
 4751:                 } else {
 4752:                     if ($legacy{'rolecolors'}) {
 4753:                         $designhash{$item} = $legacyhash{$item};
 4754:                     }
 4755:                 }
 4756:             }
 4757:         }
 4758:     } else {
 4759:         %designhash = &get_legacy_domconf($udom); 
 4760:     }
 4761:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4762: 				  $cachetime);
 4763:     return %designhash;
 4764: }
 4765: 
 4766: sub get_legacy_domconf {
 4767:     my ($udom) = @_;
 4768:     my %legacyhash;
 4769:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4770:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4771:     if (-e $designfile) {
 4772:         if ( open (my $fh,"<$designfile") ) {
 4773:             while (my $line = <$fh>) {
 4774:                 next if ($line =~ /^\#/);
 4775:                 chomp($line);
 4776:                 my ($key,$val)=(split(/\=/,$line));
 4777:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4778:             }
 4779:             close($fh);
 4780:         }
 4781:     }
 4782:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4783:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4784:     }
 4785:     return %legacyhash;
 4786: }
 4787: 
 4788: =pod
 4789: 
 4790: =item * &domainlogo()
 4791: 
 4792: Inputs: $domain (usually will be undef)
 4793: 
 4794: Returns: A link to a domain logo, if the domain logo exists.
 4795: If the domain logo does not exist, a description of the domain.
 4796: 
 4797: =cut
 4798: 
 4799: ###############################################
 4800: sub domainlogo {
 4801:     my $domain = &determinedomain(shift);
 4802:     my %designhash = &get_domainconf($domain);    
 4803:     # See if there is a logo
 4804:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4805:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4806:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4807: 	    if ($imgsrc =~ m{^/res/}) {
 4808: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4809: 		&Apache::lonnet::repcopy($local_name);
 4810: 	    }
 4811: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4812:         } 
 4813:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4814:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4815:         return &Apache::lonnet::domain($domain,'description');
 4816:     } else {
 4817:         return '';
 4818:     }
 4819: }
 4820: ##############################################
 4821: 
 4822: =pod
 4823: 
 4824: =item * &designparm()
 4825: 
 4826: Inputs: $which parameter; $domain (usually will be undef)
 4827: 
 4828: Returns: value of designparamter $which
 4829: 
 4830: =cut
 4831: 
 4832: 
 4833: ##############################################
 4834: sub designparm {
 4835:     my ($which,$domain)=@_;
 4836:     if (exists($env{'environment.color.'.$which})) {
 4837:         return $env{'environment.color.'.$which};
 4838:     }
 4839:     $domain=&determinedomain($domain);
 4840:     my %domdesign;
 4841:     unless ($domain eq 'public') {
 4842:         %domdesign = &get_domainconf($domain);
 4843:     }
 4844:     my $output;
 4845:     if ($domdesign{$domain.'.'.$which} ne '') {
 4846:         $output = $domdesign{$domain.'.'.$which};
 4847:     } else {
 4848:         $output = $defaultdesign{$which};
 4849:     }
 4850:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4851:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4852:         if ($output =~ m{^/(adm|res)/}) {
 4853:             if ($output =~ m{^/res/}) {
 4854:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4855:                 &Apache::lonnet::repcopy($local_name);
 4856:             }
 4857:             $output = &lonhttpdurl($output);
 4858:         }
 4859:     }
 4860:     return $output;
 4861: }
 4862: 
 4863: ##############################################
 4864: =pod
 4865: 
 4866: =item * &authorspace()
 4867: 
 4868: Inputs: $url (usually will be undef).
 4869: 
 4870: Returns: Path to Authoring Space containing the resource or 
 4871:          directory being viewed (or for which action is being taken). 
 4872:          If $url is provided, and begins /priv/<domain>/<uname>
 4873:          the path will be that portion of the $context argument.
 4874:          Otherwise the path will be for the author space of the current
 4875:          user when the current role is author, or for that of the 
 4876:          co-author/assistant co-author space when the current role 
 4877:          is co-author or assistant co-author.
 4878: 
 4879: =cut
 4880: 
 4881: sub authorspace {
 4882:     my ($url) = @_;
 4883:     if ($url ne '') {
 4884:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4885:            return $1;
 4886:         }
 4887:     }
 4888:     my $caname = '';
 4889:     my $cadom = '';
 4890:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4891:         ($cadom,$caname) =
 4892:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4893:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4894:         $caname = $env{'user.name'};
 4895:         $cadom = $env{'user.domain'};
 4896:     }
 4897:     if (($caname ne '') && ($cadom ne '')) {
 4898:         return "/priv/$cadom/$caname/";
 4899:     }
 4900:     return;
 4901: }
 4902: 
 4903: ##############################################
 4904: =pod
 4905: 
 4906: =item * &head_subbox()
 4907: 
 4908: Inputs: $content (contains HTML code with page functions, etc.)
 4909: 
 4910: Returns: HTML div with $content
 4911:          To be included in page header
 4912: 
 4913: =cut
 4914: 
 4915: sub head_subbox {
 4916:     my ($content)=@_;
 4917:     my $output =
 4918:         '<div class="LC_head_subbox">'
 4919:        .$content
 4920:        .'</div>'
 4921: }
 4922: 
 4923: ##############################################
 4924: =pod
 4925: 
 4926: =item * &CSTR_pageheader()
 4927: 
 4928: Input: (optional) filename from which breadcrumb trail is built.
 4929:        In most cases no input as needed, as $env{'request.filename'}
 4930:        is appropriate for use in building the breadcrumb trail.
 4931: 
 4932: Returns: HTML div with CSTR path and recent box
 4933:          To be included on Authoring Space pages
 4934: 
 4935: =cut
 4936: 
 4937: sub CSTR_pageheader {
 4938:     my ($trailfile) = @_;
 4939:     if ($trailfile eq '') {
 4940:         $trailfile = $env{'request.filename'};
 4941:     }
 4942: 
 4943: # this is for resources; directories have customtitle, and crumbs
 4944: # and select recent are created in lonpubdir.pm
 4945: 
 4946:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4947:     my ($udom,$uname,$thisdisfn)=
 4948:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 4949:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4950:     $formaction =~ s{/+}{/}g;
 4951: 
 4952:     my $parentpath = '';
 4953:     my $lastitem = '';
 4954:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4955:         $parentpath = $1;
 4956:         $lastitem = $2;
 4957:     } else {
 4958:         $lastitem = $thisdisfn;
 4959:     }
 4960: 
 4961:     my $output =
 4962:          '<div>'
 4963:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4964:         .'<b>'.&mt('Authoring Space:').'</b> '
 4965:         .'<form name="dirs" method="post" action="'.$formaction
 4966:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4967:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4968: 
 4969:     if ($lastitem) {
 4970:         $output .=
 4971:              '<span class="LC_filename">'
 4972:             .$lastitem
 4973:             .'</span>';
 4974:     }
 4975:     $output .=
 4976:          '<br />'
 4977:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4978:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4979:         .'</form>'
 4980:         .&Apache::lonmenu::constspaceform()
 4981:         .'</div>';
 4982: 
 4983:     return $output;
 4984: }
 4985: 
 4986: ###############################################
 4987: ###############################################
 4988: 
 4989: =pod
 4990: 
 4991: =back
 4992: 
 4993: =head1 HTML Helpers
 4994: 
 4995: =over 4
 4996: 
 4997: =item * &bodytag()
 4998: 
 4999: Returns a uniform header for LON-CAPA web pages.
 5000: 
 5001: Inputs: 
 5002: 
 5003: =over 4
 5004: 
 5005: =item * $title, A title to be displayed on the page.
 5006: 
 5007: =item * $function, the current role (can be undef).
 5008: 
 5009: =item * $addentries, extra parameters for the <body> tag.
 5010: 
 5011: =item * $bodyonly, if defined, only return the <body> tag.
 5012: 
 5013: =item * $domain, if defined, force a given domain.
 5014: 
 5015: =item * $forcereg, if page should register as content page (relevant for 
 5016:             text interface only)
 5017: 
 5018: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5019:                      navigational links
 5020: 
 5021: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5022: 
 5023: =item * $no_inline_link, if true and in remote mode, don't show the
 5024:          'Switch To Inline Menu' link
 5025: 
 5026: =item * $args, optional argument valid values are
 5027:             no_auto_mt_title -> prevents &mt()ing the title arg
 5028:             inherit_jsmath -> when creating popup window in a page,
 5029:                               should it have jsmath forced on by the
 5030:                               current page
 5031: 
 5032: =item * $advtoolsref, optional argument, ref to an array containing
 5033:             inlineremote items to be added in "Functions" menu below
 5034:             breadcrumbs.
 5035: 
 5036: =back
 5037: 
 5038: Returns: A uniform header for LON-CAPA web pages.  
 5039: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5040: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5041: other decorations will be returned.
 5042: 
 5043: =cut
 5044: 
 5045: sub bodytag {
 5046:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5047:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5048: 
 5049:     my $public;
 5050:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5051:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5052:         $public = 1;
 5053:     }
 5054:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5055:     my $httphost = $args->{'use_absolute'};
 5056: 
 5057:     $function = &get_users_function() if (!$function);
 5058:     my $img =    &designparm($function.'.img',$domain);
 5059:     my $font =   &designparm($function.'.font',$domain);
 5060:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5061: 
 5062:     my %design = ( 'style'   => 'margin-top: 0',
 5063: 		   'bgcolor' => $pgbg,
 5064: 		   'text'    => $font,
 5065:                    'alink'   => &designparm($function.'.alink',$domain),
 5066: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5067: 		   'link'    => &designparm($function.'.link',$domain),);
 5068:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5069: 
 5070:  # role and realm
 5071:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5072:     if ($role  eq 'ca') {
 5073:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5074:         $realm = &plainname($rname,$rdom);
 5075:     } 
 5076: # realm
 5077:     if ($env{'request.course.id'}) {
 5078:         if ($env{'request.role'} !~ /^cr/) {
 5079:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5080:         }
 5081:         if ($env{'request.course.sec'}) {
 5082:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5083:         }   
 5084: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5085:     } else {
 5086:         $role = &Apache::lonnet::plaintext($role);
 5087:     }
 5088: 
 5089:     if (!$realm) { $realm='&nbsp;'; }
 5090: 
 5091:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5092: 
 5093: # construct main body tag
 5094:     my $bodytag = "<body $extra_body_attr>".
 5095: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5096: 
 5097:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5098: 
 5099:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5100:         return $bodytag;
 5101:     }
 5102: 
 5103:     if ($public) {
 5104: 	undef($role);
 5105:     }
 5106:     
 5107:     my $titleinfo = '<h1>'.$title.'</h1>';
 5108:     #
 5109:     # Extra info if you are the DC
 5110:     my $dc_info = '';
 5111:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5112:                         $env{'course.'.$env{'request.course.id'}.
 5113:                                  '.domain'}.'/'})) {
 5114:         my $cid = $env{'request.course.id'};
 5115:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5116:         $dc_info =~ s/\s+$//;
 5117:     }
 5118: 
 5119:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5120: 
 5121:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5122: 
 5123: 
 5124: 
 5125:     my $funclist;
 5126:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5127:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5128:                     Apache::lonmenu::serverform();
 5129:         my $forbodytag;
 5130:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5131:                                             $forcereg,$args->{'group'},
 5132:                                             $args->{'bread_crumbs'},
 5133:                                             $advtoolsref,'',\$forbodytag);
 5134:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5135:             $funclist = $forbodytag;
 5136:         }
 5137:     } else {
 5138: 
 5139:         #    if ($env{'request.state'} eq 'construct') {
 5140:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5141:         #    }
 5142: 
 5143:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5144:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5145: 
 5146:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5147: 
 5148:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5149:             if ($dc_info) {
 5150:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5151:             }
 5152:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5153:                            <em>$realm</em> $dc_info</div>|;
 5154:             return $bodytag;
 5155:         }
 5156: 
 5157:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5158:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5159:         }
 5160: 
 5161:         $bodytag .= $right;
 5162: 
 5163:         if ($dc_info) {
 5164:             $dc_info = &dc_courseid_toggle($dc_info);
 5165:         }
 5166:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5167: 
 5168:         #if directed to not display the secondary menu, don't.
 5169:         if ($args->{'no_secondary_menu'}) {
 5170:             return $bodytag;
 5171:         }
 5172:         #don't show menus for public users
 5173:         if (!$public){
 5174:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5175:             $bodytag .= Apache::lonmenu::serverform();
 5176:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5177:             if ($env{'request.state'} eq 'construct') {
 5178:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5179:                                 $args->{'bread_crumbs'});
 5180:             } elsif ($forcereg) { 
 5181:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5182:                                                             $args->{'group'});
 5183:             } else {
 5184:                 my $forbodytag;
 5185:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5186:                                                     $forcereg,$args->{'group'},
 5187:                                                     $args->{'bread_crumbs'},
 5188:                                                     $advtoolsref,'',\$forbodytag);
 5189:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5190:                     $bodytag .= $forbodytag;
 5191:                 }
 5192:             }
 5193:         }else{
 5194:             # this is to seperate menu from content when there's no secondary
 5195:             # menu. Especially needed for public accessible ressources.
 5196:             $bodytag .= '<hr style="clear:both" />';
 5197:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5198:         }
 5199: 
 5200:         return $bodytag;
 5201:     }
 5202: 
 5203: #
 5204: # Top frame rendering, Remote is up
 5205: #
 5206: 
 5207:     my $imgsrc = $img;
 5208:     if ($img =~ /^\/adm/) {
 5209:         $imgsrc = &lonhttpdurl($img);
 5210:     }
 5211:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5212: 
 5213:     my $help=($no_inline_link?''
 5214:               :&Apache::loncommon::top_nav_help('Help'));
 5215: 
 5216:     # Explicit link to get inline menu
 5217:     my $menu= ($no_inline_link?''
 5218:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5219: 
 5220:     if ($dc_info) {
 5221:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5222:     }
 5223: 
 5224:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5225:     unless ($public) {
 5226:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5227:                                 undef,'LC_menubuttons_link');
 5228:     }
 5229: 
 5230:     unless ($env{'form.inhibitmenu'}) {
 5231:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5232:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5233:                        <li>$help</li>
 5234:                        <li>$menu</li>
 5235:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5236:     }
 5237:     if ($env{'request.state'} eq 'construct') {
 5238:         if (!$public){
 5239:             if ($env{'request.state'} eq 'construct') {
 5240:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5241:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5242:                             &Apache::lonhtmlcommon::scripttag('','end').
 5243:                             &Apache::lonmenu::innerregister($forcereg,
 5244:                                                             $args->{'bread_crumbs'});
 5245:             }
 5246:         }
 5247:     }
 5248:     return $bodytag."\n".$funclist;
 5249: }
 5250: 
 5251: sub dc_courseid_toggle {
 5252:     my ($dc_info) = @_;
 5253:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5254:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5255:            &mt('(More ...)').'</a></span>'.
 5256:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5257: }
 5258: 
 5259: sub make_attr_string {
 5260:     my ($register,$attr_ref) = @_;
 5261: 
 5262:     if ($attr_ref && !ref($attr_ref)) {
 5263: 	die("addentries Must be a hash ref ".
 5264: 	    join(':',caller(1))." ".
 5265: 	    join(':',caller(0))." ");
 5266:     }
 5267: 
 5268:     if ($register) {
 5269: 	my ($on_load,$on_unload);
 5270: 	foreach my $key (keys(%{$attr_ref})) {
 5271: 	    if      (lc($key) eq 'onload') {
 5272: 		$on_load.=$attr_ref->{$key}.';';
 5273: 		delete($attr_ref->{$key});
 5274: 
 5275: 	    } elsif (lc($key) eq 'onunload') {
 5276: 		$on_unload.=$attr_ref->{$key}.';';
 5277: 		delete($attr_ref->{$key});
 5278: 	    }
 5279: 	}
 5280:         if ($env{'environment.remote'} eq 'on') {
 5281:             $attr_ref->{'onload'}  =
 5282:                 &Apache::lonmenu::loadevents().  $on_load;
 5283:             $attr_ref->{'onunload'}=
 5284:                 &Apache::lonmenu::unloadevents().$on_unload;
 5285:         } else {  
 5286: 	    $attr_ref->{'onload'}  = $on_load;
 5287: 	    $attr_ref->{'onunload'}= $on_unload;
 5288:         }
 5289:     }
 5290: 
 5291:     my $attr_string;
 5292:     foreach my $attr (sort(keys(%$attr_ref))) {
 5293: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5294:     }
 5295:     return $attr_string;
 5296: }
 5297: 
 5298: 
 5299: ###############################################
 5300: ###############################################
 5301: 
 5302: =pod
 5303: 
 5304: =item * &endbodytag()
 5305: 
 5306: Returns a uniform footer for LON-CAPA web pages.
 5307: 
 5308: Inputs: 1 - optional reference to an args hash
 5309: If in the hash, key for noredirectlink has a value which evaluates to true,
 5310: a 'Continue' link is not displayed if the page contains an
 5311: internal redirect in the <head></head> section,
 5312: i.e., $env{'internal.head.redirect'} exists   
 5313: 
 5314: =cut
 5315: 
 5316: sub endbodytag {
 5317:     my ($args) = @_;
 5318:     my $endbodytag;
 5319:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5320:         $endbodytag='</body>';
 5321:     }
 5322:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5323:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5324:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5325: 	    $endbodytag=
 5326: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5327: 	        &mt('Continue').'</a>'.
 5328: 	        $endbodytag;
 5329:         }
 5330:     }
 5331:     return $endbodytag;
 5332: }
 5333: 
 5334: =pod
 5335: 
 5336: =item * &standard_css()
 5337: 
 5338: Returns a style sheet
 5339: 
 5340: Inputs: (all optional)
 5341:             domain         -> force to color decorate a page for a specific
 5342:                                domain
 5343:             function       -> force usage of a specific rolish color scheme
 5344:             bgcolor        -> override the default page bgcolor
 5345: 
 5346: =cut
 5347: 
 5348: sub standard_css {
 5349:     my ($function,$domain,$bgcolor) = @_;
 5350:     $function  = &get_users_function() if (!$function);
 5351:     my $img    = &designparm($function.'.img',   $domain);
 5352:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5353:     my $font   = &designparm($function.'.font',  $domain);
 5354:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5355: #second colour for later usage
 5356:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5357:     my $pgbg_or_bgcolor =
 5358: 	         $bgcolor ||
 5359: 	         &designparm($function.'.pgbg',  $domain);
 5360:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5361:     my $alink  = &designparm($function.'.alink', $domain);
 5362:     my $vlink  = &designparm($function.'.vlink', $domain);
 5363:     my $link   = &designparm($function.'.link',  $domain);
 5364: 
 5365:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5366:     my $mono                 = 'monospace';
 5367:     my $data_table_head      = $sidebg;
 5368:     my $data_table_light     = '#FAFAFA';
 5369:     my $data_table_dark      = '#E0E0E0';
 5370:     my $data_table_darker    = '#CCCCCC';
 5371:     my $data_table_highlight = '#FFFF00';
 5372:     my $mail_new             = '#FFBB77';
 5373:     my $mail_new_hover       = '#DD9955';
 5374:     my $mail_read            = '#BBBB77';
 5375:     my $mail_read_hover      = '#999944';
 5376:     my $mail_replied         = '#AAAA88';
 5377:     my $mail_replied_hover   = '#888855';
 5378:     my $mail_other           = '#99BBBB';
 5379:     my $mail_other_hover     = '#669999';
 5380:     my $table_header         = '#DDDDDD';
 5381:     my $feedback_link_bg     = '#BBBBBB';
 5382:     my $lg_border_color      = '#C8C8C8';
 5383:     my $button_hover         = '#BF2317';
 5384: 
 5385:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5386:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5387:                                              : '0 3px 0 4px';
 5388: 
 5389: 
 5390:     return <<END;
 5391: 
 5392: /* needed for iframe to allow 100% height in FF */
 5393: body, html { 
 5394:     margin: 0;
 5395:     padding: 0 0.5%;
 5396:     height: 99%; /* to avoid scrollbars */
 5397: }
 5398: 
 5399: body {
 5400:   font-family: $sans;
 5401:   line-height:130%;
 5402:   font-size:0.83em;
 5403:   color:$font;
 5404: }
 5405: 
 5406: a:focus,
 5407: a:focus img {
 5408:   color: red;
 5409: }
 5410: 
 5411: form, .inline {
 5412:   display: inline;
 5413: }
 5414: 
 5415: .LC_right {
 5416:   text-align:right;
 5417: }
 5418: 
 5419: .LC_middle {
 5420:   vertical-align:middle;
 5421: }
 5422: 
 5423: .LC_floatleft {
 5424:   float: left;
 5425: }
 5426: 
 5427: .LC_floatright {
 5428:   float: right;
 5429: }
 5430: 
 5431: .LC_400Box {
 5432:   width:400px;
 5433: }
 5434: 
 5435: .LC_iframecontainer {
 5436:     width: 98%;
 5437:     margin: 0;
 5438:     position: fixed;
 5439:     top: 8.5em;
 5440:     bottom: 0;
 5441: }
 5442: 
 5443: .LC_iframecontainer iframe{
 5444:     border: none;
 5445:     width: 100%;
 5446:     height: 100%;
 5447: }
 5448: 
 5449: .LC_filename {
 5450:   font-family: $mono;
 5451:   white-space:pre;
 5452:   font-size: 120%;
 5453: }
 5454: 
 5455: .LC_fileicon {
 5456:   border: none;
 5457:   height: 1.3em;
 5458:   vertical-align: text-bottom;
 5459:   margin-right: 0.3em;
 5460:   text-decoration:none;
 5461: }
 5462: 
 5463: .LC_setting {
 5464:   text-decoration:underline;
 5465: }
 5466: 
 5467: .LC_error {
 5468:   color: red;
 5469: }
 5470: 
 5471: .LC_warning {
 5472:   color: darkorange;
 5473: }
 5474: 
 5475: .LC_diff_removed {
 5476:   color: red;
 5477: }
 5478: 
 5479: .LC_info,
 5480: .LC_success,
 5481: .LC_diff_added {
 5482:   color: green;
 5483: }
 5484: 
 5485: div.LC_confirm_box {
 5486:   background-color: #FAFAFA;
 5487:   border: 1px solid $lg_border_color;
 5488:   margin-right: 0;
 5489:   padding: 5px;
 5490: }
 5491: 
 5492: div.LC_confirm_box .LC_error img,
 5493: div.LC_confirm_box .LC_success img {
 5494:   vertical-align: middle;
 5495: }
 5496: 
 5497: .LC_icon {
 5498:   border: none;
 5499:   vertical-align: middle;
 5500: }
 5501: 
 5502: .LC_docs_spacer {
 5503:   width: 25px;
 5504:   height: 1px;
 5505:   border: none;
 5506: }
 5507: 
 5508: .LC_internal_info {
 5509:   color: #999999;
 5510: }
 5511: 
 5512: .LC_discussion {
 5513:   background: $data_table_dark;
 5514:   border: 1px solid black;
 5515:   margin: 2px;
 5516: }
 5517: 
 5518: .LC_disc_action_left {
 5519:   background: $sidebg;
 5520:   text-align: left;
 5521:   padding: 4px;
 5522:   margin: 2px;
 5523: }
 5524: 
 5525: .LC_disc_action_right {
 5526:   background: $sidebg;
 5527:   text-align: right;
 5528:   padding: 4px;
 5529:   margin: 2px;
 5530: }
 5531: 
 5532: .LC_disc_new_item {
 5533:   background: white;
 5534:   border: 2px solid red;
 5535:   margin: 4px;
 5536:   padding: 4px;
 5537: }
 5538: 
 5539: .LC_disc_old_item {
 5540:   background: white;
 5541:   margin: 4px;
 5542:   padding: 4px;
 5543: }
 5544: 
 5545: table.LC_pastsubmission {
 5546:   border: 1px solid black;
 5547:   margin: 2px;
 5548: }
 5549: 
 5550: table#LC_menubuttons {
 5551:   width: 100%;
 5552:   background: $pgbg;
 5553:   border: 2px;
 5554:   border-collapse: separate;
 5555:   padding: 0;
 5556: }
 5557: 
 5558: table#LC_title_bar a {
 5559:   color: $fontmenu;
 5560: }
 5561: 
 5562: table#LC_title_bar {
 5563:   clear: both;
 5564:   display: none;
 5565: }
 5566: 
 5567: table#LC_title_bar,
 5568: table.LC_breadcrumbs, /* obsolete? */
 5569: table#LC_title_bar.LC_with_remote {
 5570:   width: 100%;
 5571:   border-color: $pgbg;
 5572:   border-style: solid;
 5573:   border-width: $border;
 5574:   background: $pgbg;
 5575:   color: $fontmenu;
 5576:   border-collapse: collapse;
 5577:   padding: 0;
 5578:   margin: 0;
 5579: }
 5580: 
 5581: ul.LC_breadcrumb_tools_outerlist {
 5582:     margin: 0;
 5583:     padding: 0;
 5584:     position: relative;
 5585:     list-style: none;
 5586: }
 5587: ul.LC_breadcrumb_tools_outerlist li {
 5588:     display: inline;
 5589: }
 5590: 
 5591: .LC_breadcrumb_tools_navigation {
 5592:     padding: 0;
 5593:     margin: 0;
 5594:     float: left;
 5595: }
 5596: .LC_breadcrumb_tools_tools {
 5597:     padding: 0;
 5598:     margin: 0;
 5599:     float: right;
 5600: }
 5601: 
 5602: table#LC_title_bar td {
 5603:   background: $tabbg;
 5604: }
 5605: 
 5606: table#LC_menubuttons img {
 5607:   border: none;
 5608: }
 5609: 
 5610: .LC_breadcrumbs_component {
 5611:   float: right;
 5612:   margin: 0 1em;
 5613: }
 5614: .LC_breadcrumbs_component img {
 5615:   vertical-align: middle;
 5616: }
 5617: 
 5618: td.LC_table_cell_checkbox {
 5619:   text-align: center;
 5620: }
 5621: 
 5622: .LC_fontsize_small {
 5623:   font-size: 70%;
 5624: }
 5625: 
 5626: #LC_breadcrumbs {
 5627:   clear:both;
 5628:   background: $sidebg;
 5629:   border-bottom: 1px solid $lg_border_color;
 5630:   line-height: 2.5em;
 5631:   overflow: hidden;
 5632:   margin: 0;
 5633:   padding: 0;
 5634:   text-align: left;
 5635: }
 5636: 
 5637: .LC_head_subbox, .LC_actionbox {
 5638:   clear:both;
 5639:   background: #F8F8F8; /* $sidebg; */
 5640:   border: 1px solid $sidebg;
 5641:   margin: 0 0 10px 0;
 5642:   padding: 3px;
 5643:   text-align: left;
 5644: }
 5645: 
 5646: .LC_fontsize_medium {
 5647:   font-size: 85%;
 5648: }
 5649: 
 5650: .LC_fontsize_large {
 5651:   font-size: 120%;
 5652: }
 5653: 
 5654: .LC_menubuttons_inline_text {
 5655:   color: $font;
 5656:   font-size: 90%;
 5657:   padding-left:3px;
 5658: }
 5659: 
 5660: .LC_menubuttons_inline_text img{
 5661:   vertical-align: middle;
 5662: }
 5663: 
 5664: li.LC_menubuttons_inline_text img {
 5665:   cursor:pointer;
 5666:   text-decoration: none;
 5667: }
 5668: 
 5669: .LC_menubuttons_link {
 5670:   text-decoration: none;
 5671: }
 5672: 
 5673: .LC_menubuttons_category {
 5674:   color: $font;
 5675:   background: $pgbg;
 5676:   font-size: larger;
 5677:   font-weight: bold;
 5678: }
 5679: 
 5680: td.LC_menubuttons_text {
 5681:   color: $font;
 5682: }
 5683: 
 5684: .LC_current_location {
 5685:   background: $tabbg;
 5686: }
 5687: 
 5688: table.LC_data_table {
 5689:   border: 1px solid #000000;
 5690:   border-collapse: separate;
 5691:   border-spacing: 1px;
 5692:   background: $pgbg;
 5693: }
 5694: 
 5695: .LC_data_table_dense {
 5696:   font-size: small;
 5697: }
 5698: 
 5699: table.LC_nested_outer {
 5700:   border: 1px solid #000000;
 5701:   border-collapse: collapse;
 5702:   border-spacing: 0;
 5703:   width: 100%;
 5704: }
 5705: 
 5706: table.LC_innerpickbox,
 5707: table.LC_nested {
 5708:   border: none;
 5709:   border-collapse: collapse;
 5710:   border-spacing: 0;
 5711:   width: 100%;
 5712: }
 5713: 
 5714: table.LC_data_table tr th,
 5715: table.LC_calendar tr th,
 5716: table.LC_prior_tries tr th,
 5717: table.LC_innerpickbox tr th {
 5718:   font-weight: bold;
 5719:   background-color: $data_table_head;
 5720:   color:$fontmenu;
 5721:   font-size:90%;
 5722: }
 5723: 
 5724: table.LC_innerpickbox tr th,
 5725: table.LC_innerpickbox tr td {
 5726:   vertical-align: top;
 5727: }
 5728: 
 5729: table.LC_data_table tr.LC_info_row > td {
 5730:   background-color: #CCCCCC;
 5731:   font-weight: bold;
 5732:   text-align: left;
 5733: }
 5734: 
 5735: table.LC_data_table tr.LC_odd_row > td {
 5736:   background-color: $data_table_light;
 5737:   padding: 2px;
 5738:   vertical-align: top;
 5739: }
 5740: 
 5741: table.LC_pick_box tr > td.LC_odd_row {
 5742:   background-color: $data_table_light;
 5743:   vertical-align: top;
 5744: }
 5745: 
 5746: table.LC_data_table tr.LC_even_row > td {
 5747:   background-color: $data_table_dark;
 5748:   padding: 2px;
 5749:   vertical-align: top;
 5750: }
 5751: 
 5752: table.LC_pick_box tr > td.LC_even_row {
 5753:   background-color: $data_table_dark;
 5754:   vertical-align: top;
 5755: }
 5756: 
 5757: table.LC_data_table tr.LC_data_table_highlight td {
 5758:   background-color: $data_table_darker;
 5759: }
 5760: 
 5761: table.LC_data_table tr td.LC_leftcol_header {
 5762:   background-color: $data_table_head;
 5763:   font-weight: bold;
 5764: }
 5765: 
 5766: table.LC_data_table tr.LC_empty_row td,
 5767: table.LC_nested tr.LC_empty_row td {
 5768:   font-weight: bold;
 5769:   font-style: italic;
 5770:   text-align: center;
 5771:   padding: 8px;
 5772: }
 5773: 
 5774: table.LC_data_table tr.LC_empty_row td,
 5775: table.LC_data_table tr.LC_footer_row td {
 5776:   background-color: $sidebg;
 5777: }
 5778: 
 5779: table.LC_nested tr.LC_empty_row td {
 5780:   background-color: #FFFFFF;
 5781: }
 5782: 
 5783: table.LC_caption {
 5784: }
 5785: 
 5786: table.LC_nested tr.LC_empty_row td {
 5787:   padding: 4ex
 5788: }
 5789: 
 5790: table.LC_nested_outer tr th {
 5791:   font-weight: bold;
 5792:   color:$fontmenu;
 5793:   background-color: $data_table_head;
 5794:   font-size: small;
 5795:   border-bottom: 1px solid #000000;
 5796: }
 5797: 
 5798: table.LC_nested_outer tr td.LC_subheader {
 5799:   background-color: $data_table_head;
 5800:   font-weight: bold;
 5801:   font-size: small;
 5802:   border-bottom: 1px solid #000000;
 5803:   text-align: right;
 5804: }
 5805: 
 5806: table.LC_nested tr.LC_info_row td {
 5807:   background-color: #CCCCCC;
 5808:   font-weight: bold;
 5809:   font-size: small;
 5810:   text-align: center;
 5811: }
 5812: 
 5813: table.LC_nested tr.LC_info_row td.LC_left_item,
 5814: table.LC_nested_outer tr th.LC_left_item {
 5815:   text-align: left;
 5816: }
 5817: 
 5818: table.LC_nested td {
 5819:   background-color: #FFFFFF;
 5820:   font-size: small;
 5821: }
 5822: 
 5823: table.LC_nested_outer tr th.LC_right_item,
 5824: table.LC_nested tr.LC_info_row td.LC_right_item,
 5825: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5826: table.LC_nested tr td.LC_right_item {
 5827:   text-align: right;
 5828: }
 5829: 
 5830: table.LC_nested tr.LC_odd_row td {
 5831:   background-color: #EEEEEE;
 5832: }
 5833: 
 5834: table.LC_createuser {
 5835: }
 5836: 
 5837: table.LC_createuser tr.LC_section_row td {
 5838:   font-size: small;
 5839: }
 5840: 
 5841: table.LC_createuser tr.LC_info_row td  {
 5842:   background-color: #CCCCCC;
 5843:   font-weight: bold;
 5844:   text-align: center;
 5845: }
 5846: 
 5847: table.LC_calendar {
 5848:   border: 1px solid #000000;
 5849:   border-collapse: collapse;
 5850:   width: 98%;
 5851: }
 5852: 
 5853: table.LC_calendar_pickdate {
 5854:   font-size: xx-small;
 5855: }
 5856: 
 5857: table.LC_calendar tr td {
 5858:   border: 1px solid #000000;
 5859:   vertical-align: top;
 5860:   width: 14%;
 5861: }
 5862: 
 5863: table.LC_calendar tr td.LC_calendar_day_empty {
 5864:   background-color: $data_table_dark;
 5865: }
 5866: 
 5867: table.LC_calendar tr td.LC_calendar_day_current {
 5868:   background-color: $data_table_highlight;
 5869: }
 5870: 
 5871: table.LC_data_table tr td.LC_mail_new {
 5872:   background-color: $mail_new;
 5873: }
 5874: 
 5875: table.LC_data_table tr.LC_mail_new:hover {
 5876:   background-color: $mail_new_hover;
 5877: }
 5878: 
 5879: table.LC_data_table tr td.LC_mail_read {
 5880:   background-color: $mail_read;
 5881: }
 5882: 
 5883: /*
 5884: table.LC_data_table tr.LC_mail_read:hover {
 5885:   background-color: $mail_read_hover;
 5886: }
 5887: */
 5888: 
 5889: table.LC_data_table tr td.LC_mail_replied {
 5890:   background-color: $mail_replied;
 5891: }
 5892: 
 5893: /*
 5894: table.LC_data_table tr.LC_mail_replied:hover {
 5895:   background-color: $mail_replied_hover;
 5896: }
 5897: */
 5898: 
 5899: table.LC_data_table tr td.LC_mail_other {
 5900:   background-color: $mail_other;
 5901: }
 5902: 
 5903: /*
 5904: table.LC_data_table tr.LC_mail_other:hover {
 5905:   background-color: $mail_other_hover;
 5906: }
 5907: */
 5908: 
 5909: table.LC_data_table tr > td.LC_browser_file,
 5910: table.LC_data_table tr > td.LC_browser_file_published {
 5911:   background: #AAEE77;
 5912: }
 5913: 
 5914: table.LC_data_table tr > td.LC_browser_file_locked,
 5915: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5916:   background: #FFAA99;
 5917: }
 5918: 
 5919: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5920:   background: #888888;
 5921: }
 5922: 
 5923: table.LC_data_table tr > td.LC_browser_file_modified,
 5924: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5925:   background: #F8F866;
 5926: }
 5927: 
 5928: table.LC_data_table tr.LC_browser_folder > td {
 5929:   background: #E0E8FF;
 5930: }
 5931: 
 5932: table.LC_data_table tr > td.LC_roles_is {
 5933:   /* background: #77FF77; */
 5934: }
 5935: 
 5936: table.LC_data_table tr > td.LC_roles_future {
 5937:   border-right: 8px solid #FFFF77;
 5938: }
 5939: 
 5940: table.LC_data_table tr > td.LC_roles_will {
 5941:   border-right: 8px solid #FFAA77;
 5942: }
 5943: 
 5944: table.LC_data_table tr > td.LC_roles_expired {
 5945:   border-right: 8px solid #FF7777;
 5946: }
 5947: 
 5948: table.LC_data_table tr > td.LC_roles_will_not {
 5949:   border-right: 8px solid #AAFF77;
 5950: }
 5951: 
 5952: table.LC_data_table tr > td.LC_roles_selected {
 5953:   border-right: 8px solid #11CC55;
 5954: }
 5955: 
 5956: span.LC_current_location {
 5957:   font-size:larger;
 5958:   background: $pgbg;
 5959: }
 5960: 
 5961: span.LC_current_nav_location {
 5962:   font-weight:bold;
 5963:   background: $sidebg;
 5964: }
 5965: 
 5966: span.LC_parm_menu_item {
 5967:   font-size: larger;
 5968: }
 5969: 
 5970: span.LC_parm_scope_all {
 5971:   color: red;
 5972: }
 5973: 
 5974: span.LC_parm_scope_folder {
 5975:   color: green;
 5976: }
 5977: 
 5978: span.LC_parm_scope_resource {
 5979:   color: orange;
 5980: }
 5981: 
 5982: span.LC_parm_part {
 5983:   color: blue;
 5984: }
 5985: 
 5986: span.LC_parm_folder,
 5987: span.LC_parm_symb {
 5988:   font-size: x-small;
 5989:   font-family: $mono;
 5990:   color: #AAAAAA;
 5991: }
 5992: 
 5993: ul.LC_parm_parmlist li {
 5994:   display: inline-block;
 5995:   padding: 0.3em 0.8em;
 5996:   vertical-align: top;
 5997:   width: 150px;
 5998:   border-top:1px solid $lg_border_color;
 5999: }
 6000: 
 6001: td.LC_parm_overview_level_menu,
 6002: td.LC_parm_overview_map_menu,
 6003: td.LC_parm_overview_parm_selectors,
 6004: td.LC_parm_overview_restrictions  {
 6005:   border: 1px solid black;
 6006:   border-collapse: collapse;
 6007: }
 6008: 
 6009: table.LC_parm_overview_restrictions td {
 6010:   border-width: 1px 4px 1px 4px;
 6011:   border-style: solid;
 6012:   border-color: $pgbg;
 6013:   text-align: center;
 6014: }
 6015: 
 6016: table.LC_parm_overview_restrictions th {
 6017:   background: $tabbg;
 6018:   border-width: 1px 4px 1px 4px;
 6019:   border-style: solid;
 6020:   border-color: $pgbg;
 6021: }
 6022: 
 6023: table#LC_helpmenu {
 6024:   border: none;
 6025:   height: 55px;
 6026:   border-spacing: 0;
 6027: }
 6028: 
 6029: table#LC_helpmenu fieldset legend {
 6030:   font-size: larger;
 6031: }
 6032: 
 6033: table#LC_helpmenu_links {
 6034:   width: 100%;
 6035:   border: 1px solid black;
 6036:   background: $pgbg;
 6037:   padding: 0;
 6038:   border-spacing: 1px;
 6039: }
 6040: 
 6041: table#LC_helpmenu_links tr td {
 6042:   padding: 1px;
 6043:   background: $tabbg;
 6044:   text-align: center;
 6045:   font-weight: bold;
 6046: }
 6047: 
 6048: table#LC_helpmenu_links a:link,
 6049: table#LC_helpmenu_links a:visited,
 6050: table#LC_helpmenu_links a:active {
 6051:   text-decoration: none;
 6052:   color: $font;
 6053: }
 6054: 
 6055: table#LC_helpmenu_links a:hover {
 6056:   text-decoration: underline;
 6057:   color: $vlink;
 6058: }
 6059: 
 6060: .LC_chrt_popup_exists {
 6061:   border: 1px solid #339933;
 6062:   margin: -1px;
 6063: }
 6064: 
 6065: .LC_chrt_popup_up {
 6066:   border: 1px solid yellow;
 6067:   margin: -1px;
 6068: }
 6069: 
 6070: .LC_chrt_popup {
 6071:   border: 1px solid #8888FF;
 6072:   background: #CCCCFF;
 6073: }
 6074: 
 6075: table.LC_pick_box {
 6076:   border-collapse: separate;
 6077:   background: white;
 6078:   border: 1px solid black;
 6079:   border-spacing: 1px;
 6080: }
 6081: 
 6082: table.LC_pick_box td.LC_pick_box_title {
 6083:   background: $sidebg;
 6084:   font-weight: bold;
 6085:   text-align: left;
 6086:   vertical-align: top;
 6087:   width: 184px;
 6088:   padding: 8px;
 6089: }
 6090: 
 6091: table.LC_pick_box td.LC_pick_box_value {
 6092:   text-align: left;
 6093:   padding: 8px;
 6094: }
 6095: 
 6096: table.LC_pick_box td.LC_pick_box_select {
 6097:   text-align: left;
 6098:   padding: 8px;
 6099: }
 6100: 
 6101: table.LC_pick_box td.LC_pick_box_separator {
 6102:   padding: 0;
 6103:   height: 1px;
 6104:   background: black;
 6105: }
 6106: 
 6107: table.LC_pick_box td.LC_pick_box_submit {
 6108:   text-align: right;
 6109: }
 6110: 
 6111: table.LC_pick_box td.LC_evenrow_value {
 6112:   text-align: left;
 6113:   padding: 8px;
 6114:   background-color: $data_table_light;
 6115: }
 6116: 
 6117: table.LC_pick_box td.LC_oddrow_value {
 6118:   text-align: left;
 6119:   padding: 8px;
 6120:   background-color: $data_table_light;
 6121: }
 6122: 
 6123: span.LC_helpform_receipt_cat {
 6124:   font-weight: bold;
 6125: }
 6126: 
 6127: table.LC_group_priv_box {
 6128:   background: white;
 6129:   border: 1px solid black;
 6130:   border-spacing: 1px;
 6131: }
 6132: 
 6133: table.LC_group_priv_box td.LC_pick_box_title {
 6134:   background: $tabbg;
 6135:   font-weight: bold;
 6136:   text-align: right;
 6137:   width: 184px;
 6138: }
 6139: 
 6140: table.LC_group_priv_box td.LC_groups_fixed {
 6141:   background: $data_table_light;
 6142:   text-align: center;
 6143: }
 6144: 
 6145: table.LC_group_priv_box td.LC_groups_optional {
 6146:   background: $data_table_dark;
 6147:   text-align: center;
 6148: }
 6149: 
 6150: table.LC_group_priv_box td.LC_groups_functionality {
 6151:   background: $data_table_darker;
 6152:   text-align: center;
 6153:   font-weight: bold;
 6154: }
 6155: 
 6156: table.LC_group_priv td {
 6157:   text-align: left;
 6158:   padding: 0;
 6159: }
 6160: 
 6161: .LC_navbuttons {
 6162:   margin: 2ex 0ex 2ex 0ex;
 6163: }
 6164: 
 6165: .LC_topic_bar {
 6166:   font-weight: bold;
 6167:   background: $tabbg;
 6168:   margin: 1em 0em 1em 2em;
 6169:   padding: 3px;
 6170:   font-size: 1.2em;
 6171: }
 6172: 
 6173: .LC_topic_bar span {
 6174:   left: 0.5em;
 6175:   position: absolute;
 6176:   vertical-align: middle;
 6177:   font-size: 1.2em;
 6178: }
 6179: 
 6180: table.LC_course_group_status {
 6181:   margin: 20px;
 6182: }
 6183: 
 6184: table.LC_status_selector td {
 6185:   vertical-align: top;
 6186:   text-align: center;
 6187:   padding: 4px;
 6188: }
 6189: 
 6190: div.LC_feedback_link {
 6191:   clear: both;
 6192:   background: $sidebg;
 6193:   width: 100%;
 6194:   padding-bottom: 10px;
 6195:   border: 1px $tabbg solid;
 6196:   height: 22px;
 6197:   line-height: 22px;
 6198:   padding-top: 5px;
 6199: }
 6200: 
 6201: div.LC_feedback_link img {
 6202:   height: 22px;
 6203:   vertical-align:middle;
 6204: }
 6205: 
 6206: div.LC_feedback_link a {
 6207:   text-decoration: none;
 6208: }
 6209: 
 6210: div.LC_comblock {
 6211:   display:inline;
 6212:   color:$font;
 6213:   font-size:90%;
 6214: }
 6215: 
 6216: div.LC_feedback_link div.LC_comblock {
 6217:   padding-left:5px;
 6218: }
 6219: 
 6220: div.LC_feedback_link div.LC_comblock a {
 6221:   color:$font;
 6222: }
 6223: 
 6224: span.LC_feedback_link {
 6225:   /* background: $feedback_link_bg; */
 6226:   font-size: larger;
 6227: }
 6228: 
 6229: span.LC_message_link {
 6230:   /* background: $feedback_link_bg; */
 6231:   font-size: larger;
 6232:   position: absolute;
 6233:   right: 1em;
 6234: }
 6235: 
 6236: table.LC_prior_tries {
 6237:   border: 1px solid #000000;
 6238:   border-collapse: separate;
 6239:   border-spacing: 1px;
 6240: }
 6241: 
 6242: table.LC_prior_tries td {
 6243:   padding: 2px;
 6244: }
 6245: 
 6246: .LC_answer_correct {
 6247:   background: lightgreen;
 6248:   color: darkgreen;
 6249:   padding: 6px;
 6250: }
 6251: 
 6252: .LC_answer_charged_try {
 6253:   background: #FFAAAA;
 6254:   color: darkred;
 6255:   padding: 6px;
 6256: }
 6257: 
 6258: .LC_answer_not_charged_try,
 6259: .LC_answer_no_grade,
 6260: .LC_answer_late {
 6261:   background: lightyellow;
 6262:   color: black;
 6263:   padding: 6px;
 6264: }
 6265: 
 6266: .LC_answer_previous {
 6267:   background: lightblue;
 6268:   color: darkblue;
 6269:   padding: 6px;
 6270: }
 6271: 
 6272: .LC_answer_no_message {
 6273:   background: #FFFFFF;
 6274:   color: black;
 6275:   padding: 6px;
 6276: }
 6277: 
 6278: .LC_answer_unknown {
 6279:   background: orange;
 6280:   color: black;
 6281:   padding: 6px;
 6282: }
 6283: 
 6284: span.LC_prior_numerical,
 6285: span.LC_prior_string,
 6286: span.LC_prior_custom,
 6287: span.LC_prior_reaction,
 6288: span.LC_prior_math {
 6289:   font-family: $mono;
 6290:   white-space: pre;
 6291: }
 6292: 
 6293: span.LC_prior_string {
 6294:   font-family: $mono;
 6295:   white-space: pre;
 6296: }
 6297: 
 6298: table.LC_prior_option {
 6299:   width: 100%;
 6300:   border-collapse: collapse;
 6301: }
 6302: 
 6303: table.LC_prior_rank,
 6304: table.LC_prior_match {
 6305:   border-collapse: collapse;
 6306: }
 6307: 
 6308: table.LC_prior_option tr td,
 6309: table.LC_prior_rank tr td,
 6310: table.LC_prior_match tr td {
 6311:   border: 1px solid #000000;
 6312: }
 6313: 
 6314: .LC_nobreak {
 6315:   white-space: nowrap;
 6316: }
 6317: 
 6318: span.LC_cusr_emph {
 6319:   font-style: italic;
 6320: }
 6321: 
 6322: span.LC_cusr_subheading {
 6323:   font-weight: normal;
 6324:   font-size: 85%;
 6325: }
 6326: 
 6327: div.LC_docs_entry_move {
 6328:   border: 1px solid #BBBBBB;
 6329:   background: #DDDDDD;
 6330:   width: 22px;
 6331:   padding: 1px;
 6332:   margin: 0;
 6333: }
 6334: 
 6335: table.LC_data_table tr > td.LC_docs_entry_commands,
 6336: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6337:   font-size: x-small;
 6338: }
 6339: 
 6340: .LC_docs_entry_parameter {
 6341:   white-space: nowrap;
 6342: }
 6343: 
 6344: .LC_docs_copy {
 6345:   color: #000099;
 6346: }
 6347: 
 6348: .LC_docs_cut {
 6349:   color: #550044;
 6350: }
 6351: 
 6352: .LC_docs_rename {
 6353:   color: #009900;
 6354: }
 6355: 
 6356: .LC_docs_remove {
 6357:   color: #990000;
 6358: }
 6359: 
 6360: .LC_docs_reinit_warn,
 6361: .LC_docs_ext_edit {
 6362:   font-size: x-small;
 6363: }
 6364: 
 6365: table.LC_docs_adddocs td,
 6366: table.LC_docs_adddocs th {
 6367:   border: 1px solid #BBBBBB;
 6368:   padding: 4px;
 6369:   background: #DDDDDD;
 6370: }
 6371: 
 6372: table.LC_sty_begin {
 6373:   background: #BBFFBB;
 6374: }
 6375: 
 6376: table.LC_sty_end {
 6377:   background: #FFBBBB;
 6378: }
 6379: 
 6380: table.LC_double_column {
 6381:   border-width: 0;
 6382:   border-collapse: collapse;
 6383:   width: 100%;
 6384:   padding: 2px;
 6385: }
 6386: 
 6387: table.LC_double_column tr td.LC_left_col {
 6388:   top: 2px;
 6389:   left: 2px;
 6390:   width: 47%;
 6391:   vertical-align: top;
 6392: }
 6393: 
 6394: table.LC_double_column tr td.LC_right_col {
 6395:   top: 2px;
 6396:   right: 2px;
 6397:   width: 47%;
 6398:   vertical-align: top;
 6399: }
 6400: 
 6401: div.LC_left_float {
 6402:   float: left;
 6403:   padding-right: 5%;
 6404:   padding-bottom: 4px;
 6405: }
 6406: 
 6407: div.LC_clear_float_header {
 6408:   padding-bottom: 2px;
 6409: }
 6410: 
 6411: div.LC_clear_float_footer {
 6412:   padding-top: 10px;
 6413:   clear: both;
 6414: }
 6415: 
 6416: div.LC_grade_show_user {
 6417: /*  border-left: 5px solid $sidebg; */
 6418:   border-top: 5px solid #000000;
 6419:   margin: 50px 0 0 0;
 6420:   padding: 15px 0 5px 10px;
 6421: }
 6422: 
 6423: div.LC_grade_show_user_odd_row {
 6424: /*  border-left: 5px solid #000000; */
 6425: }
 6426: 
 6427: div.LC_grade_show_user div.LC_Box {
 6428:   margin-right: 50px;
 6429: }
 6430: 
 6431: div.LC_grade_submissions,
 6432: div.LC_grade_message_center,
 6433: div.LC_grade_info_links {
 6434:   margin: 5px;
 6435:   width: 99%;
 6436:   background: #FFFFFF;
 6437: }
 6438: 
 6439: div.LC_grade_submissions_header,
 6440: div.LC_grade_message_center_header {
 6441:   font-weight: bold;
 6442:   font-size: large;
 6443: }
 6444: 
 6445: div.LC_grade_submissions_body,
 6446: div.LC_grade_message_center_body {
 6447:   border: 1px solid black;
 6448:   width: 99%;
 6449:   background: #FFFFFF;
 6450: }
 6451: 
 6452: table.LC_scantron_action {
 6453:   width: 100%;
 6454: }
 6455: 
 6456: table.LC_scantron_action tr th {
 6457:   font-weight:bold;
 6458:   font-style:normal;
 6459: }
 6460: 
 6461: .LC_edit_problem_header,
 6462: div.LC_edit_problem_footer {
 6463:   font-weight: normal;
 6464:   font-size:  medium;
 6465:   margin: 2px;
 6466:   background-color: $sidebg;
 6467: }
 6468: 
 6469: div.LC_edit_problem_header,
 6470: div.LC_edit_problem_header div,
 6471: div.LC_edit_problem_footer,
 6472: div.LC_edit_problem_footer div,
 6473: div.LC_edit_problem_editxml_header,
 6474: div.LC_edit_problem_editxml_header div {
 6475:   margin-top: 5px;
 6476: }
 6477: 
 6478: div.LC_edit_problem_header_title {
 6479:   font-weight: bold;
 6480:   font-size: larger;
 6481:   background: $tabbg;
 6482:   padding: 3px;
 6483:   margin: 0 0 5px 0;
 6484: }
 6485: 
 6486: table.LC_edit_problem_header_title {
 6487:   width: 100%;
 6488:   background: $tabbg;
 6489: }
 6490: 
 6491: div.LC_edit_problem_discards {
 6492:   float: left;
 6493:   padding-bottom: 5px;
 6494: }
 6495: 
 6496: div.LC_edit_problem_saves {
 6497:   float: right;
 6498:   padding-bottom: 5px;
 6499: }
 6500: 
 6501: .LC_edit_opt {
 6502:   padding-left: 1em;
 6503:   white-space: nowrap;
 6504: }
 6505: 
 6506: .LC_edit_problem_latexhelper{
 6507:     text-align: right;
 6508: }
 6509: 
 6510: #LC_edit_problem_colorful div{
 6511:     margin-left: 40px;
 6512: }
 6513: 
 6514: img.stift {
 6515:   border-width: 0;
 6516:   vertical-align: middle;
 6517: }
 6518: 
 6519: table td.LC_mainmenu_col_fieldset {
 6520:   vertical-align: top;
 6521: }
 6522: 
 6523: div.LC_createcourse {
 6524:   margin: 10px 10px 10px 10px;
 6525: }
 6526: 
 6527: .LC_dccid {
 6528:   float: right;
 6529:   margin: 0.2em 0 0 0;
 6530:   padding: 0;
 6531:   font-size: 90%;
 6532:   display:none;
 6533: }
 6534: 
 6535: ol.LC_primary_menu a:hover,
 6536: ol#LC_MenuBreadcrumbs a:hover,
 6537: ol#LC_PathBreadcrumbs a:hover,
 6538: ul#LC_secondary_menu a:hover,
 6539: .LC_FormSectionClearButton input:hover
 6540: ul.LC_TabContent   li:hover a {
 6541:   color:$button_hover;
 6542:   text-decoration:none;
 6543: }
 6544: 
 6545: h1 {
 6546:   padding: 0;
 6547:   line-height:130%;
 6548: }
 6549: 
 6550: h2,
 6551: h3,
 6552: h4,
 6553: h5,
 6554: h6 {
 6555:   margin: 5px 0 5px 0;
 6556:   padding: 0;
 6557:   line-height:130%;
 6558: }
 6559: 
 6560: .LC_hcell {
 6561:   padding:3px 15px 3px 15px;
 6562:   margin: 0;
 6563:   background-color:$tabbg;
 6564:   color:$fontmenu;
 6565:   border-bottom:solid 1px $lg_border_color;
 6566: }
 6567: 
 6568: .LC_Box > .LC_hcell {
 6569:   margin: 0 -10px 10px -10px;
 6570: }
 6571: 
 6572: .LC_noBorder {
 6573:   border: 0;
 6574: }
 6575: 
 6576: .LC_FormSectionClearButton input {
 6577:   background-color:transparent;
 6578:   border: none;
 6579:   cursor:pointer;
 6580:   text-decoration:underline;
 6581: }
 6582: 
 6583: .LC_help_open_topic {
 6584:   color: #FFFFFF;
 6585:   background-color: #EEEEFF;
 6586:   margin: 1px;
 6587:   padding: 4px;
 6588:   border: 1px solid #000033;
 6589:   white-space: nowrap;
 6590:   /* vertical-align: middle; */
 6591: }
 6592: 
 6593: dl,
 6594: ul,
 6595: div,
 6596: fieldset {
 6597:   margin: 10px 10px 10px 0;
 6598:   /* overflow: hidden; */
 6599: }
 6600: 
 6601: fieldset > legend {
 6602:   font-weight: bold;
 6603:   padding: 0 5px 0 5px;
 6604: }
 6605: 
 6606: #LC_nav_bar {
 6607:   float: left;
 6608:   background-color: $pgbg_or_bgcolor;
 6609:   margin: 0 0 2px 0;
 6610: }
 6611: 
 6612: #LC_realm {
 6613:   margin: 0.2em 0 0 0;
 6614:   padding: 0;
 6615:   font-weight: bold;
 6616:   text-align: center;
 6617:   background-color: $pgbg_or_bgcolor;
 6618: }
 6619: 
 6620: #LC_nav_bar em {
 6621:   font-weight: bold;
 6622:   font-style: normal;
 6623: }
 6624: 
 6625: ol.LC_primary_menu {
 6626:   margin: 0;
 6627:   padding: 0;
 6628:   background-color: $pgbg_or_bgcolor;
 6629: }
 6630: 
 6631: ol#LC_PathBreadcrumbs {
 6632:   margin: 0;
 6633: }
 6634: 
 6635: ol.LC_primary_menu li {
 6636:   color: RGB(80, 80, 80);
 6637:   vertical-align: middle;
 6638:   text-align: left;
 6639:   list-style: none;
 6640:   float: left;
 6641: }
 6642: 
 6643: ol.LC_primary_menu li a {
 6644:   display: block;
 6645:   margin: 0;
 6646:   padding: 0 5px 0 10px;
 6647:   text-decoration: none;
 6648: }
 6649: 
 6650: ol.LC_primary_menu li ul {
 6651:   display: none;
 6652:   width: 10em;
 6653:   background-color: $data_table_light;
 6654: }
 6655: 
 6656: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6657:   display: block;
 6658:   position: absolute;
 6659:   margin: 0;
 6660:   padding: 0;
 6661:   z-index: 2;
 6662: }
 6663: 
 6664: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6665:   font-size: 90%;
 6666:   vertical-align: top;
 6667:   float: none;
 6668:   border-left: 1px solid black;
 6669:   border-right: 1px solid black;
 6670: }
 6671: 
 6672: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6673:   background-color:$data_table_light;
 6674: }
 6675: 
 6676: ol.LC_primary_menu li li a:hover {
 6677:    color:$button_hover;
 6678:    background-color:$data_table_dark;
 6679: }
 6680: 
 6681: ol.LC_primary_menu li img {
 6682:   vertical-align: bottom;
 6683:   height: 1.1em;
 6684:   margin: 0.2em 0 0 0;
 6685: }
 6686: 
 6687: ol.LC_primary_menu a {
 6688:   color: RGB(80, 80, 80);
 6689:   text-decoration: none;
 6690: }
 6691: 
 6692: ol.LC_primary_menu a.LC_new_message {
 6693:   font-weight:bold;
 6694:   color: darkred;
 6695: }
 6696: 
 6697: ol.LC_docs_parameters {
 6698:   margin-left: 0;
 6699:   padding: 0;
 6700:   list-style: none;
 6701: }
 6702: 
 6703: ol.LC_docs_parameters li {
 6704:   margin: 0;
 6705:   padding-right: 20px;
 6706:   display: inline;
 6707: }
 6708: 
 6709: ol.LC_docs_parameters li:before {
 6710:   content: "\\002022 \\0020";
 6711: }
 6712: 
 6713: li.LC_docs_parameters_title {
 6714:   font-weight: bold;
 6715: }
 6716: 
 6717: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6718:   content: "";
 6719: }
 6720: 
 6721: ul#LC_secondary_menu {
 6722:   clear: right;
 6723:   color: $fontmenu;
 6724:   background: $tabbg;
 6725:   list-style: none;
 6726:   padding: 0;
 6727:   margin: 0;
 6728:   width: 100%;
 6729:   text-align: left;
 6730:   float: left;
 6731: }
 6732: 
 6733: ul#LC_secondary_menu li {
 6734:   font-weight: bold;
 6735:   line-height: 1.8em;
 6736:   border-right: 1px solid black;
 6737:   vertical-align: middle;
 6738:   float: left;
 6739: }
 6740: 
 6741: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6742:   background-color: $data_table_light;
 6743: }
 6744: 
 6745: ul#LC_secondary_menu li a {
 6746:   padding: 0 0.8em;
 6747: }
 6748: 
 6749: ul#LC_secondary_menu li ul {
 6750:   display: none;
 6751: }
 6752: 
 6753: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6754:   display: block;
 6755:   position: absolute;
 6756:   margin: 0;
 6757:   padding: 0;
 6758:   list-style:none;
 6759:   float: none;
 6760:   background-color: $data_table_light;
 6761:   z-index: 2;
 6762:   margin-left: -1px;
 6763: }
 6764: 
 6765: ul#LC_secondary_menu li ul li {
 6766:   font-size: 90%;
 6767:   vertical-align: top;
 6768:   border-left: 1px solid black;
 6769:   border-right: 1px solid black;
 6770:   background-color: $data_table_light;
 6771:   list-style:none;
 6772:   float: none;
 6773: }
 6774: 
 6775: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6776:   background-color: $data_table_dark;
 6777: }
 6778: 
 6779: ul.LC_TabContent {
 6780:   display:block;
 6781:   background: $sidebg;
 6782:   border-bottom: solid 1px $lg_border_color;
 6783:   list-style:none;
 6784:   margin: -1px -10px 0 -10px;
 6785:   padding: 0;
 6786: }
 6787: 
 6788: ul.LC_TabContent li,
 6789: ul.LC_TabContentBigger li {
 6790:   float:left;
 6791: }
 6792: 
 6793: ul#LC_secondary_menu li a {
 6794:   color: $fontmenu;
 6795:   text-decoration: none;
 6796: }
 6797: 
 6798: ul.LC_TabContent {
 6799:   min-height:20px;
 6800: }
 6801: 
 6802: ul.LC_TabContent li {
 6803:   vertical-align:middle;
 6804:   padding: 0 16px 0 10px;
 6805:   background-color:$tabbg;
 6806:   border-bottom:solid 1px $lg_border_color;
 6807:   border-left: solid 1px $font;
 6808: }
 6809: 
 6810: ul.LC_TabContent .right {
 6811:   float:right;
 6812: }
 6813: 
 6814: ul.LC_TabContent li a,
 6815: ul.LC_TabContent li {
 6816:   color:rgb(47,47,47);
 6817:   text-decoration:none;
 6818:   font-size:95%;
 6819:   font-weight:bold;
 6820:   min-height:20px;
 6821: }
 6822: 
 6823: ul.LC_TabContent li a:hover,
 6824: ul.LC_TabContent li a:focus {
 6825:   color: $button_hover;
 6826:   background:none;
 6827:   outline:none;
 6828: }
 6829: 
 6830: ul.LC_TabContent li:hover {
 6831:   color: $button_hover;
 6832:   cursor:pointer;
 6833: }
 6834: 
 6835: ul.LC_TabContent li.active {
 6836:   color: $font;
 6837:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6838:   border-bottom:solid 1px #FFFFFF;
 6839:   cursor: default;
 6840: }
 6841: 
 6842: ul.LC_TabContent li.active a {
 6843:   color:$font;
 6844:   background:#FFFFFF;
 6845:   outline: none;
 6846: }
 6847: 
 6848: ul.LC_TabContent li.goback {
 6849:   float: left;
 6850:   border-left: none;
 6851: }
 6852: 
 6853: #maincoursedoc {
 6854:   clear:both;
 6855: }
 6856: 
 6857: ul.LC_TabContentBigger {
 6858:   display:block;
 6859:   list-style:none;
 6860:   padding: 0;
 6861: }
 6862: 
 6863: ul.LC_TabContentBigger li {
 6864:   vertical-align:bottom;
 6865:   height: 30px;
 6866:   font-size:110%;
 6867:   font-weight:bold;
 6868:   color: #737373;
 6869: }
 6870: 
 6871: ul.LC_TabContentBigger li.active {
 6872:   position: relative;
 6873:   top: 1px;
 6874: }
 6875: 
 6876: ul.LC_TabContentBigger li a {
 6877:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6878:   height: 30px;
 6879:   line-height: 30px;
 6880:   text-align: center;
 6881:   display: block;
 6882:   text-decoration: none;
 6883:   outline: none;  
 6884: }
 6885: 
 6886: ul.LC_TabContentBigger li.active a {
 6887:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6888:   color:$font;
 6889: }
 6890: 
 6891: ul.LC_TabContentBigger li b {
 6892:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6893:   display: block;
 6894:   float: left;
 6895:   padding: 0 30px;
 6896:   border-bottom: 1px solid $lg_border_color;
 6897: }
 6898: 
 6899: ul.LC_TabContentBigger li:hover b {
 6900:   color:$button_hover;
 6901: }
 6902: 
 6903: ul.LC_TabContentBigger li.active b {
 6904:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6905:   color:$font;
 6906:   border: 0;
 6907: }
 6908: 
 6909: 
 6910: ul.LC_CourseBreadcrumbs {
 6911:   background: $sidebg;
 6912:   height: 2em;
 6913:   padding-left: 10px;
 6914:   margin: 0;
 6915:   list-style-position: inside;
 6916: }
 6917: 
 6918: ol#LC_MenuBreadcrumbs,
 6919: ol#LC_PathBreadcrumbs {
 6920:   padding-left: 10px;
 6921:   margin: 0;
 6922:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6923: }
 6924: 
 6925: ol#LC_MenuBreadcrumbs li,
 6926: ol#LC_PathBreadcrumbs li,
 6927: ul.LC_CourseBreadcrumbs li {
 6928:   display: inline;
 6929:   white-space: normal;  
 6930: }
 6931: 
 6932: ol#LC_MenuBreadcrumbs li a,
 6933: ul.LC_CourseBreadcrumbs li a {
 6934:   text-decoration: none;
 6935:   font-size:90%;
 6936: }
 6937: 
 6938: ol#LC_MenuBreadcrumbs h1 {
 6939:   display: inline;
 6940:   font-size: 90%;
 6941:   line-height: 2.5em;
 6942:   margin: 0;
 6943:   padding: 0;
 6944: }
 6945: 
 6946: ol#LC_PathBreadcrumbs li a {
 6947:   text-decoration:none;
 6948:   font-size:100%;
 6949:   font-weight:bold;
 6950: }
 6951: 
 6952: .LC_Box {
 6953:   border: solid 1px $lg_border_color;
 6954:   padding: 0 10px 10px 10px;
 6955: }
 6956: 
 6957: .LC_DocsBox {
 6958:   border: solid 1px $lg_border_color;
 6959:   padding: 0 0 10px 10px;
 6960: }
 6961: 
 6962: .LC_AboutMe_Image {
 6963:   float:left;
 6964:   margin-right:10px;
 6965: }
 6966: 
 6967: .LC_Clear_AboutMe_Image {
 6968:   clear:left;
 6969: }
 6970: 
 6971: dl.LC_ListStyleClean dt {
 6972:   padding-right: 5px;
 6973:   display: table-header-group;
 6974: }
 6975: 
 6976: dl.LC_ListStyleClean dd {
 6977:   display: table-row;
 6978: }
 6979: 
 6980: .LC_ListStyleClean,
 6981: .LC_ListStyleSimple,
 6982: .LC_ListStyleNormal,
 6983: .LC_ListStyleSpecial {
 6984:   /* display:block; */
 6985:   list-style-position: inside;
 6986:   list-style-type: none;
 6987:   overflow: hidden;
 6988:   padding: 0;
 6989: }
 6990: 
 6991: .LC_ListStyleSimple li,
 6992: .LC_ListStyleSimple dd,
 6993: .LC_ListStyleNormal li,
 6994: .LC_ListStyleNormal dd,
 6995: .LC_ListStyleSpecial li,
 6996: .LC_ListStyleSpecial dd {
 6997:   margin: 0;
 6998:   padding: 5px 5px 5px 10px;
 6999:   clear: both;
 7000: }
 7001: 
 7002: .LC_ListStyleClean li,
 7003: .LC_ListStyleClean dd {
 7004:   padding-top: 0;
 7005:   padding-bottom: 0;
 7006: }
 7007: 
 7008: .LC_ListStyleSimple dd,
 7009: .LC_ListStyleSimple li {
 7010:   border-bottom: solid 1px $lg_border_color;
 7011: }
 7012: 
 7013: .LC_ListStyleSpecial li,
 7014: .LC_ListStyleSpecial dd {
 7015:   list-style-type: none;
 7016:   background-color: RGB(220, 220, 220);
 7017:   margin-bottom: 4px;
 7018: }
 7019: 
 7020: table.LC_SimpleTable {
 7021:   margin:5px;
 7022:   border:solid 1px $lg_border_color;
 7023: }
 7024: 
 7025: table.LC_SimpleTable tr {
 7026:   padding: 0;
 7027:   border:solid 1px $lg_border_color;
 7028: }
 7029: 
 7030: table.LC_SimpleTable thead {
 7031:   background:rgb(220,220,220);
 7032: }
 7033: 
 7034: div.LC_columnSection {
 7035:   display: block;
 7036:   clear: both;
 7037:   overflow: hidden;
 7038:   margin: 0;
 7039: }
 7040: 
 7041: div.LC_columnSection>* {
 7042:   float: left;
 7043:   margin: 10px 20px 10px 0;
 7044:   overflow:hidden;
 7045: }
 7046: 
 7047: table em {
 7048:   font-weight: bold;
 7049:   font-style: normal;
 7050: }
 7051: 
 7052: table.LC_tableBrowseRes,
 7053: table.LC_tableOfContent {
 7054:   border:none;
 7055:   border-spacing: 1px;
 7056:   padding: 3px;
 7057:   background-color: #FFFFFF;
 7058:   font-size: 90%;
 7059: }
 7060: 
 7061: table.LC_tableOfContent {
 7062:   border-collapse: collapse;
 7063: }
 7064: 
 7065: table.LC_tableBrowseRes a,
 7066: table.LC_tableOfContent a {
 7067:   background-color: transparent;
 7068:   text-decoration: none;
 7069: }
 7070: 
 7071: table.LC_tableOfContent img {
 7072:   border: none;
 7073:   height: 1.3em;
 7074:   vertical-align: text-bottom;
 7075:   margin-right: 0.3em;
 7076: }
 7077: 
 7078: a#LC_content_toolbar_firsthomework {
 7079:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7080: }
 7081: 
 7082: a#LC_content_toolbar_everything {
 7083:   background-image:url(/res/adm/pages/show-all.gif);
 7084: }
 7085: 
 7086: a#LC_content_toolbar_uncompleted {
 7087:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7088: }
 7089: 
 7090: #LC_content_toolbar_clearbubbles {
 7091:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7092: }
 7093: 
 7094: a#LC_content_toolbar_changefolder {
 7095:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7096: }
 7097: 
 7098: a#LC_content_toolbar_changefolder_toggled {
 7099:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7100: }
 7101: 
 7102: a#LC_content_toolbar_edittoplevel {
 7103:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7104: }
 7105: 
 7106: ul#LC_toolbar li a:hover {
 7107:   background-position: bottom center;
 7108: }
 7109: 
 7110: ul#LC_toolbar {
 7111:   padding: 0;
 7112:   margin: 2px;
 7113:   list-style:none;
 7114:   position:relative;
 7115:   background-color:white;
 7116:   overflow: auto;
 7117: }
 7118: 
 7119: ul#LC_toolbar li {
 7120:   border:1px solid white;
 7121:   padding: 0;
 7122:   margin: 0;
 7123:   float: left;
 7124:   display:inline;
 7125:   vertical-align:middle;
 7126:   white-space: nowrap;
 7127: }
 7128: 
 7129: 
 7130: a.LC_toolbarItem {
 7131:   display:block;
 7132:   padding: 0;
 7133:   margin: 0;
 7134:   height: 32px;
 7135:   width: 32px;
 7136:   color:white;
 7137:   border: none;
 7138:   background-repeat:no-repeat;
 7139:   background-color:transparent;
 7140: }
 7141: 
 7142: ul.LC_funclist {
 7143:     margin: 0;
 7144:     padding: 0.5em 1em 0.5em 0;
 7145: }
 7146: 
 7147: ul.LC_funclist > li:first-child {
 7148:     font-weight:bold; 
 7149:     margin-left:0.8em;
 7150: }
 7151: 
 7152: ul.LC_funclist + ul.LC_funclist {
 7153:     /* 
 7154:        left border as a seperator if we have more than
 7155:        one list 
 7156:     */
 7157:     border-left: 1px solid $sidebg;
 7158:     /* 
 7159:        this hides the left border behind the border of the 
 7160:        outer box if element is wrapped to the next 'line' 
 7161:     */
 7162:     margin-left: -1px;
 7163: }
 7164: 
 7165: ul.LC_funclist li {
 7166:   display: inline;
 7167:   white-space: nowrap;
 7168:   margin: 0 0 0 25px;
 7169:   line-height: 150%;
 7170: }
 7171: 
 7172: .LC_hidden {
 7173:   display: none;
 7174: }
 7175: 
 7176: .LCmodal-overlay {
 7177: 		position:fixed;
 7178: 		top:0;
 7179: 		right:0;
 7180: 		bottom:0;
 7181: 		left:0;
 7182: 		height:100%;
 7183: 		width:100%;
 7184: 		margin:0;
 7185: 		padding:0;
 7186: 		background:#999;
 7187: 		opacity:.75;
 7188: 		filter: alpha(opacity=75);
 7189: 		-moz-opacity: 0.75;
 7190: 		z-index:101;
 7191: }
 7192: 
 7193: * html .LCmodal-overlay {   
 7194: 		position: absolute;
 7195: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7196: }
 7197: 
 7198: .LCmodal-window {
 7199: 		position:fixed;
 7200: 		top:50%;
 7201: 		left:50%;
 7202: 		margin:0;
 7203: 		padding:0;
 7204: 		z-index:102;
 7205: 	}
 7206: 
 7207: * html .LCmodal-window {
 7208: 		position:absolute;
 7209: }
 7210: 
 7211: .LCclose-window {
 7212: 		position:absolute;
 7213: 		width:32px;
 7214: 		height:32px;
 7215: 		right:8px;
 7216: 		top:8px;
 7217: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7218: 		text-indent:-99999px;
 7219: 		overflow:hidden;
 7220: 		cursor:pointer;
 7221: }
 7222: 
 7223: /*
 7224:   styles used by TTH when "Default set of options to pass to tth/m
 7225:   when converting TeX" in course settings has been set
 7226: 
 7227:   option passed: -t
 7228: 
 7229: */
 7230: 
 7231: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7232: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7233: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7234: td div.norm {line-height:normal;}
 7235: 
 7236: /*
 7237:   option passed -y3
 7238: */
 7239: 
 7240: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7241: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7242: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7243: 
 7244: END
 7245: }
 7246: 
 7247: =pod
 7248: 
 7249: =item * &headtag()
 7250: 
 7251: Returns a uniform footer for LON-CAPA web pages.
 7252: 
 7253: Inputs: $title - optional title for the head
 7254:         $head_extra - optional extra HTML to put inside the <head>
 7255:         $args - optional arguments
 7256:             force_register - if is true call registerurl so the remote is 
 7257:                              informed
 7258:             redirect       -> array ref of
 7259:                                    1- seconds before redirect occurs
 7260:                                    2- url to redirect to
 7261:                                    3- whether the side effect should occur
 7262:                            (side effect of setting 
 7263:                                $env{'internal.head.redirect'} to the url 
 7264:                                redirected too)
 7265:             domain         -> force to color decorate a page for a specific
 7266:                                domain
 7267:             function       -> force usage of a specific rolish color scheme
 7268:             bgcolor        -> override the default page bgcolor
 7269:             no_auto_mt_title
 7270:                            -> prevent &mt()ing the title arg
 7271: 
 7272: =cut
 7273: 
 7274: sub headtag {
 7275:     my ($title,$head_extra,$args) = @_;
 7276:     
 7277:     my $function = $args->{'function'} || &get_users_function();
 7278:     my $domain   = $args->{'domain'}   || &determinedomain();
 7279:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7280:     my $httphost = $args->{'use_absolute'};
 7281:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7282: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7283: 		   #time(),
 7284: 		   $env{'environment.color.timestamp'},
 7285: 		   $function,$domain,$bgcolor);
 7286: 
 7287:     $url = '/adm/css/'.&escape($url).'.css';
 7288: 
 7289:     my $result =
 7290: 	'<head>'.
 7291: 	&font_settings($args);
 7292: 
 7293:     my $inhibitprint = &print_suppression();
 7294: 
 7295:     if (!$args->{'frameset'}) {
 7296: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7297:     }
 7298:     if ($args->{'force_register'}) {
 7299:         $result .= &Apache::lonmenu::registerurl(1);
 7300:     }
 7301:     if (!$args->{'no_nav_bar'} 
 7302: 	&& !$args->{'only_body'}
 7303: 	&& !$args->{'frameset'}) {
 7304: 	$result .= &help_menu_js($httphost);
 7305:         $result.=&modal_window();
 7306:         $result.=&togglebox_script();
 7307:         $result.=&wishlist_window();
 7308:         $result.=&LCprogressbarUpdate_script();
 7309:     } else {
 7310:         if ($args->{'add_modal'}) {
 7311:            $result.=&modal_window();
 7312:         }
 7313:         if ($args->{'add_wishlist'}) {
 7314:            $result.=&wishlist_window();
 7315:         }
 7316:         if ($args->{'add_togglebox'}) {
 7317:            $result.=&togglebox_script();
 7318:         }
 7319:         if ($args->{'add_progressbar'}) {
 7320:            $result.=&LCprogressbarUpdate_script();
 7321:         }
 7322:     }
 7323:     if (ref($args->{'redirect'})) {
 7324: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7325: 	$url = &Apache::lonenc::check_encrypt($url);
 7326: 	if (!$inhibit_continue) {
 7327: 	    $env{'internal.head.redirect'} = $url;
 7328: 	}
 7329: 	$result.=<<ADDMETA
 7330: <meta http-equiv="pragma" content="no-cache" />
 7331: <meta http-equiv="Refresh" content="$time; url=$url" />
 7332: ADDMETA
 7333:     }
 7334:     if (!defined($title)) {
 7335: 	$title = 'The LearningOnline Network with CAPA';
 7336:     }
 7337:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7338:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7339: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7340:     if (!$args->{'frameset'}) {
 7341:         $result .= ' /';
 7342:     }
 7343:     $result .= '>'
 7344:         .$inhibitprint
 7345: 	.$head_extra;
 7346:     if ($env{'browser.mobile'}) {
 7347:         $result .= '
 7348: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7349: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7350:     }
 7351:     return $result.'</head>';
 7352: }
 7353: 
 7354: =pod
 7355: 
 7356: =item * &font_settings()
 7357: 
 7358: Returns neccessary <meta> to set the proper encoding
 7359: 
 7360: Inputs: optional reference to HASH -- $args passed to &headtag()
 7361: 
 7362: =cut
 7363: 
 7364: sub font_settings {
 7365:     my ($args) = @_;
 7366:     my $headerstring='';
 7367:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7368:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7369: 	$headerstring.=
 7370: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7371:         if (!$args->{'frameset'}) {
 7372:             $headerstring.= ' /';
 7373:         }
 7374:         $headerstring .= '>'."\n";
 7375:     }
 7376:     return $headerstring;
 7377: }
 7378: 
 7379: =pod
 7380: 
 7381: =item * &print_suppression()
 7382: 
 7383: In course context returns css which causes the body to be blank when media="print",
 7384: if printout generation is unavailable for the current resource.
 7385: 
 7386: This could be because:
 7387: 
 7388: (a) printstartdate is in the future
 7389: 
 7390: (b) printenddate is in the past
 7391: 
 7392: (c) there is an active exam block with "printout"
 7393: functionality blocked
 7394: 
 7395: Users with pav, pfo or evb privileges are exempt.
 7396: 
 7397: Inputs: none
 7398: 
 7399: =cut
 7400: 
 7401: 
 7402: sub print_suppression {
 7403:     my $noprint;
 7404:     if ($env{'request.course.id'}) {
 7405:         my $scope = $env{'request.course.id'};
 7406:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7407:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7408:             return;
 7409:         }
 7410:         if ($env{'request.course.sec'} ne '') {
 7411:             $scope .= "/$env{'request.course.sec'}";
 7412:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7413:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7414:                 return;
 7415:             }
 7416:         }
 7417:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7418:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7419:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7420:         if ($blocked) {
 7421:             my $checkrole = "cm./$cdom/$cnum";
 7422:             if ($env{'request.course.sec'} ne '') {
 7423:                 $checkrole .= "/$env{'request.course.sec'}";
 7424:             }
 7425:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7426:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7427:                 $noprint = 1;
 7428:             }
 7429:         }
 7430:         unless ($noprint) {
 7431:             my $symb = &Apache::lonnet::symbread();
 7432:             if ($symb ne '') {
 7433:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7434:                 if (ref($navmap)) {
 7435:                     my $res = $navmap->getBySymb($symb);
 7436:                     if (ref($res)) {
 7437:                         if (!$res->resprintable()) {
 7438:                             $noprint = 1;
 7439:                         }
 7440:                     }
 7441:                 }
 7442:             }
 7443:         }
 7444:         if ($noprint) {
 7445:             return <<"ENDSTYLE";
 7446: <style type="text/css" media="print">
 7447:     body { display:none }
 7448: </style>
 7449: ENDSTYLE
 7450:         }
 7451:     }
 7452:     return;
 7453: }
 7454: 
 7455: =pod
 7456: 
 7457: =item * &xml_begin()
 7458: 
 7459: Returns the needed doctype and <html>
 7460: 
 7461: Inputs: none
 7462: 
 7463: =cut
 7464: 
 7465: sub xml_begin {
 7466:     my ($is_frameset) = @_;
 7467:     my $output='';
 7468: 
 7469:     if ($env{'browser.mathml'}) {
 7470: 	$output='<?xml version="1.0"?>'
 7471:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7472: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7473:             
 7474: #	    .'<!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">] >'
 7475: 	    .'<!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">'
 7476:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7477: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7478:     } elsif ($is_frameset) {
 7479:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 7480:                 '<html>'."\n";
 7481:     } else {
 7482: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 7483:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7484:     }
 7485:     return $output;
 7486: }
 7487: 
 7488: =pod
 7489: 
 7490: =item * &start_page()
 7491: 
 7492: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7493: 
 7494: Inputs:
 7495: 
 7496: =over 4
 7497: 
 7498: $title - optional title for the page
 7499: 
 7500: $head_extra - optional extra HTML to incude inside the <head>
 7501: 
 7502: $args - additional optional args supported are:
 7503: 
 7504: =over 8
 7505: 
 7506:              only_body      -> is true will set &bodytag() onlybodytag
 7507:                                     arg on
 7508:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7509:              add_entries    -> additional attributes to add to the  <body>
 7510:              domain         -> force to color decorate a page for a 
 7511:                                     specific domain
 7512:              function       -> force usage of a specific rolish color
 7513:                                     scheme
 7514:              redirect       -> see &headtag()
 7515:              bgcolor        -> override the default page bg color
 7516:              js_ready       -> return a string ready for being used in 
 7517:                                     a javascript writeln
 7518:              html_encode    -> return a string ready for being used in 
 7519:                                     a html attribute
 7520:              force_register -> if is true will turn on the &bodytag()
 7521:                                     $forcereg arg
 7522:              frameset       -> if true will start with a <frameset>
 7523:                                     rather than <body>
 7524:              skip_phases    -> hash ref of 
 7525:                                     head -> skip the <html><head> generation
 7526:                                     body -> skip all <body> generation
 7527:              no_inline_link -> if true and in remote mode, don't show the
 7528:                                     'Switch To Inline Menu' link
 7529:              no_auto_mt_title -> prevent &mt()ing the title arg
 7530:              inherit_jsmath -> when creating popup window in a page,
 7531:                                     should it have jsmath forced on by the
 7532:                                     current page
 7533:              bread_crumbs ->             Array containing breadcrumbs
 7534:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7535:              group          -> includes the current group, if page is for a
 7536:                                specific group
 7537: 
 7538: =back
 7539: 
 7540: =back
 7541: 
 7542: =cut
 7543: 
 7544: sub start_page {
 7545:     my ($title,$head_extra,$args) = @_;
 7546:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7547: 
 7548:     $env{'internal.start_page'}++;
 7549:     my ($result,@advtools);
 7550: 
 7551:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7552:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 7553:     }
 7554:     
 7555:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7556: 	if ($args->{'frameset'}) {
 7557: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7558: 						$args->{'add_entries'});
 7559: 	    $result .= "\n<frameset $attr_string>\n";
 7560:         } else {
 7561:             $result .=
 7562:                 &bodytag($title, 
 7563:                          $args->{'function'},       $args->{'add_entries'},
 7564:                          $args->{'only_body'},      $args->{'domain'},
 7565:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7566:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7567:                          $args,                     \@advtools);
 7568:         }
 7569:     }
 7570: 
 7571:     if ($args->{'js_ready'}) {
 7572: 		$result = &js_ready($result);
 7573:     }
 7574:     if ($args->{'html_encode'}) {
 7575: 		$result = &html_encode($result);
 7576:     }
 7577: 
 7578:     # Preparation for new and consistent functionlist at top of screen
 7579:     # if ($args->{'functionlist'}) {
 7580:     #            $result .= &build_functionlist();
 7581:     #}
 7582: 
 7583:     # Don't add anything more if only_body wanted or in const space
 7584:     return $result if    $args->{'only_body'} 
 7585:                       || $env{'request.state'} eq 'construct';
 7586: 
 7587:     #Breadcrumbs
 7588:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7589: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7590: 		#if any br links exists, add them to the breadcrumbs
 7591: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7592: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7593: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7594: 			}
 7595: 		}
 7596:                 # if @advtools array contains items add then to the breadcrumbs
 7597:                 if (@advtools > 0) {
 7598:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7599:                 }
 7600: 
 7601: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7602: 		if(exists($args->{'bread_crumbs_component'})){
 7603: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7604: 		}else{
 7605: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7606: 		}
 7607:     } elsif (($env{'environment.remote'} eq 'on') &&
 7608:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7609:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7610:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7611:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7612:     }
 7613:     return $result;
 7614: }
 7615: 
 7616: sub end_page {
 7617:     my ($args) = @_;
 7618:     $env{'internal.end_page'}++;
 7619:     my $result;
 7620:     if ($args->{'discussion'}) {
 7621: 	my ($target,$parser);
 7622: 	if (ref($args->{'discussion'})) {
 7623: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7624: 				$args->{'discussion'}{'parser'});
 7625: 	}
 7626: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7627:     }
 7628:     if ($args->{'frameset'}) {
 7629: 	$result .= '</frameset>';
 7630:     } else {
 7631: 	$result .= &endbodytag($args);
 7632:     }
 7633:     unless ($args->{'notbody'}) {
 7634:         $result .= "\n</html>";
 7635:     }
 7636: 
 7637:     if ($args->{'js_ready'}) {
 7638: 	$result = &js_ready($result);
 7639:     }
 7640: 
 7641:     if ($args->{'html_encode'}) {
 7642: 	$result = &html_encode($result);
 7643:     }
 7644: 
 7645:     return $result;
 7646: }
 7647: 
 7648: sub wishlist_window {
 7649:     return(<<'ENDWISHLIST');
 7650: <script type="text/javascript">
 7651: // <![CDATA[
 7652: // <!-- BEGIN LON-CAPA Internal
 7653: function set_wishlistlink(title, path) {
 7654:     if (!title) {
 7655:         title = document.title;
 7656:         title = title.replace(/^LON-CAPA /,'');
 7657:     }
 7658:     title = encodeURIComponent(title);
 7659:     if (!path) {
 7660:         path = location.pathname;
 7661:     }
 7662:     path = encodeURIComponent(path);
 7663:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7664:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7665: }
 7666: // END LON-CAPA Internal -->
 7667: // ]]>
 7668: </script>
 7669: ENDWISHLIST
 7670: }
 7671: 
 7672: sub modal_window {
 7673:     return(<<'ENDMODAL');
 7674: <script type="text/javascript">
 7675: // <![CDATA[
 7676: // <!-- BEGIN LON-CAPA Internal
 7677: var modalWindow = {
 7678: 	parent:"body",
 7679: 	windowId:null,
 7680: 	content:null,
 7681: 	width:null,
 7682: 	height:null,
 7683: 	close:function()
 7684: 	{
 7685: 	        $(".LCmodal-window").remove();
 7686: 	        $(".LCmodal-overlay").remove();
 7687: 	},
 7688: 	open:function()
 7689: 	{
 7690: 		var modal = "";
 7691: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7692: 		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;\">";
 7693: 		modal += this.content;
 7694: 		modal += "</div>";	
 7695: 
 7696: 		$(this.parent).append(modal);
 7697: 
 7698: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7699: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7700: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7701: 	}
 7702: };
 7703: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7704: 	{
 7705: 		modalWindow.windowId = "myModal";
 7706: 		modalWindow.width = width;
 7707: 		modalWindow.height = height;
 7708: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
 7709: 		modalWindow.open();
 7710: 	};	
 7711: // END LON-CAPA Internal -->
 7712: // ]]>
 7713: </script>
 7714: ENDMODAL
 7715: }
 7716: 
 7717: sub modal_link {
 7718:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7719:     unless ($width) { $width=480; }
 7720:     unless ($height) { $height=400; }
 7721:     unless ($scrolling) { $scrolling='yes'; }
 7722:     unless ($transparency) { $transparency='true'; }
 7723: 
 7724:     my $target_attr;
 7725:     if (defined($target)) {
 7726:         $target_attr = 'target="'.$target.'"';
 7727:     }
 7728:     return <<"ENDLINK";
 7729: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7730:            $linktext</a>
 7731: ENDLINK
 7732: }
 7733: 
 7734: sub modal_adhoc_script {
 7735:     my ($funcname,$width,$height,$content)=@_;
 7736:     return (<<ENDADHOC);
 7737: <script type="text/javascript">
 7738: // <![CDATA[
 7739:         var $funcname = function()
 7740:         {
 7741:                 modalWindow.windowId = "myModal";
 7742:                 modalWindow.width = $width;
 7743:                 modalWindow.height = $height;
 7744:                 modalWindow.content = '$content';
 7745:                 modalWindow.open();
 7746:         };  
 7747: // ]]>
 7748: </script>
 7749: ENDADHOC
 7750: }
 7751: 
 7752: sub modal_adhoc_inner {
 7753:     my ($funcname,$width,$height,$content)=@_;
 7754:     my $innerwidth=$width-20;
 7755:     $content=&js_ready(
 7756:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7757:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7758:                  $content.
 7759:                  &end_scrollbox().
 7760:                  &end_page()
 7761:              );
 7762:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7763: }
 7764: 
 7765: sub modal_adhoc_window {
 7766:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7767:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7768:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7769: }
 7770: 
 7771: sub modal_adhoc_launch {
 7772:     my ($funcname,$width,$height,$content)=@_;
 7773:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7774: <script type="text/javascript">
 7775: // <![CDATA[
 7776: $funcname();
 7777: // ]]>
 7778: </script>
 7779: ENDLAUNCH
 7780: }
 7781: 
 7782: sub modal_adhoc_close {
 7783:     return (<<ENDCLOSE);
 7784: <script type="text/javascript">
 7785: // <![CDATA[
 7786: modalWindow.close();
 7787: // ]]>
 7788: </script>
 7789: ENDCLOSE
 7790: }
 7791: 
 7792: sub togglebox_script {
 7793:    return(<<ENDTOGGLE);
 7794: <script type="text/javascript"> 
 7795: // <![CDATA[
 7796: function LCtoggleDisplay(id,hidetext,showtext) {
 7797:    link = document.getElementById(id + "link").childNodes[0];
 7798:    with (document.getElementById(id).style) {
 7799:       if (display == "none" ) {
 7800:           display = "inline";
 7801:           link.nodeValue = hidetext;
 7802:         } else {
 7803:           display = "none";
 7804:           link.nodeValue = showtext;
 7805:        }
 7806:    }
 7807: }
 7808: // ]]>
 7809: </script>
 7810: ENDTOGGLE
 7811: }
 7812: 
 7813: sub start_togglebox {
 7814:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7815:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7816:     unless ($showtext) { $showtext=&mt('show'); }
 7817:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7818:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7819:     return &start_data_table().
 7820:            &start_data_table_header_row().
 7821:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7822:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7823:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7824:            &end_data_table_header_row().
 7825:            '<tr id="'.$id.'" style="display:none""><td>';
 7826: }
 7827: 
 7828: sub end_togglebox {
 7829:     return '</td></tr>'.&end_data_table();
 7830: }
 7831: 
 7832: sub LCprogressbar_script {
 7833:    my ($id)=@_;
 7834:    return(<<ENDPROGRESS);
 7835: <script type="text/javascript">
 7836: // <![CDATA[
 7837: \$('#progressbar$id').progressbar({
 7838:   value: 0,
 7839:   change: function(event, ui) {
 7840:     var newVal = \$(this).progressbar('option', 'value');
 7841:     \$('.pblabel', this).text(LCprogressTxt);
 7842:   }
 7843: });
 7844: // ]]>
 7845: </script>
 7846: ENDPROGRESS
 7847: }
 7848: 
 7849: sub LCprogressbarUpdate_script {
 7850:    return(<<ENDPROGRESSUPDATE);
 7851: <style type="text/css">
 7852: .ui-progressbar { position:relative; }
 7853: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7854: </style>
 7855: <script type="text/javascript">
 7856: // <![CDATA[
 7857: var LCprogressTxt='---';
 7858: 
 7859: function LCupdateProgress(percent,progresstext,id) {
 7860:    LCprogressTxt=progresstext;
 7861:    \$('#progressbar'+id).progressbar('value',percent);
 7862: }
 7863: // ]]>
 7864: </script>
 7865: ENDPROGRESSUPDATE
 7866: }
 7867: 
 7868: my $LClastpercent;
 7869: my $LCidcnt;
 7870: my $LCcurrentid;
 7871: 
 7872: sub LCprogressbar {
 7873:     my ($r)=(@_);
 7874:     $LClastpercent=0;
 7875:     $LCidcnt++;
 7876:     $LCcurrentid=$$.'_'.$LCidcnt;
 7877:     my $starting=&mt('Starting');
 7878:     my $content=(<<ENDPROGBAR);
 7879:   <div id="progressbar$LCcurrentid">
 7880:     <span class="pblabel">$starting</span>
 7881:   </div>
 7882: ENDPROGBAR
 7883:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7884: }
 7885: 
 7886: sub LCprogressbarUpdate {
 7887:     my ($r,$val,$text)=@_;
 7888:     unless ($val) { 
 7889:        if ($LClastpercent) {
 7890:            $val=$LClastpercent;
 7891:        } else {
 7892:            $val=0;
 7893:        }
 7894:     }
 7895:     if ($val<0) { $val=0; }
 7896:     if ($val>100) { $val=0; }
 7897:     $LClastpercent=$val;
 7898:     unless ($text) { $text=$val.'%'; }
 7899:     $text=&js_ready($text);
 7900:     &r_print($r,<<ENDUPDATE);
 7901: <script type="text/javascript">
 7902: // <![CDATA[
 7903: LCupdateProgress($val,'$text','$LCcurrentid');
 7904: // ]]>
 7905: </script>
 7906: ENDUPDATE
 7907: }
 7908: 
 7909: sub LCprogressbarClose {
 7910:     my ($r)=@_;
 7911:     $LClastpercent=0;
 7912:     &r_print($r,<<ENDCLOSE);
 7913: <script type="text/javascript">
 7914: // <![CDATA[
 7915: \$("#progressbar$LCcurrentid").hide('slow'); 
 7916: // ]]>
 7917: </script>
 7918: ENDCLOSE
 7919: }
 7920: 
 7921: sub r_print {
 7922:     my ($r,$to_print)=@_;
 7923:     if ($r) {
 7924:       $r->print($to_print);
 7925:       $r->rflush();
 7926:     } else {
 7927:       print($to_print);
 7928:     }
 7929: }
 7930: 
 7931: sub html_encode {
 7932:     my ($result) = @_;
 7933: 
 7934:     $result = &HTML::Entities::encode($result,'<>&"');
 7935:     
 7936:     return $result;
 7937: }
 7938: 
 7939: sub js_ready {
 7940:     my ($result) = @_;
 7941: 
 7942:     $result =~ s/[\n\r]/ /xmsg;
 7943:     $result =~ s/\\/\\\\/xmsg;
 7944:     $result =~ s/'/\\'/xmsg;
 7945:     $result =~ s{</}{<\\/}xmsg;
 7946:     
 7947:     return $result;
 7948: }
 7949: 
 7950: sub validate_page {
 7951:     if (  exists($env{'internal.start_page'})
 7952: 	  &&     $env{'internal.start_page'} > 1) {
 7953: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7954: 				 $env{'internal.start_page'}.' '.
 7955: 				 $ENV{'request.filename'});
 7956:     }
 7957:     if (  exists($env{'internal.end_page'})
 7958: 	  &&     $env{'internal.end_page'} > 1) {
 7959: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7960: 				 $env{'internal.end_page'}.' '.
 7961: 				 $env{'request.filename'});
 7962:     }
 7963:     if (     exists($env{'internal.start_page'})
 7964: 	&& ! exists($env{'internal.end_page'})) {
 7965: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7966: 				 $env{'request.filename'});
 7967:     }
 7968:     if (   ! exists($env{'internal.start_page'})
 7969: 	&&   exists($env{'internal.end_page'})) {
 7970: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7971: 				 $env{'request.filename'});
 7972:     }
 7973: }
 7974: 
 7975: 
 7976: sub start_scrollbox {
 7977:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 7978:     unless ($outerwidth) { $outerwidth='520px'; }
 7979:     unless ($width) { $width='500px'; }
 7980:     unless ($height) { $height='200px'; }
 7981:     my ($table_id,$div_id,$tdcol);
 7982:     if ($id ne '') {
 7983:         $table_id = ' id="table_'.$id.'"';
 7984:         $div_id = ' id="div_'.$id.'"';
 7985:     }
 7986:     if ($bgcolor ne '') {
 7987:         $tdcol = "background-color: $bgcolor;";
 7988:     }
 7989:     my $nicescroll_js;
 7990:     if ($env{'browser.mobile'}) {
 7991:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 7992:     }
 7993:     return <<"END";
 7994: $nicescroll_js
 7995: 
 7996: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 7997: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 7998: END
 7999: }
 8000: 
 8001: sub end_scrollbox {
 8002:     return '</div></td></tr></table>';
 8003: }
 8004: 
 8005: sub nicescroll_javascript {
 8006:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8007:     my %options;
 8008:     if (ref($cursor) eq 'HASH') {
 8009:         %options = %{$cursor};
 8010:     }
 8011:     unless ($options{'railalign'} =~ /^left|right$/) {
 8012:         $options{'railalign'} = 'left';
 8013:     }
 8014:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8015:         my $function  = &get_users_function();
 8016:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8017:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8018:             $options{'cursorcolor'} = '#00F';
 8019:         }
 8020:     }
 8021:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8022:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8023:             $options{'cursoropacity'}='1.0';
 8024:         }
 8025:     } else {
 8026:         $options{'cursoropacity'}='1.0';
 8027:     }
 8028:     if ($options{'cursorfixedheight'} eq 'none') {
 8029:         delete($options{'cursorfixedheight'});
 8030:     } else {
 8031:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8032:     }
 8033:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8034:         delete($options{'railoffset'});
 8035:     }
 8036:     my @niceoptions;
 8037:     while (my($key,$value) = each(%options)) {
 8038:         if ($value =~ /^\{.+\}$/) {
 8039:             push(@niceoptions,$key.':'.$value);
 8040:         } else {
 8041:             push(@niceoptions,$key.':"'.$value.'"');
 8042:         }
 8043:     }
 8044:     my $nicescroll_js = '
 8045: $(document).ready(
 8046:       function() {
 8047:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8048:       }
 8049: );
 8050: ';
 8051:     if ($framecheck) {
 8052:         $nicescroll_js .= '
 8053: function expand_div(caller) {
 8054:     if (top === self) {
 8055:         document.getElementById("'.$id.'").style.width = "auto";
 8056:         document.getElementById("'.$id.'").style.height = "auto";
 8057:     } else {
 8058:         try {
 8059:             if (parent.frames) {
 8060:                 if (parent.frames.length > 1) {
 8061:                     var framesrc = parent.frames[1].location.href;
 8062:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8063:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8064:                         document.getElementById("'.$id.'").style.width = "auto";
 8065:                         document.getElementById("'.$id.'").style.height = "auto";
 8066:                     }
 8067:                 }
 8068:             }
 8069:         } catch (e) {
 8070:             return;
 8071:         }
 8072:     }
 8073:     return;
 8074: }
 8075: ';
 8076:     }
 8077:     if ($needjsready) {
 8078:         $nicescroll_js = '
 8079: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8080:     } else {
 8081:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8082:     }
 8083:     return $nicescroll_js;
 8084: }
 8085: 
 8086: sub simple_error_page {
 8087:     my ($r,$title,$msg,$args) = @_;
 8088:     if (ref($args) eq 'HASH') {
 8089:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8090:     } else {
 8091:         $msg = &mt($msg);
 8092:     }
 8093: 
 8094:     my $page =
 8095: 	&Apache::loncommon::start_page($title).
 8096: 	'<p class="LC_error">'.$msg.'</p>'.
 8097: 	&Apache::loncommon::end_page();
 8098:     if (ref($r)) {
 8099: 	$r->print($page);
 8100: 	return;
 8101:     }
 8102:     return $page;
 8103: }
 8104: 
 8105: {
 8106:     my @row_count;
 8107: 
 8108:     sub start_data_table_count {
 8109:         unshift(@row_count, 0);
 8110:         return;
 8111:     }
 8112: 
 8113:     sub end_data_table_count {
 8114:         shift(@row_count);
 8115:         return;
 8116:     }
 8117: 
 8118:     sub start_data_table {
 8119: 	my ($add_class,$id) = @_;
 8120: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8121:         my $table_id;
 8122:         if (defined($id)) {
 8123:             $table_id = ' id="'.$id.'"';
 8124:         }
 8125: 	&start_data_table_count();
 8126: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8127:     }
 8128: 
 8129:     sub end_data_table {
 8130: 	&end_data_table_count();
 8131: 	return '</table>'."\n";;
 8132:     }
 8133: 
 8134:     sub start_data_table_row {
 8135: 	my ($add_class, $id) = @_;
 8136: 	$row_count[0]++;
 8137: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8138: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8139:         $id = (' id="'.$id.'"') unless ($id eq '');
 8140:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8141:     }
 8142:     
 8143:     sub continue_data_table_row {
 8144: 	my ($add_class, $id) = @_;
 8145: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8146: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8147:         $id = (' id="'.$id.'"') unless ($id eq '');
 8148:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8149:     }
 8150: 
 8151:     sub end_data_table_row {
 8152: 	return '</tr>'."\n";;
 8153:     }
 8154: 
 8155:     sub start_data_table_empty_row {
 8156: #	$row_count[0]++;
 8157: 	return  '<tr class="LC_empty_row" >'."\n";;
 8158:     }
 8159: 
 8160:     sub end_data_table_empty_row {
 8161: 	return '</tr>'."\n";;
 8162:     }
 8163: 
 8164:     sub start_data_table_header_row {
 8165: 	return  '<tr class="LC_header_row">'."\n";;
 8166:     }
 8167: 
 8168:     sub end_data_table_header_row {
 8169: 	return '</tr>'."\n";;
 8170:     }
 8171: 
 8172:     sub data_table_caption {
 8173:         my $caption = shift;
 8174:         return "<caption class=\"LC_caption\">$caption</caption>";
 8175:     }
 8176: }
 8177: 
 8178: =pod
 8179: 
 8180: =item * &inhibit_menu_check($arg)
 8181: 
 8182: Checks for a inhibitmenu state and generates output to preserve it
 8183: 
 8184: Inputs:         $arg - can be any of
 8185:                      - undef - in which case the return value is a string 
 8186:                                to add  into arguments list of a uri
 8187:                      - 'input' - in which case the return value is a HTML
 8188:                                  <form> <input> field of type hidden to
 8189:                                  preserve the value
 8190:                      - a url - in which case the return value is the url with
 8191:                                the neccesary cgi args added to preserve the
 8192:                                inhibitmenu state
 8193:                      - a ref to a url - no return value, but the string is
 8194:                                         updated to include the neccessary cgi
 8195:                                         args to preserve the inhibitmenu state
 8196: 
 8197: =cut
 8198: 
 8199: sub inhibit_menu_check {
 8200:     my ($arg) = @_;
 8201:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8202:     if ($arg eq 'input') {
 8203: 	if ($env{'form.inhibitmenu'}) {
 8204: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8205: 	} else {
 8206: 	    return
 8207: 	}
 8208:     }
 8209:     if ($env{'form.inhibitmenu'}) {
 8210: 	if (ref($arg)) {
 8211: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8212: 	} elsif ($arg eq '') {
 8213: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8214: 	} else {
 8215: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8216: 	}
 8217:     }
 8218:     if (!ref($arg)) {
 8219: 	return $arg;
 8220:     }
 8221: }
 8222: 
 8223: ###############################################
 8224: 
 8225: =pod
 8226: 
 8227: =back
 8228: 
 8229: =head1 User Information Routines
 8230: 
 8231: =over 4
 8232: 
 8233: =item * &get_users_function()
 8234: 
 8235: Used by &bodytag to determine the current users primary role.
 8236: Returns either 'student','coordinator','admin', or 'author'.
 8237: 
 8238: =cut
 8239: 
 8240: ###############################################
 8241: sub get_users_function {
 8242:     my $function = 'norole';
 8243:     if ($env{'request.role'}=~/^(st)/) {
 8244:         $function='student';
 8245:     }
 8246:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8247:         $function='coordinator';
 8248:     }
 8249:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8250:         $function='admin';
 8251:     }
 8252:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8253:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8254:         $function='author';
 8255:     }
 8256:     return $function;
 8257: }
 8258: 
 8259: ###############################################
 8260: 
 8261: =pod
 8262: 
 8263: =item * &show_course()
 8264: 
 8265: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8266: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8267: 
 8268: Inputs:
 8269: None
 8270: 
 8271: Outputs:
 8272: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8273: 
 8274: =cut
 8275: 
 8276: ###############################################
 8277: sub show_course {
 8278:     my $course = !$env{'user.adv'};
 8279:     if (!$env{'user.adv'}) {
 8280:         foreach my $env (keys(%env)) {
 8281:             next if ($env !~ m/^user\.priv\./);
 8282:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8283:                 $course = 0;
 8284:                 last;
 8285:             }
 8286:         }
 8287:     }
 8288:     return $course;
 8289: }
 8290: 
 8291: ###############################################
 8292: 
 8293: =pod
 8294: 
 8295: =item * &check_user_status()
 8296: 
 8297: Determines current status of supplied role for a
 8298: specific user. Roles can be active, previous or future.
 8299: 
 8300: Inputs: 
 8301: user's domain, user's username, course's domain,
 8302: course's number, optional section ID.
 8303: 
 8304: Outputs:
 8305: role status: active, previous or future. 
 8306: 
 8307: =cut
 8308: 
 8309: sub check_user_status {
 8310:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8311:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8312:     my @uroles = keys %userinfo;
 8313:     my $srchstr;
 8314:     my $active_chk = 'none';
 8315:     my $now = time;
 8316:     if (@uroles > 0) {
 8317:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8318:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8319:         } else {
 8320:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8321:         }
 8322:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8323:             my $role_end = 0;
 8324:             my $role_start = 0;
 8325:             $active_chk = 'active';
 8326:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8327:                 $role_end = $1;
 8328:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8329:                     $role_start = $1;
 8330:                 }
 8331:             }
 8332:             if ($role_start > 0) {
 8333:                 if ($now < $role_start) {
 8334:                     $active_chk = 'future';
 8335:                 }
 8336:             }
 8337:             if ($role_end > 0) {
 8338:                 if ($now > $role_end) {
 8339:                     $active_chk = 'previous';
 8340:                 }
 8341:             }
 8342:         }
 8343:     }
 8344:     return $active_chk;
 8345: }
 8346: 
 8347: ###############################################
 8348: 
 8349: =pod
 8350: 
 8351: =item * &get_sections()
 8352: 
 8353: Determines all the sections for a course including
 8354: sections with students and sections containing other roles.
 8355: Incoming parameters: 
 8356: 
 8357: 1. domain
 8358: 2. course number 
 8359: 3. reference to array containing roles for which sections should 
 8360: be gathered (optional).
 8361: 4. reference to array containing status types for which sections 
 8362: should be gathered (optional).
 8363: 
 8364: If the third argument is undefined, sections are gathered for any role. 
 8365: If the fourth argument is undefined, sections are gathered for any status.
 8366: Permissible values are 'active' or 'future' or 'previous'.
 8367:  
 8368: Returns section hash (keys are section IDs, values are
 8369: number of users in each section), subject to the
 8370: optional roles filter, optional status filter 
 8371: 
 8372: =cut
 8373: 
 8374: ###############################################
 8375: sub get_sections {
 8376:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8377:     if (!defined($cdom) || !defined($cnum)) {
 8378:         my $cid =  $env{'request.course.id'};
 8379: 
 8380: 	return if (!defined($cid));
 8381: 
 8382:         $cdom = $env{'course.'.$cid.'.domain'};
 8383:         $cnum = $env{'course.'.$cid.'.num'};
 8384:     }
 8385: 
 8386:     my %sectioncount;
 8387:     my $now = time;
 8388: 
 8389:     my $check_students = 1;
 8390:     my $only_students = 0;
 8391:     if (ref($possible_roles) eq 'ARRAY') {
 8392:         if (grep(/^st$/,@{$possible_roles})) {
 8393:             if (@{$possible_roles} == 1) {
 8394:                 $only_students = 1;
 8395:             }
 8396:         } else {
 8397:             $check_students = 0;
 8398:         }
 8399:     }
 8400: 
 8401:     if ($check_students) {
 8402: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8403: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8404: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8405:         my $start_index = &Apache::loncoursedata::CL_START();
 8406:         my $end_index = &Apache::loncoursedata::CL_END();
 8407:         my $status;
 8408: 	while (my ($student,$data) = each(%$classlist)) {
 8409: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8410: 				                     $data->[$status_index],
 8411:                                                      $data->[$start_index],
 8412:                                                      $data->[$end_index]);
 8413:             if ($stu_status eq 'Active') {
 8414:                 $status = 'active';
 8415:             } elsif ($end < $now) {
 8416:                 $status = 'previous';
 8417:             } elsif ($start > $now) {
 8418:                 $status = 'future';
 8419:             } 
 8420: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8421:                 if ((!defined($possible_status)) || (($status ne '') && 
 8422:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8423: 		    $sectioncount{$section}++;
 8424:                 }
 8425: 	    }
 8426: 	}
 8427:     }
 8428:     if ($only_students) {
 8429:         return %sectioncount;
 8430:     }
 8431:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8432:     foreach my $user (sort(keys(%courseroles))) {
 8433: 	if ($user !~ /^(\w{2})/) { next; }
 8434: 	my ($role) = ($user =~ /^(\w{2})/);
 8435: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8436: 	my ($section,$status);
 8437: 	if ($role eq 'cr' &&
 8438: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8439: 	    $section=$1;
 8440: 	}
 8441: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8442: 	if (!defined($section) || $section eq '-1') { next; }
 8443:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8444:         if ($end == -1 && $start == -1) {
 8445:             next; #deleted role
 8446:         }
 8447:         if (!defined($possible_status)) { 
 8448:             $sectioncount{$section}++;
 8449:         } else {
 8450:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8451:                 $status = 'active';
 8452:             } elsif ($end < $now) {
 8453:                 $status = 'future';
 8454:             } elsif ($start > $now) {
 8455:                 $status = 'previous';
 8456:             }
 8457:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8458:                 $sectioncount{$section}++;
 8459:             }
 8460:         }
 8461:     }
 8462:     return %sectioncount;
 8463: }
 8464: 
 8465: ###############################################
 8466: 
 8467: =pod
 8468: 
 8469: =item * &get_course_users()
 8470: 
 8471: Retrieves usernames:domains for users in the specified course
 8472: with specific role(s), and access status. 
 8473: 
 8474: Incoming parameters:
 8475: 1. course domain
 8476: 2. course number
 8477: 3. access status: users must have - either active, 
 8478: previous, future, or all.
 8479: 4. reference to array of permissible roles
 8480: 5. reference to array of section restrictions (optional)
 8481: 6. reference to results object (hash of hashes).
 8482: 7. reference to optional userdata hash
 8483: 8. reference to optional statushash
 8484: 9. flag if privileged users (except those set to unhide in
 8485:    course settings) should be excluded    
 8486: Keys of top level results hash are roles.
 8487: Keys of inner hashes are username:domain, with 
 8488: values set to access type.
 8489: Optional userdata hash returns an array with arguments in the 
 8490: same order as loncoursedata::get_classlist() for student data.
 8491: 
 8492: Optional statushash returns
 8493: 
 8494: Entries for end, start, section and status are blank because
 8495: of the possibility of multiple values for non-student roles.
 8496: 
 8497: =cut
 8498: 
 8499: ###############################################
 8500: 
 8501: sub get_course_users {
 8502:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8503:     my %idx = ();
 8504:     my %seclists;
 8505: 
 8506:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8507:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8508:     $idx{end} = &Apache::loncoursedata::CL_END();
 8509:     $idx{start} = &Apache::loncoursedata::CL_START();
 8510:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8511:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8512:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8513:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8514: 
 8515:     if (grep(/^st$/,@{$roles})) {
 8516:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8517:         my $now = time;
 8518:         foreach my $student (keys(%{$classlist})) {
 8519:             my $match = 0;
 8520:             my $secmatch = 0;
 8521:             my $section = $$classlist{$student}[$idx{section}];
 8522:             my $status = $$classlist{$student}[$idx{status}];
 8523:             if ($section eq '') {
 8524:                 $section = 'none';
 8525:             }
 8526:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8527:                 if (grep(/^all$/,@{$sections})) {
 8528:                     $secmatch = 1;
 8529:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8530:                     if (grep(/^none$/,@{$sections})) {
 8531:                         $secmatch = 1;
 8532:                     }
 8533:                 } else {  
 8534: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8535: 		        $secmatch = 1;
 8536:                     }
 8537: 		}
 8538:                 if (!$secmatch) {
 8539:                     next;
 8540:                 }
 8541:             }
 8542:             if (defined($$types{'active'})) {
 8543:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8544:                     push(@{$$users{st}{$student}},'active');
 8545:                     $match = 1;
 8546:                 }
 8547:             }
 8548:             if (defined($$types{'previous'})) {
 8549:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8550:                     push(@{$$users{st}{$student}},'previous');
 8551:                     $match = 1;
 8552:                 }
 8553:             }
 8554:             if (defined($$types{'future'})) {
 8555:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8556:                     push(@{$$users{st}{$student}},'future');
 8557:                     $match = 1;
 8558:                 }
 8559:             }
 8560:             if ($match) {
 8561:                 push(@{$seclists{$student}},$section);
 8562:                 if (ref($userdata) eq 'HASH') {
 8563:                     $$userdata{$student} = $$classlist{$student};
 8564:                 }
 8565:                 if (ref($statushash) eq 'HASH') {
 8566:                     $statushash->{$student}{'st'}{$section} = $status;
 8567:                 }
 8568:             }
 8569:         }
 8570:     }
 8571:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8572:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8573:         my $now = time;
 8574:         my %displaystatus = ( previous => 'Expired',
 8575:                               active   => 'Active',
 8576:                               future   => 'Future',
 8577:                             );
 8578:         my (%nothide,@possdoms);
 8579:         if ($hidepriv) {
 8580:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8581:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8582:                 if ($user !~ /:/) {
 8583:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8584:                 } else {
 8585:                     $nothide{$user} = 1;
 8586:                 }
 8587:             }
 8588:             my @possdoms = ($cdom);
 8589:             if ($coursehash{'checkforpriv'}) {
 8590:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8591:             }
 8592:         }
 8593:         foreach my $person (sort(keys(%coursepersonnel))) {
 8594:             my $match = 0;
 8595:             my $secmatch = 0;
 8596:             my $status;
 8597:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8598:             $user =~ s/:$//;
 8599:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8600:             if ($end == -1 || $start == -1) {
 8601:                 next;
 8602:             }
 8603:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8604:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8605:                 my ($uname,$udom) = split(/:/,$user);
 8606:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8607:                     if (grep(/^all$/,@{$sections})) {
 8608:                         $secmatch = 1;
 8609:                     } elsif ($usec eq '') {
 8610:                         if (grep(/^none$/,@{$sections})) {
 8611:                             $secmatch = 1;
 8612:                         }
 8613:                     } else {
 8614:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8615:                             $secmatch = 1;
 8616:                         }
 8617:                     }
 8618:                     if (!$secmatch) {
 8619:                         next;
 8620:                     }
 8621:                 }
 8622:                 if ($usec eq '') {
 8623:                     $usec = 'none';
 8624:                 }
 8625:                 if ($uname ne '' && $udom ne '') {
 8626:                     if ($hidepriv) {
 8627:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8628:                             (!$nothide{$uname.':'.$udom})) {
 8629:                             next;
 8630:                         }
 8631:                     }
 8632:                     if ($end > 0 && $end < $now) {
 8633:                         $status = 'previous';
 8634:                     } elsif ($start > $now) {
 8635:                         $status = 'future';
 8636:                     } else {
 8637:                         $status = 'active';
 8638:                     }
 8639:                     foreach my $type (keys(%{$types})) { 
 8640:                         if ($status eq $type) {
 8641:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8642:                                 push(@{$$users{$role}{$user}},$type);
 8643:                             }
 8644:                             $match = 1;
 8645:                         }
 8646:                     }
 8647:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8648:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8649: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8650:                         }
 8651:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8652:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8653:                         }
 8654:                         if (ref($statushash) eq 'HASH') {
 8655:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8656:                         }
 8657:                     }
 8658:                 }
 8659:             }
 8660:         }
 8661:         if (grep(/^ow$/,@{$roles})) {
 8662:             if ((defined($cdom)) && (defined($cnum))) {
 8663:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8664:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8665:                     my $owner = $csettings{'internal.courseowner'};
 8666:                     next if ($owner eq '');
 8667:                     my ($ownername,$ownerdom);
 8668:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8669:                         $ownername = $1;
 8670:                         $ownerdom = $2;
 8671:                     } else {
 8672:                         $ownername = $owner;
 8673:                         $ownerdom = $cdom;
 8674:                         $owner = $ownername.':'.$ownerdom;
 8675:                     }
 8676:                     @{$$users{'ow'}{$owner}} = 'any';
 8677:                     if (defined($userdata) && 
 8678: 			!exists($$userdata{$owner})) {
 8679: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8680:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8681:                             push(@{$seclists{$owner}},'none');
 8682:                         }
 8683:                         if (ref($statushash) eq 'HASH') {
 8684:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8685:                         }
 8686: 		    }
 8687:                 }
 8688:             }
 8689:         }
 8690:         foreach my $user (keys(%seclists)) {
 8691:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8692:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8693:         }
 8694:     }
 8695:     return;
 8696: }
 8697: 
 8698: sub get_user_info {
 8699:     my ($udom,$uname,$idx,$userdata) = @_;
 8700:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8701: 	&plainname($uname,$udom,'lastname');
 8702:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8703:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8704:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8705:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8706:     return;
 8707: }
 8708: 
 8709: ###############################################
 8710: 
 8711: =pod
 8712: 
 8713: =item * &get_user_quota()
 8714: 
 8715: Retrieves quota assigned for storage of user files.
 8716: Default is to report quota for portfolio files.
 8717: 
 8718: Incoming parameters:
 8719: 1. user's username
 8720: 2. user's domain
 8721: 3. quota name - portfolio, author, or course
 8722:    (if no quota name provided, defaults to portfolio).
 8723: 4. crstype - official, unofficial, textbook or community, if quota name is
 8724:    course
 8725: 
 8726: Returns:
 8727: 1. Disk quota (in MB) assigned to student.
 8728: 2. (Optional) Type of setting: custom or default
 8729:    (individually assigned or default for user's 
 8730:    institutional status).
 8731: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8732:    or student - types as defined in localenroll::inst_usertypes 
 8733:    for user's domain, which determines default quota for user.
 8734: 4. (Optional) - Default quota which would apply to the user.
 8735: 
 8736: If a value has been stored in the user's environment, 
 8737: it will return that, otherwise it returns the maximal default
 8738: defined for the user's institutional status(es) in the domain.
 8739: 
 8740: =cut
 8741: 
 8742: ###############################################
 8743: 
 8744: 
 8745: sub get_user_quota {
 8746:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8747:     my ($quota,$quotatype,$settingstatus,$defquota);
 8748:     if (!defined($udom)) {
 8749:         $udom = $env{'user.domain'};
 8750:     }
 8751:     if (!defined($uname)) {
 8752:         $uname = $env{'user.name'};
 8753:     }
 8754:     if (($udom eq '' || $uname eq '') ||
 8755:         ($udom eq 'public') && ($uname eq 'public')) {
 8756:         $quota = 0;
 8757:         $quotatype = 'default';
 8758:         $defquota = 0; 
 8759:     } else {
 8760:         my $inststatus;
 8761:         if ($quotaname eq 'course') {
 8762:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8763:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8764:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8765:             } else {
 8766:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8767:                 $quota = $cenv{'internal.uploadquota'};
 8768:             }
 8769:         } else {
 8770:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8771:                 if ($quotaname eq 'author') {
 8772:                     $quota = $env{'environment.authorquota'};
 8773:                 } else {
 8774:                     $quota = $env{'environment.portfolioquota'};
 8775:                 }
 8776:                 $inststatus = $env{'environment.inststatus'};
 8777:             } else {
 8778:                 my %userenv = 
 8779:                     &Apache::lonnet::get('environment',['portfolioquota',
 8780:                                          'authorquota','inststatus'],$udom,$uname);
 8781:                 my ($tmp) = keys(%userenv);
 8782:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8783:                     if ($quotaname eq 'author') {
 8784:                         $quota = $userenv{'authorquota'};
 8785:                     } else {
 8786:                         $quota = $userenv{'portfolioquota'};
 8787:                     }
 8788:                     $inststatus = $userenv{'inststatus'};
 8789:                 } else {
 8790:                     undef(%userenv);
 8791:                 }
 8792:             }
 8793:         }
 8794:         if ($quota eq '' || wantarray) {
 8795:             if ($quotaname eq 'course') {
 8796:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8797:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 8798:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 8799:                     $defquota = $domdefs{$crstype.'quota'};
 8800:                 }
 8801:                 if ($defquota eq '') {
 8802:                     $defquota = 500;
 8803:                 }
 8804:             } else {
 8805:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8806:             }
 8807:             if ($quota eq '') {
 8808:                 $quota = $defquota;
 8809:                 $quotatype = 'default';
 8810:             } else {
 8811:                 $quotatype = 'custom';
 8812:             }
 8813:         }
 8814:     }
 8815:     if (wantarray) {
 8816:         return ($quota,$quotatype,$settingstatus,$defquota);
 8817:     } else {
 8818:         return $quota;
 8819:     }
 8820: }
 8821: 
 8822: ###############################################
 8823: 
 8824: =pod
 8825: 
 8826: =item * &default_quota()
 8827: 
 8828: Retrieves default quota assigned for storage of user portfolio files,
 8829: given an (optional) user's institutional status.
 8830: 
 8831: Incoming parameters:
 8832: 
 8833: 1. domain
 8834: 2. (Optional) institutional status(es).  This is a : separated list of 
 8835:    status types (e.g., faculty, staff, student etc.)
 8836:    which apply to the user for whom the default is being retrieved.
 8837:    If the institutional status string in undefined, the domain
 8838:    default quota will be returned.
 8839: 3.  quota name - portfolio, author, or course
 8840:    (if no quota name provided, defaults to portfolio).
 8841: 
 8842: Returns:
 8843: 
 8844: 1. Default disk quota (in MB) for user portfolios in the domain.
 8845: 2. (Optional) institutional type which determined the value of the
 8846:    default quota.
 8847: 
 8848: If a value has been stored in the domain's configuration db,
 8849: it will return that, otherwise it returns 20 (for backwards 
 8850: compatibility with domains which have not set up a configuration
 8851: db file; the original statically defined portfolio quota was 20 MB). 
 8852: 
 8853: If the user's status includes multiple types (e.g., staff and student),
 8854: the largest default quota which applies to the user determines the
 8855: default quota returned.
 8856: 
 8857: =cut
 8858: 
 8859: ###############################################
 8860: 
 8861: 
 8862: sub default_quota {
 8863:     my ($udom,$inststatus,$quotaname) = @_;
 8864:     my ($defquota,$settingstatus);
 8865:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8866:                                             ['quotas'],$udom);
 8867:     my $key = 'defaultquota';
 8868:     if ($quotaname eq 'author') {
 8869:         $key = 'authorquota';
 8870:     }
 8871:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8872:         if ($inststatus ne '') {
 8873:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8874:             foreach my $item (@statuses) {
 8875:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8876:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 8877:                         if ($defquota eq '') {
 8878:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8879:                             $settingstatus = $item;
 8880:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 8881:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8882:                             $settingstatus = $item;
 8883:                         }
 8884:                     }
 8885:                 } elsif ($key eq 'defaultquota') {
 8886:                     if ($quotahash{'quotas'}{$item} ne '') {
 8887:                         if ($defquota eq '') {
 8888:                             $defquota = $quotahash{'quotas'}{$item};
 8889:                             $settingstatus = $item;
 8890:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8891:                             $defquota = $quotahash{'quotas'}{$item};
 8892:                             $settingstatus = $item;
 8893:                         }
 8894:                     }
 8895:                 }
 8896:             }
 8897:         }
 8898:         if ($defquota eq '') {
 8899:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8900:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 8901:             } elsif ($key eq 'defaultquota') {
 8902:                 $defquota = $quotahash{'quotas'}{'default'};
 8903:             }
 8904:             $settingstatus = 'default';
 8905:             if ($defquota eq '') {
 8906:                 if ($quotaname eq 'author') {
 8907:                     $defquota = 500;
 8908:                 }
 8909:             }
 8910:         }
 8911:     } else {
 8912:         $settingstatus = 'default';
 8913:         if ($quotaname eq 'author') {
 8914:             $defquota = 500;
 8915:         } else {
 8916:             $defquota = 20;
 8917:         }
 8918:     }
 8919:     if (wantarray) {
 8920:         return ($defquota,$settingstatus);
 8921:     } else {
 8922:         return $defquota;
 8923:     }
 8924: }
 8925: 
 8926: ###############################################
 8927: 
 8928: =pod
 8929: 
 8930: =item * &excess_filesize_warning()
 8931: 
 8932: Returns warning message if upload of file to authoring space, or copying
 8933: of existing file within authoring space will cause quota for the authoring
 8934: space to be exceeded.
 8935: 
 8936: Same, if upload of a file directly to a course/community via Course Editor
 8937: will cause quota for uploaded content for the course to be exceeded.
 8938: 
 8939: Inputs: 7 
 8940: 1. username or coursenum
 8941: 2. domain
 8942: 3. context ('author' or 'course')
 8943: 4. filename of file for which action is being requested
 8944: 5. filesize (kB) of file
 8945: 6. action being taken: copy or upload.
 8946: 7. quotatype (in course context -- official, unofficial, community or textbook).
 8947: 
 8948: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 8949:          otherwise return null.
 8950: 
 8951: =back
 8952: 
 8953: =cut
 8954: 
 8955: sub excess_filesize_warning {
 8956:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 8957:     my $current_disk_usage = 0;
 8958:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 8959:     if ($context eq 'author') {
 8960:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 8961:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 8962:     } else {
 8963:         foreach my $subdir ('docs','supplemental') {
 8964:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 8965:         }
 8966:     }
 8967:     $disk_quota = int($disk_quota * 1000);
 8968:     if (($current_disk_usage + $filesize) > $disk_quota) {
 8969:         return '<p><span class="LC_warning">'.
 8970:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 8971:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
 8972:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 8973:                             $disk_quota,$current_disk_usage).
 8974:                '</p>';
 8975:     }
 8976:     return;
 8977: }
 8978: 
 8979: ###############################################
 8980: 
 8981: 
 8982: sub get_secgrprole_info {
 8983:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8984:     my %sections_count = &get_sections($cdom,$cnum);
 8985:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8986:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8987:     my @groups = sort(keys(%curr_groups));
 8988:     my $allroles = [];
 8989:     my $rolehash;
 8990:     my $accesshash = {
 8991:                      active => 'Currently has access',
 8992:                      future => 'Will have future access',
 8993:                      previous => 'Previously had access',
 8994:                   };
 8995:     if ($needroles) {
 8996:         $rolehash = {'all' => 'all'};
 8997:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8998: 	if (&Apache::lonnet::error(%user_roles)) {
 8999: 	    undef(%user_roles);
 9000: 	}
 9001:         foreach my $item (keys(%user_roles)) {
 9002:             my ($role)=split(/\:/,$item,2);
 9003:             if ($role eq 'cr') { next; }
 9004:             if ($role =~ /^cr/) {
 9005:                 $$rolehash{$role} = (split('/',$role))[3];
 9006:             } else {
 9007:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9008:             }
 9009:         }
 9010:         foreach my $key (sort(keys(%{$rolehash}))) {
 9011:             push(@{$allroles},$key);
 9012:         }
 9013:         push (@{$allroles},'st');
 9014:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9015:     }
 9016:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9017: }
 9018: 
 9019: sub user_picker {
 9020:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9021:     my $currdom = $dom;
 9022:     my %curr_selected = (
 9023:                         srchin => 'dom',
 9024:                         srchby => 'lastname',
 9025:                       );
 9026:     my $srchterm;
 9027:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9028:         if ($srch->{'srchby'} ne '') {
 9029:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9030:         }
 9031:         if ($srch->{'srchin'} ne '') {
 9032:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9033:         }
 9034:         if ($srch->{'srchtype'} ne '') {
 9035:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9036:         }
 9037:         if ($srch->{'srchdomain'} ne '') {
 9038:             $currdom = $srch->{'srchdomain'};
 9039:         }
 9040:         $srchterm = $srch->{'srchterm'};
 9041:     }
 9042:     my %lt=&Apache::lonlocal::texthash(
 9043:                     'usr'       => 'Search criteria',
 9044:                     'doma'      => 'Domain/institution to search',
 9045:                     'uname'     => 'username',
 9046:                     'lastname'  => 'last name',
 9047:                     'lastfirst' => 'last name, first name',
 9048:                     'crs'       => 'in this course',
 9049:                     'dom'       => 'in selected LON-CAPA domain', 
 9050:                     'alc'       => 'all LON-CAPA',
 9051:                     'instd'     => 'in institutional directory for selected domain',
 9052:                     'exact'     => 'is',
 9053:                     'contains'  => 'contains',
 9054:                     'begins'    => 'begins with',
 9055:                     'youm'      => "You must include some text to search for.",
 9056:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9057:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9058:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9059:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9060:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9061:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9062:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9063:                                        );
 9064:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9065:     my $srchinsel = ' <select name="srchin">';
 9066: 
 9067:     my @srchins = ('crs','dom','alc','instd');
 9068: 
 9069:     foreach my $option (@srchins) {
 9070:         # FIXME 'alc' option unavailable until 
 9071:         #       loncreateuser::print_user_query_page()
 9072:         #       has been completed.
 9073:         next if ($option eq 'alc');
 9074:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9075:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9076:         if ($curr_selected{'srchin'} eq $option) {
 9077:             $srchinsel .= ' 
 9078:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9079:         } else {
 9080:             $srchinsel .= '
 9081:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9082:         }
 9083:     }
 9084:     $srchinsel .= "\n  </select>\n";
 9085: 
 9086:     my $srchbysel =  ' <select name="srchby">';
 9087:     foreach my $option ('lastname','lastfirst','uname') {
 9088:         if ($curr_selected{'srchby'} eq $option) {
 9089:             $srchbysel .= '
 9090:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9091:         } else {
 9092:             $srchbysel .= '
 9093:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9094:          }
 9095:     }
 9096:     $srchbysel .= "\n  </select>\n";
 9097: 
 9098:     my $srchtypesel = ' <select name="srchtype">';
 9099:     foreach my $option ('begins','contains','exact') {
 9100:         if ($curr_selected{'srchtype'} eq $option) {
 9101:             $srchtypesel .= '
 9102:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9103:         } else {
 9104:             $srchtypesel .= '
 9105:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9106:         }
 9107:     }
 9108:     $srchtypesel .= "\n  </select>\n";
 9109: 
 9110:     my ($newuserscript,$new_user_create);
 9111:     my $context_dom = $env{'request.role.domain'};
 9112:     if ($context eq 'requestcrs') {
 9113:         if ($env{'form.coursedom'} ne '') { 
 9114:             $context_dom = $env{'form.coursedom'};
 9115:         }
 9116:     }
 9117:     if ($forcenewuser) {
 9118:         if (ref($srch) eq 'HASH') {
 9119:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9120:                 if ($cancreate) {
 9121:                     $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>';
 9122:                 } else {
 9123:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9124:                     my %usertypetext = (
 9125:                         official   => 'institutional',
 9126:                         unofficial => 'non-institutional',
 9127:                     );
 9128:                     $new_user_create = '<p class="LC_warning">'
 9129:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9130:                                       .' '
 9131:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9132:                                           ,'<a href="'.$helplink.'">','</a>')
 9133:                                       .'</p><br />';
 9134:                 }
 9135:             }
 9136:         }
 9137: 
 9138:         $newuserscript = <<"ENDSCRIPT";
 9139: 
 9140: function setSearch(createnew,callingForm) {
 9141:     if (createnew == 1) {
 9142:         for (var i=0; i<callingForm.srchby.length; i++) {
 9143:             if (callingForm.srchby.options[i].value == 'uname') {
 9144:                 callingForm.srchby.selectedIndex = i;
 9145:             }
 9146:         }
 9147:         for (var i=0; i<callingForm.srchin.length; i++) {
 9148:             if ( callingForm.srchin.options[i].value == 'dom') {
 9149: 		callingForm.srchin.selectedIndex = i;
 9150:             }
 9151:         }
 9152:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9153:             if (callingForm.srchtype.options[i].value == 'exact') {
 9154:                 callingForm.srchtype.selectedIndex = i;
 9155:             }
 9156:         }
 9157:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9158:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9159:                 callingForm.srchdomain.selectedIndex = i;
 9160:             }
 9161:         }
 9162:     }
 9163: }
 9164: ENDSCRIPT
 9165: 
 9166:     }
 9167: 
 9168:     my $output = <<"END_BLOCK";
 9169: <script type="text/javascript">
 9170: // <![CDATA[
 9171: function validateEntry(callingForm) {
 9172: 
 9173:     var checkok = 1;
 9174:     var srchin;
 9175:     for (var i=0; i<callingForm.srchin.length; i++) {
 9176: 	if ( callingForm.srchin[i].checked ) {
 9177: 	    srchin = callingForm.srchin[i].value;
 9178: 	}
 9179:     }
 9180: 
 9181:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9182:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9183:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9184:     var srchterm =  callingForm.srchterm.value;
 9185:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9186:     var msg = "";
 9187: 
 9188:     if (srchterm == "") {
 9189:         checkok = 0;
 9190:         msg += "$lt{'youm'}\\n";
 9191:     }
 9192: 
 9193:     if (srchtype== 'begins') {
 9194:         if (srchterm.length < 2) {
 9195:             checkok = 0;
 9196:             msg += "$lt{'thte'}\\n";
 9197:         }
 9198:     }
 9199: 
 9200:     if (srchtype== 'contains') {
 9201:         if (srchterm.length < 3) {
 9202:             checkok = 0;
 9203:             msg += "$lt{'thet'}\\n";
 9204:         }
 9205:     }
 9206:     if (srchin == 'instd') {
 9207:         if (srchdomain == '') {
 9208:             checkok = 0;
 9209:             msg += "$lt{'yomc'}\\n";
 9210:         }
 9211:     }
 9212:     if (srchin == 'dom') {
 9213:         if (srchdomain == '') {
 9214:             checkok = 0;
 9215:             msg += "$lt{'ymcd'}\\n";
 9216:         }
 9217:     }
 9218:     if (srchby == 'lastfirst') {
 9219:         if (srchterm.indexOf(",") == -1) {
 9220:             checkok = 0;
 9221:             msg += "$lt{'whus'}\\n";
 9222:         }
 9223:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9224:             checkok = 0;
 9225:             msg += "$lt{'whse'}\\n";
 9226:         }
 9227:     }
 9228:     if (checkok == 0) {
 9229:         alert("$lt{'thfo'}\\n"+msg);
 9230:         return;
 9231:     }
 9232:     if (checkok == 1) {
 9233:         callingForm.submit();
 9234:     }
 9235: }
 9236: 
 9237: $newuserscript
 9238: 
 9239: // ]]>
 9240: </script>
 9241: 
 9242: $new_user_create
 9243: 
 9244: END_BLOCK
 9245: 
 9246:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9247:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9248:                $domform.
 9249:                &Apache::lonhtmlcommon::row_closure().
 9250:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9251:                $srchbysel.
 9252:                $srchtypesel. 
 9253:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9254:                $srchinsel.
 9255:                &Apache::lonhtmlcommon::row_closure(1). 
 9256:                &Apache::lonhtmlcommon::end_pick_box().
 9257:                '<br />';
 9258:     return $output;
 9259: }
 9260: 
 9261: sub user_rule_check {
 9262:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9263:     my $response;
 9264:     if (ref($usershash) eq 'HASH') {
 9265:         foreach my $user (keys(%{$usershash})) {
 9266:             my ($uname,$udom) = split(/:/,$user);
 9267:             next if ($udom eq '' || $uname eq '');
 9268:             my ($id,$newuser);
 9269:             if (ref($usershash->{$user}) eq 'HASH') {
 9270:                 $newuser = $usershash->{$user}->{'newuser'};
 9271:                 $id = $usershash->{$user}->{'id'};
 9272:             }
 9273:             my $inst_response;
 9274:             if (ref($checks) eq 'HASH') {
 9275:                 if (defined($checks->{'username'})) {
 9276:                     ($inst_response,%{$inst_results->{$user}}) = 
 9277:                         &Apache::lonnet::get_instuser($udom,$uname);
 9278:                 } elsif (defined($checks->{'id'})) {
 9279:                     ($inst_response,%{$inst_results->{$user}}) =
 9280:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9281:                 }
 9282:             } else {
 9283:                 ($inst_response,%{$inst_results->{$user}}) =
 9284:                     &Apache::lonnet::get_instuser($udom,$uname);
 9285:                 return;
 9286:             }
 9287:             if (!$got_rules->{$udom}) {
 9288:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9289:                                                   ['usercreation'],$udom);
 9290:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9291:                     foreach my $item ('username','id') {
 9292:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9293:                             $$curr_rules{$udom}{$item} = 
 9294:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9295:                         }
 9296:                     }
 9297:                 }
 9298:                 $got_rules->{$udom} = 1;  
 9299:             }
 9300:             foreach my $item (keys(%{$checks})) {
 9301:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9302:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9303:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9304:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9305:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9306:                                 if ($rule_check{$rule}) {
 9307:                                     $$rulematch{$user}{$item} = $rule;
 9308:                                     if ($inst_response eq 'ok') {
 9309:                                         if (ref($inst_results) eq 'HASH') {
 9310:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9311:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9312:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9313:                                                 }
 9314:                                             }
 9315:                                         }
 9316:                                     }
 9317:                                     last;
 9318:                                 }
 9319:                             }
 9320:                         }
 9321:                     }
 9322:                 }
 9323:             }
 9324:         }
 9325:     }
 9326:     return;
 9327: }
 9328: 
 9329: sub user_rule_formats {
 9330:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9331:     my %text = ( 
 9332:                  'username' => 'Usernames',
 9333:                  'id'       => 'IDs',
 9334:                );
 9335:     my $output;
 9336:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9337:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9338:         if (@{$ruleorder} > 0) {
 9339:             $output = '<br />'.
 9340:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9341:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9342:                       ' <ul>';
 9343:             foreach my $rule (@{$ruleorder}) {
 9344:                 if (ref($curr_rules) eq 'ARRAY') {
 9345:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9346:                         if (ref($rules->{$rule}) eq 'HASH') {
 9347:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9348:                                         $rules->{$rule}{'desc'}.'</li>';
 9349:                         }
 9350:                     }
 9351:                 }
 9352:             }
 9353:             $output .= '</ul>';
 9354:         }
 9355:     }
 9356:     return $output;
 9357: }
 9358: 
 9359: sub instrule_disallow_msg {
 9360:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9361:     my $response;
 9362:     my %text = (
 9363:                   item   => 'username',
 9364:                   items  => 'usernames',
 9365:                   match  => 'matches',
 9366:                   do     => 'does',
 9367:                   action => 'a username',
 9368:                   one    => 'one',
 9369:                );
 9370:     if ($count > 1) {
 9371:         $text{'item'} = 'usernames';
 9372:         $text{'match'} ='match';
 9373:         $text{'do'} = 'do';
 9374:         $text{'action'} = 'usernames',
 9375:         $text{'one'} = 'ones';
 9376:     }
 9377:     if ($checkitem eq 'id') {
 9378:         $text{'items'} = 'IDs';
 9379:         $text{'item'} = 'ID';
 9380:         $text{'action'} = 'an ID';
 9381:         if ($count > 1) {
 9382:             $text{'item'} = 'IDs';
 9383:             $text{'action'} = 'IDs';
 9384:         }
 9385:     }
 9386:     $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 />';
 9387:     if ($mode eq 'upload') {
 9388:         if ($checkitem eq 'username') {
 9389:             $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'}.");
 9390:         } elsif ($checkitem eq 'id') {
 9391:             $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.");
 9392:         }
 9393:     } elsif ($mode eq 'selfcreate') {
 9394:         if ($checkitem eq 'id') {
 9395:             $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.");
 9396:         }
 9397:     } else {
 9398:         if ($checkitem eq 'username') {
 9399:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9400:         } elsif ($checkitem eq 'id') {
 9401:             $response .= &mt("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.");
 9402:         }
 9403:     }
 9404:     return $response;
 9405: }
 9406: 
 9407: sub personal_data_fieldtitles {
 9408:     my %fieldtitles = &Apache::lonlocal::texthash (
 9409:                         id => 'Student/Employee ID',
 9410:                         permanentemail => 'E-mail address',
 9411:                         lastname => 'Last Name',
 9412:                         firstname => 'First Name',
 9413:                         middlename => 'Middle Name',
 9414:                         generation => 'Generation',
 9415:                         gen => 'Generation',
 9416:                         inststatus => 'Affiliation',
 9417:                    );
 9418:     return %fieldtitles;
 9419: }
 9420: 
 9421: sub sorted_inst_types {
 9422:     my ($dom) = @_;
 9423:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9424:     my $othertitle = &mt('All users');
 9425:     if ($env{'request.course.id'}) {
 9426:         $othertitle  = &mt('Any users');
 9427:     }
 9428:     my @types;
 9429:     if (ref($order) eq 'ARRAY') {
 9430:         @types = @{$order};
 9431:     }
 9432:     if (@types == 0) {
 9433:         if (ref($usertypes) eq 'HASH') {
 9434:             @types = sort(keys(%{$usertypes}));
 9435:         }
 9436:     }
 9437:     if (keys(%{$usertypes}) > 0) {
 9438:         $othertitle = &mt('Other users');
 9439:     }
 9440:     return ($othertitle,$usertypes,\@types);
 9441: }
 9442: 
 9443: sub get_institutional_codes {
 9444:     my ($settings,$allcourses,$LC_code) = @_;
 9445: # Get complete list of course sections to update
 9446:     my @currsections = ();
 9447:     my @currxlists = ();
 9448:     my $coursecode = $$settings{'internal.coursecode'};
 9449: 
 9450:     if ($$settings{'internal.sectionnums'} ne '') {
 9451:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9452:     }
 9453: 
 9454:     if ($$settings{'internal.crosslistings'} ne '') {
 9455:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9456:     }
 9457: 
 9458:     if (@currxlists > 0) {
 9459:         foreach (@currxlists) {
 9460:             if (m/^([^:]+):(\w*)$/) {
 9461:                 unless (grep/^$1$/,@{$allcourses}) {
 9462:                     push @{$allcourses},$1;
 9463:                     $$LC_code{$1} = $2;
 9464:                 }
 9465:             }
 9466:         }
 9467:     }
 9468:  
 9469:     if (@currsections > 0) {
 9470:         foreach (@currsections) {
 9471:             if (m/^(\w+):(\w*)$/) {
 9472:                 my $sec = $coursecode.$1;
 9473:                 my $lc_sec = $2;
 9474:                 unless (grep/^$sec$/,@{$allcourses}) {
 9475:                     push @{$allcourses},$sec;
 9476:                     $$LC_code{$sec} = $lc_sec;
 9477:                 }
 9478:             }
 9479:         }
 9480:     }
 9481:     return;
 9482: }
 9483: 
 9484: sub get_standard_codeitems {
 9485:     return ('Year','Semester','Department','Number','Section');
 9486: }
 9487: 
 9488: =pod
 9489: 
 9490: =head1 Slot Helpers
 9491: 
 9492: =over 4
 9493: 
 9494: =item * sorted_slots()
 9495: 
 9496: Sorts an array of slot names in order of an optional sort key,
 9497: default sort is by slot start time (earliest first). 
 9498: 
 9499: Inputs:
 9500: 
 9501: =over 4
 9502: 
 9503: slotsarr  - Reference to array of unsorted slot names.
 9504: 
 9505: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9506: 
 9507: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9508: 
 9509: =back
 9510: 
 9511: Returns:
 9512: 
 9513: =over 4
 9514: 
 9515: sorted   - An array of slot names sorted by a specified sort key 
 9516:            (default sort key is start time of the slot).
 9517: 
 9518: =back
 9519: 
 9520: =cut
 9521: 
 9522: 
 9523: sub sorted_slots {
 9524:     my ($slotsarr,$slots,$sortkey) = @_;
 9525:     if ($sortkey eq '') {
 9526:         $sortkey = 'starttime';
 9527:     }
 9528:     my @sorted;
 9529:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9530:         @sorted =
 9531:             sort {
 9532:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9533:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9534:                      }
 9535:                      if (ref($slots->{$a})) { return -1;}
 9536:                      if (ref($slots->{$b})) { return 1;}
 9537:                      return 0;
 9538:                  } @{$slotsarr};
 9539:     }
 9540:     return @sorted;
 9541: }
 9542: 
 9543: =pod
 9544: 
 9545: =item * get_future_slots()
 9546: 
 9547: Inputs:
 9548: 
 9549: =over 4
 9550: 
 9551: cnum - course number
 9552: 
 9553: cdom - course domain
 9554: 
 9555: now - current UNIX time
 9556: 
 9557: symb - optional symb
 9558: 
 9559: =back
 9560: 
 9561: Returns:
 9562: 
 9563: =over 4
 9564: 
 9565: sorted_reservable - ref to array of student_schedulable slots currently 
 9566:                     reservable, ordered by end date of reservation period.
 9567: 
 9568: reservable_now - ref to hash of student_schedulable slots currently
 9569:                  reservable.
 9570: 
 9571:     Keys in inner hash are:
 9572:     (a) symb: either blank or symb to which slot use is restricted.
 9573:     (b) endreserve: end date of reservation period. 
 9574: 
 9575: sorted_future - ref to array of student_schedulable slots reservable in
 9576:                 the future, ordered by start date of reservation period.
 9577: 
 9578: future_reservable - ref to hash of student_schedulable slots reservable
 9579:                     in the future.
 9580: 
 9581:     Keys in inner hash are:
 9582:     (a) symb: either blank or symb to which slot use is restricted.
 9583:     (b) startreserve:  start date of reservation period.
 9584: 
 9585: =back
 9586: 
 9587: =cut
 9588: 
 9589: sub get_future_slots {
 9590:     my ($cnum,$cdom,$now,$symb) = @_;
 9591:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9592:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9593:     foreach my $slot (keys(%slots)) {
 9594:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9595:         if ($symb) {
 9596:             next if (($slots{$slot}->{'symb'} ne '') && 
 9597:                      ($slots{$slot}->{'symb'} ne $symb));
 9598:         }
 9599:         if (($slots{$slot}->{'starttime'} > $now) &&
 9600:             ($slots{$slot}->{'endtime'} > $now)) {
 9601:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9602:                 my $userallowed = 0;
 9603:                 if ($slots{$slot}->{'allowedsections'}) {
 9604:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9605:                     if (!defined($env{'request.role.sec'})
 9606:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9607:                         $userallowed=1;
 9608:                     } else {
 9609:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9610:                             $userallowed=1;
 9611:                         }
 9612:                     }
 9613:                     unless ($userallowed) {
 9614:                         if (defined($env{'request.course.groups'})) {
 9615:                             my @groups = split(/:/,$env{'request.course.groups'});
 9616:                             foreach my $group (@groups) {
 9617:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9618:                                     $userallowed=1;
 9619:                                     last;
 9620:                                 }
 9621:                             }
 9622:                         }
 9623:                     }
 9624:                 }
 9625:                 if ($slots{$slot}->{'allowedusers'}) {
 9626:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9627:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9628:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9629:                         $userallowed = 1;
 9630:                     }
 9631:                 }
 9632:                 next unless($userallowed);
 9633:             }
 9634:             my $startreserve = $slots{$slot}->{'startreserve'};
 9635:             my $endreserve = $slots{$slot}->{'endreserve'};
 9636:             my $symb = $slots{$slot}->{'symb'};
 9637:             if (($startreserve < $now) &&
 9638:                 (!$endreserve || $endreserve > $now)) {
 9639:                 my $lastres = $endreserve;
 9640:                 if (!$lastres) {
 9641:                     $lastres = $slots{$slot}->{'starttime'};
 9642:                 }
 9643:                 $reservable_now{$slot} = {
 9644:                                            symb       => $symb,
 9645:                                            endreserve => $lastres
 9646:                                          };
 9647:             } elsif (($startreserve > $now) &&
 9648:                      (!$endreserve || $endreserve > $startreserve)) {
 9649:                 $future_reservable{$slot} = {
 9650:                                               symb         => $symb,
 9651:                                               startreserve => $startreserve
 9652:                                             };
 9653:             }
 9654:         }
 9655:     }
 9656:     my @unsorted_reservable = keys(%reservable_now);
 9657:     if (@unsorted_reservable > 0) {
 9658:         @sorted_reservable = 
 9659:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9660:     }
 9661:     my @unsorted_future = keys(%future_reservable);
 9662:     if (@unsorted_future > 0) {
 9663:         @sorted_future =
 9664:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9665:     }
 9666:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9667: }
 9668: 
 9669: =pod
 9670: 
 9671: =back
 9672: 
 9673: =head1 HTTP Helpers
 9674: 
 9675: =over 4
 9676: 
 9677: =item * &get_unprocessed_cgi($query,$possible_names)
 9678: 
 9679: Modify the %env hash to contain unprocessed CGI form parameters held in
 9680: $query.  The parameters listed in $possible_names (an array reference),
 9681: will be set in $env{'form.name'} if they do not already exist.
 9682: 
 9683: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9684: $possible_names is an ref to an array of form element names.  As an example:
 9685: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9686: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9687: 
 9688: =cut
 9689: 
 9690: sub get_unprocessed_cgi {
 9691:   my ($query,$possible_names)= @_;
 9692:   # $Apache::lonxml::debug=1;
 9693:   foreach my $pair (split(/&/,$query)) {
 9694:     my ($name, $value) = split(/=/,$pair);
 9695:     $name = &unescape($name);
 9696:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9697:       $value =~ tr/+/ /;
 9698:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9699:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9700:     }
 9701:   }
 9702: }
 9703: 
 9704: =pod
 9705: 
 9706: =item * &cacheheader() 
 9707: 
 9708: returns cache-controlling header code
 9709: 
 9710: =cut
 9711: 
 9712: sub cacheheader {
 9713:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9714:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9715:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9716:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9717:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9718:     return $output;
 9719: }
 9720: 
 9721: =pod
 9722: 
 9723: =item * &no_cache($r) 
 9724: 
 9725: specifies header code to not have cache
 9726: 
 9727: =cut
 9728: 
 9729: sub no_cache {
 9730:     my ($r) = @_;
 9731:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9732: 	$env{'request.method'} ne 'GET') { return ''; }
 9733:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9734:     $r->no_cache(1);
 9735:     $r->header_out("Expires" => $date);
 9736:     $r->header_out("Pragma" => "no-cache");
 9737: }
 9738: 
 9739: sub content_type {
 9740:     my ($r,$type,$charset) = @_;
 9741:     if ($r) {
 9742: 	#  Note that printout.pl calls this with undef for $r.
 9743: 	&no_cache($r);
 9744:     }
 9745:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9746:     unless ($charset) {
 9747: 	$charset=&Apache::lonlocal::current_encoding;
 9748:     }
 9749:     if ($charset) { $type.='; charset='.$charset; }
 9750:     if ($r) {
 9751: 	$r->content_type($type);
 9752:     } else {
 9753: 	print("Content-type: $type\n\n");
 9754:     }
 9755: }
 9756: 
 9757: =pod
 9758: 
 9759: =item * &add_to_env($name,$value) 
 9760: 
 9761: adds $name to the %env hash with value
 9762: $value, if $name already exists, the entry is converted to an array
 9763: reference and $value is added to the array.
 9764: 
 9765: =cut
 9766: 
 9767: sub add_to_env {
 9768:   my ($name,$value)=@_;
 9769:   if (defined($env{$name})) {
 9770:     if (ref($env{$name})) {
 9771:       #already have multiple values
 9772:       push(@{ $env{$name} },$value);
 9773:     } else {
 9774:       #first time seeing multiple values, convert hash entry to an arrayref
 9775:       my $first=$env{$name};
 9776:       undef($env{$name});
 9777:       push(@{ $env{$name} },$first,$value);
 9778:     }
 9779:   } else {
 9780:     $env{$name}=$value;
 9781:   }
 9782: }
 9783: 
 9784: =pod
 9785: 
 9786: =item * &get_env_multiple($name) 
 9787: 
 9788: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9789: values may be defined and end up as an array ref.
 9790: 
 9791: returns an array of values
 9792: 
 9793: =cut
 9794: 
 9795: sub get_env_multiple {
 9796:     my ($name) = @_;
 9797:     my @values;
 9798:     if (defined($env{$name})) {
 9799:         # exists is it an array
 9800:         if (ref($env{$name})) {
 9801:             @values=@{ $env{$name} };
 9802:         } else {
 9803:             $values[0]=$env{$name};
 9804:         }
 9805:     }
 9806:     return(@values);
 9807: }
 9808: 
 9809: sub ask_for_embedded_content {
 9810:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9811:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9812:         %currsubfile,%unused,$rem);
 9813:     my $counter = 0;
 9814:     my $numnew = 0;
 9815:     my $numremref = 0;
 9816:     my $numinvalid = 0;
 9817:     my $numpathchg = 0;
 9818:     my $numexisting = 0;
 9819:     my $numunused = 0;
 9820:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9821:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
 9822:     my $heading = &mt('Upload embedded files');
 9823:     my $buttontext = &mt('Upload');
 9824: 
 9825:     if ($env{'request.course.id'}) {
 9826:         if ($actionurl eq '/adm/dependencies') {
 9827:             $navmap = Apache::lonnavmaps::navmap->new();
 9828:         }
 9829:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9830:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9831:     }
 9832:     if (($actionurl eq '/adm/portfolio') ||
 9833:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9834:         my $current_path='/';
 9835:         if ($env{'form.currentpath'}) {
 9836:             $current_path = $env{'form.currentpath'};
 9837:         }
 9838:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9839:             $udom = $cdom;
 9840:             $uname = $cnum;
 9841:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9842:         } else {
 9843:             $udom = $env{'user.domain'};
 9844:             $uname = $env{'user.name'};
 9845:             $url = '/userfiles/portfolio';
 9846:         }
 9847:         $toplevel = $url.'/';
 9848:         $url .= $current_path;
 9849:         $getpropath = 1;
 9850:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9851:              ($actionurl eq '/adm/imsimport')) { 
 9852:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9853:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9854:         $toplevel = $url;
 9855:         if ($rest ne '') {
 9856:             $url .= $rest;
 9857:         }
 9858:     } elsif ($actionurl eq '/adm/coursedocs') {
 9859:         if (ref($args) eq 'HASH') {
 9860:             $url = $args->{'docs_url'};
 9861:             $toplevel = $url;
 9862:             if ($args->{'context'} eq 'paste') {
 9863:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9864:                 ($path) =
 9865:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9866:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9867:                 $fileloc =~ s{^/}{};
 9868:             }
 9869:         }
 9870:     } elsif ($actionurl eq '/adm/dependencies') {
 9871:         if ($env{'request.course.id'} ne '') {
 9872:             if (ref($args) eq 'HASH') {
 9873:                 $url = $args->{'docs_url'};
 9874:                 $title = $args->{'docs_title'};
 9875:                 $toplevel = $url;
 9876:                 unless ($toplevel =~ m{^/}) {
 9877:                     $toplevel = "/$url";
 9878:                 }
 9879:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9880:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
 9881:                     $path = $1;
 9882:                 } else {
 9883:                     ($path) =
 9884:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9885:                 }
 9886:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9887:                 $fileloc =~ s{^/}{};
 9888:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9889:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9890:             }
 9891:         }
 9892:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9893:         $udom = $cdom;
 9894:         $uname = $cnum;
 9895:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
 9896:         $toplevel = $url;
 9897:         $path = $url;
 9898:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
 9899:         $fileloc =~ s{^/}{};
 9900:     }
 9901:     foreach my $file (keys(%{$allfiles})) {
 9902:         my $embed_file;
 9903:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
 9904:             $embed_file = $1;
 9905:         } else {
 9906:             $embed_file = $file;
 9907:         }
 9908:         my ($absolutepath,$cleaned_file);
 9909:         if ($embed_file =~ m{^\w+://}) {
 9910:             $cleaned_file = $embed_file;
 9911:             $newfiles{$cleaned_file} = 1;
 9912:             $mapping{$cleaned_file} = $embed_file;
 9913:         } else {
 9914:             $cleaned_file = &clean_path($embed_file);
 9915:             if ($embed_file =~ m{^/}) {
 9916:                 $absolutepath = $embed_file;
 9917:             }
 9918:             if ($cleaned_file =~ m{/}) {
 9919:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
 9920:                 $path = &check_for_traversal($path,$url,$toplevel);
 9921:                 my $item = $fname;
 9922:                 if ($path ne '') {
 9923:                     $item = $path.'/'.$fname;
 9924:                     $subdependencies{$path}{$fname} = 1;
 9925:                 } else {
 9926:                     $dependencies{$item} = 1;
 9927:                 }
 9928:                 if ($absolutepath) {
 9929:                     $mapping{$item} = $absolutepath;
 9930:                 } else {
 9931:                     $mapping{$item} = $embed_file;
 9932:                 }
 9933:             } else {
 9934:                 $dependencies{$embed_file} = 1;
 9935:                 if ($absolutepath) {
 9936:                     $mapping{$cleaned_file} = $absolutepath;
 9937:                 } else {
 9938:                     $mapping{$cleaned_file} = $embed_file;
 9939:                 }
 9940:             }
 9941:         }
 9942:     }
 9943:     my $dirptr = 16384;
 9944:     foreach my $path (keys(%subdependencies)) {
 9945:         $currsubfile{$path} = {};
 9946:         if (($actionurl eq '/adm/portfolio') ||
 9947:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9948:             my ($sublistref,$listerror) =
 9949:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9950:             if (ref($sublistref) eq 'ARRAY') {
 9951:                 foreach my $line (@{$sublistref}) {
 9952:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9953:                     $currsubfile{$path}{$file_name} = 1;
 9954:                 }
 9955:             }
 9956:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9957:             if (opendir(my $dir,$url.'/'.$path)) {
 9958:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9959:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9960:             }
 9961:         } elsif (($actionurl eq '/adm/dependencies') ||
 9962:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9963:                   ($args->{'context'} eq 'paste')) ||
 9964:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9965:             if ($env{'request.course.id'} ne '') {
 9966:                 my $dir;
 9967:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9968:                     $dir = $fileloc;
 9969:                 } else {
 9970:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9971:                 }
 9972:                 if ($dir ne '') {
 9973:                     my ($sublistref,$listerror) =
 9974:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9975:                     if (ref($sublistref) eq 'ARRAY') {
 9976:                         foreach my $line (@{$sublistref}) {
 9977:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9978:                                 undef,$mtime)=split(/\&/,$line,12);
 9979:                             unless (($testdir&$dirptr) ||
 9980:                                     ($file_name =~ /^\.\.?$/)) {
 9981:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9982:                             }
 9983:                         }
 9984:                     }
 9985:                 }
 9986:             }
 9987:         }
 9988:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9989:             if (exists($currsubfile{$path}{$file})) {
 9990:                 my $item = $path.'/'.$file;
 9991:                 unless ($mapping{$item} eq $item) {
 9992:                     $pathchanges{$item} = 1;
 9993:                 }
 9994:                 $existing{$item} = 1;
 9995:                 $numexisting ++;
 9996:             } else {
 9997:                 $newfiles{$path.'/'.$file} = 1;
 9998:             }
 9999:         }
10000:         if ($actionurl eq '/adm/dependencies') {
10001:             foreach my $path (keys(%currsubfile)) {
10002:                 if (ref($currsubfile{$path}) eq 'HASH') {
10003:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10004:                          unless ($subdependencies{$path}{$file}) {
10005:                              next if (($rem ne '') &&
10006:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10007:                                        (ref($navmap) &&
10008:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10009:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10010:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10011:                              $unused{$path.'/'.$file} = 1; 
10012:                          }
10013:                     }
10014:                 }
10015:             }
10016:         }
10017:     }
10018:     my %currfile;
10019:     if (($actionurl eq '/adm/portfolio') ||
10020:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10021:         my ($dirlistref,$listerror) =
10022:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10023:         if (ref($dirlistref) eq 'ARRAY') {
10024:             foreach my $line (@{$dirlistref}) {
10025:                 my ($file_name,$rest) = split(/\&/,$line,2);
10026:                 $currfile{$file_name} = 1;
10027:             }
10028:         }
10029:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10030:         if (opendir(my $dir,$url)) {
10031:             my @dir_list = grep(!/^\./,readdir($dir));
10032:             map {$currfile{$_} = 1;} @dir_list;
10033:         }
10034:     } elsif (($actionurl eq '/adm/dependencies') ||
10035:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10036:               ($args->{'context'} eq 'paste')) ||
10037:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10038:         if ($env{'request.course.id'} ne '') {
10039:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10040:             if ($dir ne '') {
10041:                 my ($dirlistref,$listerror) =
10042:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10043:                 if (ref($dirlistref) eq 'ARRAY') {
10044:                     foreach my $line (@{$dirlistref}) {
10045:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10046:                             $size,undef,$mtime)=split(/\&/,$line,12);
10047:                         unless (($testdir&$dirptr) ||
10048:                                 ($file_name =~ /^\.\.?$/)) {
10049:                             $currfile{$file_name} = [$size,$mtime];
10050:                         }
10051:                     }
10052:                 }
10053:             }
10054:         }
10055:     }
10056:     foreach my $file (keys(%dependencies)) {
10057:         if (exists($currfile{$file})) {
10058:             unless ($mapping{$file} eq $file) {
10059:                 $pathchanges{$file} = 1;
10060:             }
10061:             $existing{$file} = 1;
10062:             $numexisting ++;
10063:         } else {
10064:             $newfiles{$file} = 1;
10065:         }
10066:     }
10067:     foreach my $file (keys(%currfile)) {
10068:         unless (($file eq $filename) ||
10069:                 ($file eq $filename.'.bak') ||
10070:                 ($dependencies{$file})) {
10071:             if ($actionurl eq '/adm/dependencies') {
10072:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10073:                     next if (($rem ne '') &&
10074:                              (($env{"httpref.$rem".$file} ne '') ||
10075:                               (ref($navmap) &&
10076:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10077:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10078:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10079:                 }
10080:             }
10081:             $unused{$file} = 1;
10082:         }
10083:     }
10084:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10085:         ($args->{'context'} eq 'paste')) {
10086:         $counter = scalar(keys(%existing));
10087:         $numpathchg = scalar(keys(%pathchanges));
10088:         return ($output,$counter,$numpathchg,\%existing);
10089:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10090:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10091:         $counter = scalar(keys(%existing));
10092:         $numpathchg = scalar(keys(%pathchanges));
10093:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10094:     }
10095:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10096:         if ($actionurl eq '/adm/dependencies') {
10097:             next if ($embed_file =~ m{^\w+://});
10098:         }
10099:         $upload_output .= &start_data_table_row().
10100:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10101:                           '<span class="LC_filename">'.$embed_file.'</span>';
10102:         unless ($mapping{$embed_file} eq $embed_file) {
10103:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10104:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10105:         }
10106:         $upload_output .= '</td>';
10107:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10108:             $upload_output.='<td align="right">'.
10109:                             '<span class="LC_info LC_fontsize_medium">'.
10110:                             &mt("URL points to web address").'</span>';
10111:             $numremref++;
10112:         } elsif ($args->{'error_on_invalid_names'}
10113:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10114:             $upload_output.='<td align="right"><span class="LC_warning">'.
10115:                             &mt('Invalid characters').'</span>';
10116:             $numinvalid++;
10117:         } else {
10118:             $upload_output .= '<td>'.
10119:                               &embedded_file_element('upload_embedded',$counter,
10120:                                                      $embed_file,\%mapping,
10121:                                                      $allfiles,$codebase,'upload');
10122:             $counter ++;
10123:             $numnew ++;
10124:         }
10125:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10126:     }
10127:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10128:         if ($actionurl eq '/adm/dependencies') {
10129:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10130:             $modify_output .= &start_data_table_row().
10131:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10132:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10133:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10134:                               '<td>'.$size.'</td>'.
10135:                               '<td>'.$mtime.'</td>'.
10136:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10137:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10138:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10139:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10140:                               &embedded_file_element('upload_embedded',$counter,
10141:                                                      $embed_file,\%mapping,
10142:                                                      $allfiles,$codebase,'modify').
10143:                               '</div></td>'.
10144:                               &end_data_table_row()."\n";
10145:             $counter ++;
10146:         } else {
10147:             $upload_output .= &start_data_table_row().
10148:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10149:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10150:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10151:                               &Apache::loncommon::end_data_table_row()."\n";
10152:         }
10153:     }
10154:     my $delidx = $counter;
10155:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10156:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10157:         $delete_output .= &start_data_table_row().
10158:                           '<td><img src="'.&icon($oldfile).'" />'.
10159:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10160:                           '<td>'.$size.'</td>'.
10161:                           '<td>'.$mtime.'</td>'.
10162:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10163:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10164:                           &embedded_file_element('upload_embedded',$delidx,
10165:                                                  $oldfile,\%mapping,$allfiles,
10166:                                                  $codebase,'delete').'</td>'.
10167:                           &end_data_table_row()."\n"; 
10168:         $numunused ++;
10169:         $delidx ++;
10170:     }
10171:     if ($upload_output) {
10172:         $upload_output = &start_data_table().
10173:                          $upload_output.
10174:                          &end_data_table()."\n";
10175:     }
10176:     if ($modify_output) {
10177:         $modify_output = &start_data_table().
10178:                          &start_data_table_header_row().
10179:                          '<th>'.&mt('File').'</th>'.
10180:                          '<th>'.&mt('Size (KB)').'</th>'.
10181:                          '<th>'.&mt('Modified').'</th>'.
10182:                          '<th>'.&mt('Upload replacement?').'</th>'.
10183:                          &end_data_table_header_row().
10184:                          $modify_output.
10185:                          &end_data_table()."\n";
10186:     }
10187:     if ($delete_output) {
10188:         $delete_output = &start_data_table().
10189:                          &start_data_table_header_row().
10190:                          '<th>'.&mt('File').'</th>'.
10191:                          '<th>'.&mt('Size (KB)').'</th>'.
10192:                          '<th>'.&mt('Modified').'</th>'.
10193:                          '<th>'.&mt('Delete?').'</th>'.
10194:                          &end_data_table_header_row().
10195:                          $delete_output.
10196:                          &end_data_table()."\n";
10197:     }
10198:     my $applies = 0;
10199:     if ($numremref) {
10200:         $applies ++;
10201:     }
10202:     if ($numinvalid) {
10203:         $applies ++;
10204:     }
10205:     if ($numexisting) {
10206:         $applies ++;
10207:     }
10208:     if ($counter || $numunused) {
10209:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10210:                   ' method="post" enctype="multipart/form-data">'."\n".
10211:                   $state.'<h3>'.$heading.'</h3>'; 
10212:         if ($actionurl eq '/adm/dependencies') {
10213:             if ($numnew) {
10214:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10215:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10216:                            $upload_output.'<br />'."\n";
10217:             }
10218:             if ($numexisting) {
10219:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10220:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10221:                            $modify_output.'<br />'."\n";
10222:                            $buttontext = &mt('Save changes');
10223:             }
10224:             if ($numunused) {
10225:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10226:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10227:                            $delete_output.'<br />'."\n";
10228:                            $buttontext = &mt('Save changes');
10229:             }
10230:         } else {
10231:             $output .= $upload_output.'<br />'."\n";
10232:         }
10233:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10234:                    $counter.'" />'."\n";
10235:         if ($actionurl eq '/adm/dependencies') { 
10236:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10237:                        $numnew.'" />'."\n";
10238:         } elsif ($actionurl eq '') {
10239:             $output .=  '<input type="hidden" name="phase" value="three" />';
10240:         }
10241:     } elsif ($applies) {
10242:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10243:         if ($applies > 1) {
10244:             $output .=  
10245:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10246:             if ($numremref) {
10247:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10248:             }
10249:             if ($numinvalid) {
10250:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10251:             }
10252:             if ($numexisting) {
10253:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10254:             }
10255:             $output .= '</ul><br />';
10256:         } elsif ($numremref) {
10257:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10258:         } elsif ($numinvalid) {
10259:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10260:         } elsif ($numexisting) {
10261:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10262:         }
10263:         $output .= $upload_output.'<br />';
10264:     }
10265:     my ($pathchange_output,$chgcount);
10266:     $chgcount = $counter;
10267:     if (keys(%pathchanges) > 0) {
10268:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10269:             if ($counter) {
10270:                 $output .= &embedded_file_element('pathchange',$chgcount,
10271:                                                   $embed_file,\%mapping,
10272:                                                   $allfiles,$codebase,'change');
10273:             } else {
10274:                 $pathchange_output .= 
10275:                     &start_data_table_row().
10276:                     '<td><input type ="checkbox" name="namechange" value="'.
10277:                     $chgcount.'" checked="checked" /></td>'.
10278:                     '<td>'.$mapping{$embed_file}.'</td>'.
10279:                     '<td>'.$embed_file.
10280:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10281:                                            \%mapping,$allfiles,$codebase,'change').
10282:                     '</td>'.&end_data_table_row();
10283:             }
10284:             $numpathchg ++;
10285:             $chgcount ++;
10286:         }
10287:     }
10288:     if (($counter) || ($numunused)) {
10289:         if ($numpathchg) {
10290:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10291:                        $numpathchg.'" />'."\n";
10292:         }
10293:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10294:             ($actionurl eq '/adm/imsimport')) {
10295:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10296:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10297:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10298:         } elsif ($actionurl eq '/adm/dependencies') {
10299:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10300:         }
10301:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10302:     } elsif ($numpathchg) {
10303:         my %pathchange = ();
10304:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10305:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10306:             $output .= '<p>'.&mt('or').'</p>'; 
10307:         }
10308:     }
10309:     return ($output,$counter,$numpathchg);
10310: }
10311: 
10312: =pod
10313: 
10314: =item * clean_path($name)
10315: 
10316: Performs clean-up of directories, subdirectories and filename in an
10317: embedded object, referenced in an HTML file which is being uploaded
10318: to a course or portfolio, where
10319: "Upload embedded images/multimedia files if HTML file" checkbox was
10320: checked.
10321: 
10322: Clean-up is similar to replacements in lonnet::clean_filename()
10323: except each / between sub-directory and next level is preserved.
10324: 
10325: =cut
10326: 
10327: sub clean_path {
10328:     my ($embed_file) = @_;
10329:     $embed_file =~s{^/+}{};
10330:     my @contents;
10331:     if ($embed_file =~ m{/}) {
10332:         @contents = split(/\//,$embed_file);
10333:     } else {
10334:         @contents = ($embed_file);
10335:     }
10336:     my $lastidx = scalar(@contents)-1;
10337:     for (my $i=0; $i<=$lastidx; $i++) {
10338:         $contents[$i]=~s{\\}{/}g;
10339:         $contents[$i]=~s/\s+/\_/g;
10340:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10341:         if ($i == $lastidx) {
10342:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10343:         }
10344:     }
10345:     if ($lastidx > 0) {
10346:         return join('/',@contents);
10347:     } else {
10348:         return $contents[0];
10349:     }
10350: }
10351: 
10352: sub embedded_file_element {
10353:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10354:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10355:                    (ref($codebase) eq 'HASH'));
10356:     my $output;
10357:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10358:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10359:     }
10360:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10361:                &escape($embed_file).'" />';
10362:     unless (($context eq 'upload_embedded') && 
10363:             ($mapping->{$embed_file} eq $embed_file)) {
10364:         $output .='
10365:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10366:     }
10367:     my $attrib;
10368:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10369:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10370:     }
10371:     $output .=
10372:         "\n\t\t".
10373:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10374:         $attrib.'" />';
10375:     if (exists($codebase->{$mapping->{$embed_file}})) {
10376:         $output .=
10377:             "\n\t\t".
10378:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10379:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10380:     }
10381:     return $output;
10382: }
10383: 
10384: sub get_dependency_details {
10385:     my ($currfile,$currsubfile,$embed_file) = @_;
10386:     my ($size,$mtime,$showsize,$showmtime);
10387:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10388:         if ($embed_file =~ m{/}) {
10389:             my ($path,$fname) = split(/\//,$embed_file);
10390:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10391:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10392:             }
10393:         } else {
10394:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10395:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10396:             }
10397:         }
10398:         $showsize = $size/1024.0;
10399:         $showsize = sprintf("%.1f",$showsize);
10400:         if ($mtime > 0) {
10401:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10402:         }
10403:     }
10404:     return ($showsize,$showmtime);
10405: }
10406: 
10407: sub ask_embedded_js {
10408:     return <<"END";
10409: <script type="text/javascript"">
10410: // <![CDATA[
10411: function toggleBrowse(counter) {
10412:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10413:     var fileid = document.getElementById('embedded_item_'+counter);
10414:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10415:     if (chkboxid.checked == true) {
10416:         uploaddivid.style.display='block';
10417:     } else {
10418:         uploaddivid.style.display='none';
10419:         fileid.value = '';
10420:     }
10421: }
10422: // ]]>
10423: </script>
10424: 
10425: END
10426: }
10427: 
10428: sub upload_embedded {
10429:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10430:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10431:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10432:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10433:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10434:         my $orig_uploaded_filename =
10435:             $env{'form.embedded_item_'.$i.'.filename'};
10436:         foreach my $type ('orig','ref','attrib','codebase') {
10437:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10438:                 $env{'form.embedded_'.$type.'_'.$i} =
10439:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10440:             }
10441:         }
10442:         my ($path,$fname) =
10443:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10444:         # no path, whole string is fname
10445:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10446:         $fname = &Apache::lonnet::clean_filename($fname);
10447:         # See if there is anything left
10448:         next if ($fname eq '');
10449: 
10450:         # Check if file already exists as a file or directory.
10451:         my ($state,$msg);
10452:         if ($context eq 'portfolio') {
10453:             my $port_path = $dirpath;
10454:             if ($group ne '') {
10455:                 $port_path = "groups/$group/$port_path";
10456:             }
10457:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10458:                                               $fname,$group,'embedded_item_'.$i,
10459:                                               $dir_root,$port_path,$disk_quota,
10460:                                               $current_disk_usage,$uname,$udom);
10461:             if ($state eq 'will_exceed_quota'
10462:                 || $state eq 'file_locked') {
10463:                 $output .= $msg;
10464:                 next;
10465:             }
10466:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10467:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10468:             if ($state eq 'exists') {
10469:                 $output .= $msg;
10470:                 next;
10471:             }
10472:         }
10473:         # Check if extension is valid
10474:         if (($fname =~ /\.(\w+)$/) &&
10475:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10476:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10477:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10478:             next;
10479:         } elsif (($fname =~ /\.(\w+)$/) &&
10480:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10481:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10482:             next;
10483:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10484:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10485:             next;
10486:         }
10487:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10488:         my $subdir = $path;
10489:         $subdir =~ s{/+$}{};
10490:         if ($context eq 'portfolio') {
10491:             my $result;
10492:             if ($state eq 'existingfile') {
10493:                 $result=
10494:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10495:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10496:             } else {
10497:                 $result=
10498:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10499:                                                     $dirpath.
10500:                                                     $env{'form.currentpath'}.$subdir);
10501:                 if ($result !~ m|^/uploaded/|) {
10502:                     $output .= '<span class="LC_error">'
10503:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10504:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10505:                                .'</span><br />';
10506:                     next;
10507:                 } else {
10508:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10509:                                $path.$fname.'</span>').'<br />';     
10510:                 }
10511:             }
10512:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10513:             my $extendedsubdir = $dirpath.'/'.$subdir;
10514:             $extendedsubdir =~ s{/+$}{};
10515:             my $result =
10516:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10517:             if ($result !~ m|^/uploaded/|) {
10518:                 $output .= '<span class="LC_error">'
10519:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10520:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10521:                            .'</span><br />';
10522:                     next;
10523:             } else {
10524:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10525:                            $path.$fname.'</span>').'<br />';
10526:                 if ($context eq 'syllabus') {
10527:                     &Apache::lonnet::make_public_indefinitely($result);
10528:                 }
10529:             }
10530:         } else {
10531: # Save the file
10532:             my $target = $env{'form.embedded_item_'.$i};
10533:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10534:             my $dest = $fullpath.$fname;
10535:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10536:             my @parts=split(/\//,"$dirpath/$path");
10537:             my $count;
10538:             my $filepath = $dir_root;
10539:             foreach my $subdir (@parts) {
10540:                 $filepath .= "/$subdir";
10541:                 if (!-e $filepath) {
10542:                     mkdir($filepath,0770);
10543:                 }
10544:             }
10545:             my $fh;
10546:             if (!open($fh,'>'.$dest)) {
10547:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10548:                 $output .= '<span class="LC_error">'.
10549:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10550:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10551:                            '</span><br />';
10552:             } else {
10553:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10554:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10555:                     $output .= '<span class="LC_error">'.
10556:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10557:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10558:                               '</span><br />';
10559:                 } else {
10560:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10561:                                $url.'</span>').'<br />';
10562:                     unless ($context eq 'testbank') {
10563:                         $footer .= &mt('View embedded file: [_1]',
10564:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10565:                     }
10566:                 }
10567:                 close($fh);
10568:             }
10569:         }
10570:         if ($env{'form.embedded_ref_'.$i}) {
10571:             $pathchange{$i} = 1;
10572:         }
10573:     }
10574:     if ($output) {
10575:         $output = '<p>'.$output.'</p>';
10576:     }
10577:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10578:     $returnflag = 'ok';
10579:     my $numpathchgs = scalar(keys(%pathchange));
10580:     if ($numpathchgs > 0) {
10581:         if ($context eq 'portfolio') {
10582:             $output .= '<p>'.&mt('or').'</p>';
10583:         } elsif ($context eq 'testbank') {
10584:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10585:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10586:             $returnflag = 'modify_orightml';
10587:         }
10588:     }
10589:     return ($output.$footer,$returnflag,$numpathchgs);
10590: }
10591: 
10592: sub modify_html_form {
10593:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10594:     my $end = 0;
10595:     my $modifyform;
10596:     if ($context eq 'upload_embedded') {
10597:         return unless (ref($pathchange) eq 'HASH');
10598:         if ($env{'form.number_embedded_items'}) {
10599:             $end += $env{'form.number_embedded_items'};
10600:         }
10601:         if ($env{'form.number_pathchange_items'}) {
10602:             $end += $env{'form.number_pathchange_items'};
10603:         }
10604:         if ($end) {
10605:             for (my $i=0; $i<$end; $i++) {
10606:                 if ($i < $env{'form.number_embedded_items'}) {
10607:                     next unless($pathchange->{$i});
10608:                 }
10609:                 $modifyform .=
10610:                     &start_data_table_row().
10611:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10612:                     'checked="checked" /></td>'.
10613:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10614:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10615:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10616:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10617:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10618:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10619:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10620:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10621:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10622:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10623:                     &end_data_table_row();
10624:             }
10625:         }
10626:     } else {
10627:         $modifyform = $pathchgtable;
10628:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10629:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10630:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10631:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10632:         }
10633:     }
10634:     if ($modifyform) {
10635:         if ($actionurl eq '/adm/dependencies') {
10636:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10637:         }
10638:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10639:                '<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".
10640:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10641:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10642:                '</ol></p>'."\n".'<p>'.
10643:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10644:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10645:                &start_data_table()."\n".
10646:                &start_data_table_header_row().
10647:                '<th>'.&mt('Change?').'</th>'.
10648:                '<th>'.&mt('Current reference').'</th>'.
10649:                '<th>'.&mt('Required reference').'</th>'.
10650:                &end_data_table_header_row()."\n".
10651:                $modifyform.
10652:                &end_data_table().'<br />'."\n".$hiddenstate.
10653:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10654:                '</form>'."\n";
10655:     }
10656:     return;
10657: }
10658: 
10659: sub modify_html_refs {
10660:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10661:     my $container;
10662:     if ($context eq 'portfolio') {
10663:         $container = $env{'form.container'};
10664:     } elsif ($context eq 'coursedoc') {
10665:         $container = $env{'form.primaryurl'};
10666:     } elsif ($context eq 'manage_dependencies') {
10667:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10668:         $container = "/$container";
10669:     } elsif ($context eq 'syllabus') {
10670:         $container = $url;
10671:     } else {
10672:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10673:     }
10674:     my (%allfiles,%codebase,$output,$content);
10675:     my @changes = &get_env_multiple('form.namechange');
10676:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
10677:         if (wantarray) {
10678:             return ('',0,0); 
10679:         } else {
10680:             return;
10681:         }
10682:     }
10683:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10684:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10685:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10686:             if (wantarray) {
10687:                 return ('',0,0);
10688:             } else {
10689:                 return;
10690:             }
10691:         } 
10692:         $content = &Apache::lonnet::getfile($container);
10693:         if ($content eq '-1') {
10694:             if (wantarray) {
10695:                 return ('',0,0);
10696:             } else {
10697:                 return;
10698:             }
10699:         }
10700:     } else {
10701:         unless ($container =~ /^\Q$dir_root\E/) {
10702:             if (wantarray) {
10703:                 return ('',0,0);
10704:             } else {
10705:                 return;
10706:             }
10707:         } 
10708:         if (open(my $fh,"<$container")) {
10709:             $content = join('', <$fh>);
10710:             close($fh);
10711:         } else {
10712:             if (wantarray) {
10713:                 return ('',0,0);
10714:             } else {
10715:                 return;
10716:             }
10717:         }
10718:     }
10719:     my ($count,$codebasecount) = (0,0);
10720:     my $mm = new File::MMagic;
10721:     my $mime_type = $mm->checktype_contents($content);
10722:     if ($mime_type eq 'text/html') {
10723:         my $parse_result = 
10724:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10725:                                                     \%codebase,\$content);
10726:         if ($parse_result eq 'ok') {
10727:             foreach my $i (@changes) {
10728:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10729:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10730:                 if ($allfiles{$ref}) {
10731:                     my $newname =  $orig;
10732:                     my ($attrib_regexp,$codebase);
10733:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10734:                     if ($attrib_regexp =~ /:/) {
10735:                         $attrib_regexp =~ s/\:/|/g;
10736:                     }
10737:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10738:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10739:                         $count += $numchg;
10740:                         $allfiles{$newname} = $allfiles{$ref};
10741:                         delete($allfiles{$ref});
10742:                     }
10743:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10744:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10745:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10746:                         $codebasecount ++;
10747:                     }
10748:                 }
10749:             }
10750:             my $skiprewrites;
10751:             if ($count || $codebasecount) {
10752:                 my $saveresult;
10753:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10754:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10755:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10756:                     if ($url eq $container) {
10757:                         my ($fname) = ($container =~ m{/([^/]+)$});
10758:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10759:                                             $count,'<span class="LC_filename">'.
10760:                                             $fname.'</span>').'</p>';
10761:                     } else {
10762:                          $output = '<p class="LC_error">'.
10763:                                    &mt('Error: update failed for: [_1].',
10764:                                    '<span class="LC_filename">'.
10765:                                    $container.'</span>').'</p>';
10766:                     }
10767:                     if ($context eq 'syllabus') {
10768:                         unless ($saveresult eq 'ok') {
10769:                             $skiprewrites = 1;
10770:                         }
10771:                     }
10772:                 } else {
10773:                     if (open(my $fh,">$container")) {
10774:                         print $fh $content;
10775:                         close($fh);
10776:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10777:                                   $count,'<span class="LC_filename">'.
10778:                                   $container.'</span>').'</p>';
10779:                     } else {
10780:                          $output = '<p class="LC_error">'.
10781:                                    &mt('Error: could not update [_1].',
10782:                                    '<span class="LC_filename">'.
10783:                                    $container.'</span>').'</p>';
10784:                     }
10785:                 }
10786:             }
10787:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10788:                 my ($actionurl,$state);
10789:                 $actionurl = "/public/$udom/$uname/syllabus";
10790:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10791:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10792:                                               \%codebase,
10793:                                               {'context' => 'rewrites',
10794:                                                'ignore_remote_references' => 1,});
10795:                 if (ref($mapping) eq 'HASH') {
10796:                     my $rewrites = 0;
10797:                     foreach my $key (keys(%{$mapping})) {
10798:                         next if ($key =~ m{^https?://});
10799:                         my $ref = $mapping->{$key};
10800:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10801:                         my $attrib;
10802:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10803:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10804:                         }
10805:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10806:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10807:                             $rewrites += $numchg;
10808:                         }
10809:                     }
10810:                     if ($rewrites) {
10811:                         my $saveresult;
10812:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10813:                         if ($url eq $container) {
10814:                             my ($fname) = ($container =~ m{/([^/]+)$});
10815:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10816:                                             $count,'<span class="LC_filename">'.
10817:                                             $fname.'</span>').'</p>';
10818:                         } else {
10819:                             $output .= '<p class="LC_error">'.
10820:                                        &mt('Error: could not update links in [_1].',
10821:                                        '<span class="LC_filename">'.
10822:                                        $container.'</span>').'</p>';
10823: 
10824:                         }
10825:                     }
10826:                 }
10827:             }
10828:         } else {
10829:             &logthis('Failed to parse '.$container.
10830:                      ' to modify references: '.$parse_result);
10831:         }
10832:     }
10833:     if (wantarray) {
10834:         return ($output,$count,$codebasecount);
10835:     } else {
10836:         return $output;
10837:     }
10838: }
10839: 
10840: sub check_for_existing {
10841:     my ($path,$fname,$element) = @_;
10842:     my ($state,$msg);
10843:     if (-d $path.'/'.$fname) {
10844:         $state = 'exists';
10845:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10846:     } elsif (-e $path.'/'.$fname) {
10847:         $state = 'exists';
10848:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10849:     }
10850:     if ($state eq 'exists') {
10851:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10852:     }
10853:     return ($state,$msg);
10854: }
10855: 
10856: sub check_for_upload {
10857:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10858:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10859:     my $filesize = length($env{'form.'.$element});
10860:     if (!$filesize) {
10861:         my $msg = '<span class="LC_error">'.
10862:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10863:                       '<span class="LC_filename">'.$fname.'</span>',
10864:                       $filesize).'<br />'.
10865:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10866:                   '</span>';
10867:         return ('zero_bytes',$msg);
10868:     }
10869:     $filesize =  $filesize/1000; #express in k (1024?)
10870:     my $getpropath = 1;
10871:     my ($dirlistref,$listerror) =
10872:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10873:     my $found_file = 0;
10874:     my $locked_file = 0;
10875:     my @lockers;
10876:     my $navmap;
10877:     if ($env{'request.course.id'}) {
10878:         $navmap = Apache::lonnavmaps::navmap->new();
10879:     }
10880:     if (ref($dirlistref) eq 'ARRAY') {
10881:         foreach my $line (@{$dirlistref}) {
10882:             my ($file_name,$rest)=split(/\&/,$line,2);
10883:             if ($file_name eq $fname){
10884:                 $file_name = $path.$file_name;
10885:                 if ($group ne '') {
10886:                     $file_name = $group.$file_name;
10887:                 }
10888:                 $found_file = 1;
10889:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10890:                     foreach my $lock (@lockers) {
10891:                         if (ref($lock) eq 'ARRAY') {
10892:                             my ($symb,$crsid) = @{$lock};
10893:                             if ($crsid eq $env{'request.course.id'}) {
10894:                                 if (ref($navmap)) {
10895:                                     my $res = $navmap->getBySymb($symb);
10896:                                     foreach my $part (@{$res->parts()}) { 
10897:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10898:                                         unless (($slot_status == $res->RESERVED) ||
10899:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10900:                                             $locked_file = 1;
10901:                                         }
10902:                                     }
10903:                                 } else {
10904:                                     $locked_file = 1;
10905:                                 }
10906:                             } else {
10907:                                 $locked_file = 1;
10908:                             }
10909:                         }
10910:                    }
10911:                 } else {
10912:                     my @info = split(/\&/,$rest);
10913:                     my $currsize = $info[6]/1000;
10914:                     if ($currsize < $filesize) {
10915:                         my $extra = $filesize - $currsize;
10916:                         if (($current_disk_usage + $extra) > $disk_quota) {
10917:                             my $msg = '<span class="LC_error">'.
10918:                                       &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.',
10919:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10920:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10921:                                                    $disk_quota,$current_disk_usage);
10922:                             return ('will_exceed_quota',$msg);
10923:                         }
10924:                     }
10925:                 }
10926:             }
10927:         }
10928:     }
10929:     if (($current_disk_usage + $filesize) > $disk_quota){
10930:         my $msg = '<span class="LC_error">'.
10931:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10932:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10933:         return ('will_exceed_quota',$msg);
10934:     } elsif ($found_file) {
10935:         if ($locked_file) {
10936:             my $msg = '<span class="LC_error">';
10937:             $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>');
10938:             $msg .= '</span><br />';
10939:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10940:             return ('file_locked',$msg);
10941:         } else {
10942:             my $msg = '<span class="LC_error">';
10943:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10944:             $msg .= '</span>';
10945:             return ('existingfile',$msg);
10946:         }
10947:     }
10948: }
10949: 
10950: sub check_for_traversal {
10951:     my ($path,$url,$toplevel) = @_;
10952:     my @parts=split(/\//,$path);
10953:     my $cleanpath;
10954:     my $fullpath = $url;
10955:     for (my $i=0;$i<@parts;$i++) {
10956:         next if ($parts[$i] eq '.');
10957:         if ($parts[$i] eq '..') {
10958:             $fullpath =~ s{([^/]+/)$}{};
10959:         } else {
10960:             $fullpath .= $parts[$i].'/';
10961:         }
10962:     }
10963:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10964:         $cleanpath = $1;
10965:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10966:         my $curr_toprel = $1;
10967:         my @parts = split(/\//,$curr_toprel);
10968:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10969:         my @urlparts = split(/\//,$url_toprel);
10970:         my $doubledots;
10971:         my $startdiff = -1;
10972:         for (my $i=0; $i<@urlparts; $i++) {
10973:             if ($startdiff == -1) {
10974:                 unless ($urlparts[$i] eq $parts[$i]) {
10975:                     $startdiff = $i;
10976:                     $doubledots .= '../';
10977:                 }
10978:             } else {
10979:                 $doubledots .= '../';
10980:             }
10981:         }
10982:         if ($startdiff > -1) {
10983:             $cleanpath = $doubledots;
10984:             for (my $i=$startdiff; $i<@parts; $i++) {
10985:                 $cleanpath .= $parts[$i].'/';
10986:             }
10987:         }
10988:     }
10989:     $cleanpath =~ s{(/)$}{};
10990:     return $cleanpath;
10991: }
10992: 
10993: sub is_archive_file {
10994:     my ($mimetype) = @_;
10995:     if (($mimetype eq 'application/octet-stream') ||
10996:         ($mimetype eq 'application/x-stuffit') ||
10997:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10998:         return 1;
10999:     }
11000:     return;
11001: }
11002: 
11003: sub decompress_form {
11004:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11005:     my %lt = &Apache::lonlocal::texthash (
11006:         this => 'This file is an archive file.',
11007:         camt => 'This file is a Camtasia archive file.',
11008:         itsc => 'Its contents are as follows:',
11009:         youm => 'You may wish to extract its contents.',
11010:         extr => 'Extract contents',
11011:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11012:         proa => 'Process automatically?',
11013:         yes  => 'Yes',
11014:         no   => 'No',
11015:         fold => 'Title for folder containing movie',
11016:         movi => 'Title for page containing embedded movie', 
11017:     );
11018:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11019:     my ($is_camtasia,$topdir,%toplevel,@paths);
11020:     my $info = &list_archive_contents($fileloc,\@paths);
11021:     if (@paths) {
11022:         foreach my $path (@paths) {
11023:             $path =~ s{^/}{};
11024:             if ($path =~ m{^([^/]+)/$}) {
11025:                 $topdir = $1;
11026:             }
11027:             if ($path =~ m{^([^/]+)/}) {
11028:                 $toplevel{$1} = $path;
11029:             } else {
11030:                 $toplevel{$path} = $path;
11031:             }
11032:         }
11033:     }
11034:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11035:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11036:                         "$topdir/media/",
11037:                         "$topdir/media/$topdir.mp4",
11038:                         "$topdir/media/FirstFrame.png",
11039:                         "$topdir/media/player.swf",
11040:                         "$topdir/media/swfobject.js",
11041:                         "$topdir/media/expressInstall.swf");
11042:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
11043:                          "$topdir/$topdir.mp4",
11044:                          "$topdir/$topdir\_config.xml",
11045:                          "$topdir/$topdir\_controller.swf",
11046:                          "$topdir/$topdir\_embed.css",
11047:                          "$topdir/$topdir\_First_Frame.png",
11048:                          "$topdir/$topdir\_player.html",
11049:                          "$topdir/$topdir\_Thumbnails.png",
11050:                          "$topdir/playerProductInstall.swf",
11051:                          "$topdir/scripts/",
11052:                          "$topdir/scripts/config_xml.js",
11053:                          "$topdir/scripts/handlebars.js",
11054:                          "$topdir/scripts/jquery-1.7.1.min.js",
11055:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11056:                          "$topdir/scripts/modernizr.js",
11057:                          "$topdir/scripts/player-min.js",
11058:                          "$topdir/scripts/swfobject.js",
11059:                          "$topdir/skins/",
11060:                          "$topdir/skins/configuration_express.xml",
11061:                          "$topdir/skins/express_show/",
11062:                          "$topdir/skins/express_show/player-min.css",
11063:                          "$topdir/skins/express_show/spritesheet.png");
11064:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11065:         if (@diffs == 0) {
11066:             $is_camtasia = 6;
11067:         } else {
11068:             @diffs = &compare_arrays(\@paths,\@camtasia8);
11069:             if (@diffs == 0) {
11070:                 $is_camtasia = 8;
11071:             }
11072:         }
11073:     }
11074:     my $output;
11075:     if ($is_camtasia) {
11076:         $output = <<"ENDCAM";
11077: <script type="text/javascript" language="Javascript">
11078: // <![CDATA[
11079: 
11080: function camtasiaToggle() {
11081:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11082:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11083:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11084:                 document.getElementById('camtasia_titles').style.display='block';
11085:             } else {
11086:                 document.getElementById('camtasia_titles').style.display='none';
11087:             }
11088:         }
11089:     }
11090:     return;
11091: }
11092: 
11093: // ]]>
11094: </script>
11095: <p>$lt{'camt'}</p>
11096: ENDCAM
11097:     } else {
11098:         $output = '<p>'.$lt{'this'};
11099:         if ($info eq '') {
11100:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11101:         } else {
11102:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11103:                        '<div><pre>'.$info.'</pre></div>';
11104:         }
11105:     }
11106:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11107:     my $duplicates;
11108:     my $num = 0;
11109:     if (ref($dirlist) eq 'ARRAY') {
11110:         foreach my $item (@{$dirlist}) {
11111:             if (ref($item) eq 'ARRAY') {
11112:                 if (exists($toplevel{$item->[0]})) {
11113:                     $duplicates .= 
11114:                         &start_data_table_row().
11115:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11116:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11117:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11118:                         'value="1" />'.&mt('Yes').'</label>'.
11119:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11120:                         '<td>'.$item->[0].'</td>';
11121:                     if ($item->[2]) {
11122:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11123:                     } else {
11124:                         $duplicates .= '<td>'.&mt('File').'</td>';
11125:                     }
11126:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11127:                                    '<td>'.
11128:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11129:                                    '</td>'.
11130:                                    &end_data_table_row();
11131:                     $num ++;
11132:                 }
11133:             }
11134:         }
11135:     }
11136:     my $itemcount;
11137:     if (@paths > 0) {
11138:         $itemcount = scalar(@paths);
11139:     } else {
11140:         $itemcount = 1;
11141:     }
11142:     if ($is_camtasia) {
11143:         $output .= $lt{'auto'}.'<br />'.
11144:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11145:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11146:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11147:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11148:                    $lt{'no'}.'</label></span><br />'.
11149:                    '<div id="camtasia_titles" style="display:block">'.
11150:                    &Apache::lonhtmlcommon::start_pick_box().
11151:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11152:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11153:                    &Apache::lonhtmlcommon::row_closure().
11154:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11155:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11156:                    &Apache::lonhtmlcommon::row_closure(1).
11157:                    &Apache::lonhtmlcommon::end_pick_box().
11158:                    '</div>';
11159:     }
11160:     $output .= 
11161:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11162:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11163:         "\n";
11164:     if ($duplicates ne '') {
11165:         $output .= '<p><span class="LC_warning">'.
11166:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11167:                    &start_data_table().
11168:                    &start_data_table_header_row().
11169:                    '<th>'.&mt('Overwrite?').'</th>'.
11170:                    '<th>'.&mt('Name').'</th>'.
11171:                    '<th>'.&mt('Type').'</th>'.
11172:                    '<th>'.&mt('Size').'</th>'.
11173:                    '<th>'.&mt('Last modified').'</th>'.
11174:                    &end_data_table_header_row().
11175:                    $duplicates.
11176:                    &end_data_table().
11177:                    '</p>';
11178:     }
11179:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11180:     if (ref($hiddenelements) eq 'HASH') {
11181:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11182:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11183:         }
11184:     }
11185:     $output .= <<"END";
11186: <br />
11187: <input type="submit" name="decompress" value="$lt{'extr'}" />
11188: </form>
11189: $noextract
11190: END
11191:     return $output;
11192: }
11193: 
11194: sub decompression_utility {
11195:     my ($program) = @_;
11196:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11197:     my $location;
11198:     if (grep(/^\Q$program\E$/,@utilities)) { 
11199:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11200:                          '/usr/sbin/') {
11201:             if (-x $dir.$program) {
11202:                 $location = $dir.$program;
11203:                 last;
11204:             }
11205:         }
11206:     }
11207:     return $location;
11208: }
11209: 
11210: sub list_archive_contents {
11211:     my ($file,$pathsref) = @_;
11212:     my (@cmd,$output);
11213:     my $needsregexp;
11214:     if ($file =~ /\.zip$/) {
11215:         @cmd = (&decompression_utility('unzip'),"-l");
11216:         $needsregexp = 1;
11217:     } elsif (($file =~ m/\.tar\.gz$/) ||
11218:              ($file =~ /\.tgz$/)) {
11219:         @cmd = (&decompression_utility('tar'),"-ztf");
11220:     } elsif ($file =~ /\.tar\.bz2$/) {
11221:         @cmd = (&decompression_utility('tar'),"-jtf");
11222:     } elsif ($file =~ m|\.tar$|) {
11223:         @cmd = (&decompression_utility('tar'),"-tf");
11224:     }
11225:     if (@cmd) {
11226:         undef($!);
11227:         undef($@);
11228:         if (open(my $fh,"-|", @cmd, $file)) {
11229:             while (my $line = <$fh>) {
11230:                 $output .= $line;
11231:                 chomp($line);
11232:                 my $item;
11233:                 if ($needsregexp) {
11234:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11235:                 } else {
11236:                     $item = $line;
11237:                 }
11238:                 if ($item ne '') {
11239:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11240:                         push(@{$pathsref},$item);
11241:                     } 
11242:                 }
11243:             }
11244:             close($fh);
11245:         }
11246:     }
11247:     return $output;
11248: }
11249: 
11250: sub decompress_uploaded_file {
11251:     my ($file,$dir) = @_;
11252:     &Apache::lonnet::appenv({'cgi.file' => $file});
11253:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11254:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11255:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11256:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11257:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11258:     my $decompressed = $env{'cgi.decompressed'};
11259:     &Apache::lonnet::delenv('cgi.file');
11260:     &Apache::lonnet::delenv('cgi.dir');
11261:     &Apache::lonnet::delenv('cgi.decompressed');
11262:     return ($decompressed,$result);
11263: }
11264: 
11265: sub process_decompression {
11266:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11267:     my ($dir,$error,$warning,$output);
11268:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11269:         $error = &mt('Filename not a supported archive file type.').
11270:                  '<br />'.&mt('Filename should end with one of: [_1].',
11271:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11272:     } else {
11273:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11274:         if ($docuhome eq 'no_host') {
11275:             $error = &mt('Could not determine home server for course.');
11276:         } else {
11277:             my @ids=&Apache::lonnet::current_machine_ids();
11278:             my $currdir = "$dir_root/$destination";
11279:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11280:                 $dir = &LONCAPA::propath($docudom,$docuname).
11281:                        "$dir_root/$destination";
11282:             } else {
11283:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11284:                        "$dir_root/$docudom/$docuname/$destination";
11285:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11286:                     $error = &mt('Archive file not found.');
11287:                 }
11288:             }
11289:             my (@to_overwrite,@to_skip);
11290:             if ($env{'form.archive_overwrite_total'} > 0) {
11291:                 my $total = $env{'form.archive_overwrite_total'};
11292:                 for (my $i=0; $i<$total; $i++) {
11293:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11294:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11295:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11296:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11297:                     }
11298:                 }
11299:             }
11300:             my $numskip = scalar(@to_skip);
11301:             if (($numskip > 0) && 
11302:                 ($numskip == $env{'form.archive_itemcount'})) {
11303:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11304:             } elsif ($dir eq '') {
11305:                 $error = &mt('Directory containing archive file unavailable.');
11306:             } elsif (!$error) {
11307:                 my ($decompressed,$display);
11308:                 if ($numskip > 0) {
11309:                     my $tempdir = time.'_'.$$.int(rand(10000));
11310:                     mkdir("$dir/$tempdir",0755);
11311:                     system("mv $dir/$file $dir/$tempdir/$file");
11312:                     ($decompressed,$display) = 
11313:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11314:                     foreach my $item (@to_skip) {
11315:                         if (($item ne '') && ($item !~ /\.\./)) {
11316:                             if (-f "$dir/$tempdir/$item") { 
11317:                                 unlink("$dir/$tempdir/$item");
11318:                             } elsif (-d "$dir/$tempdir/$item") {
11319:                                 system("rm -rf $dir/$tempdir/$item");
11320:                             }
11321:                         }
11322:                     }
11323:                     system("mv $dir/$tempdir/* $dir");
11324:                     rmdir("$dir/$tempdir");   
11325:                 } else {
11326:                     ($decompressed,$display) = 
11327:                         &decompress_uploaded_file($file,$dir);
11328:                 }
11329:                 if ($decompressed eq 'ok') {
11330:                     $output = '<p class="LC_info">'.
11331:                               &mt('Files extracted successfully from archive.').
11332:                               '</p>'."\n";
11333:                     my ($warning,$result,@contents);
11334:                     my ($newdirlistref,$newlisterror) =
11335:                         &Apache::lonnet::dirlist($currdir,$docudom,
11336:                                                  $docuname,1);
11337:                     my (%is_dir,%changes,@newitems);
11338:                     my $dirptr = 16384;
11339:                     if (ref($newdirlistref) eq 'ARRAY') {
11340:                         foreach my $dir_line (@{$newdirlistref}) {
11341:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11342:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11343:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11344:                                 push(@newitems,$item);
11345:                                 if ($dirptr&$testdir) {
11346:                                     $is_dir{$item} = 1;
11347:                                 }
11348:                                 $changes{$item} = 1;
11349:                             }
11350:                         }
11351:                     }
11352:                     if (keys(%changes) > 0) {
11353:                         foreach my $item (sort(@newitems)) {
11354:                             if ($changes{$item}) {
11355:                                 push(@contents,$item);
11356:                             }
11357:                         }
11358:                     }
11359:                     if (@contents > 0) {
11360:                         my $wantform;
11361:                         unless ($env{'form.autoextract_camtasia'}) {
11362:                             $wantform = 1;
11363:                         }
11364:                         my (%children,%parent,%dirorder,%titles);
11365:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11366:                                                                 $currdir,\%is_dir,
11367:                                                                 \%children,\%parent,
11368:                                                                 \@contents,\%dirorder,
11369:                                                                 \%titles,$wantform);
11370:                         if ($datatable ne '') {
11371:                             $output .= &archive_options_form('decompressed',$datatable,
11372:                                                              $count,$hiddenelem);
11373:                             my $startcount = 6;
11374:                             $output .= &archive_javascript($startcount,$count,
11375:                                                            \%titles,\%children);
11376:                         }
11377:                         if ($env{'form.autoextract_camtasia'}) {
11378:                             my $version = $env{'form.autoextract_camtasia'};
11379:                             my %displayed;
11380:                             my $total = 1;
11381:                             $env{'form.archive_directory'} = [];
11382:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11383:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11384:                                 $path =~ s{/$}{};
11385:                                 my $item;
11386:                                 if ($path ne '') {
11387:                                     $item = "$path/$titles{$i}";
11388:                                 } else {
11389:                                     $item = $titles{$i};
11390:                                 }
11391:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11392:                                 if ($item eq $contents[0]) {
11393:                                     push(@{$env{'form.archive_directory'}},$i);
11394:                                     $env{'form.archive_'.$i} = 'display';
11395:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11396:                                     $displayed{'folder'} = $i;
11397:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11398:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11399:                                     $env{'form.archive_'.$i} = 'display';
11400:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11401:                                     $displayed{'web'} = $i;
11402:                                 } else {
11403:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11404:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11405:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11406:                                         push(@{$env{'form.archive_directory'}},$i);
11407:                                     }
11408:                                     $env{'form.archive_'.$i} = 'dependency';
11409:                                 }
11410:                                 $total ++;
11411:                             }
11412:                             for (my $i=1; $i<$total; $i++) {
11413:                                 next if ($i == $displayed{'web'});
11414:                                 next if ($i == $displayed{'folder'});
11415:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11416:                             }
11417:                             $env{'form.phase'} = 'decompress_cleanup';
11418:                             $env{'form.archivedelete'} = 1;
11419:                             $env{'form.archive_count'} = $total-1;
11420:                             $output .=
11421:                                 &process_extracted_files('coursedocs',$docudom,
11422:                                                          $docuname,$destination,
11423:                                                          $dir_root,$hiddenelem);
11424:                         }
11425:                     } else {
11426:                         $warning = &mt('No new items extracted from archive file.');
11427:                     }
11428:                 } else {
11429:                     $output = $display;
11430:                     $error = &mt('An error occurred during extraction from the archive file.');
11431:                 }
11432:             }
11433:         }
11434:     }
11435:     if ($error) {
11436:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11437:                    $error.'</p>'."\n";
11438:     }
11439:     if ($warning) {
11440:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11441:     }
11442:     return $output;
11443: }
11444: 
11445: sub get_extracted {
11446:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11447:         $titles,$wantform) = @_;
11448:     my $count = 0;
11449:     my $depth = 0;
11450:     my $datatable;
11451:     my @hierarchy;
11452:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11453:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11454:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11455:     foreach my $item (@{$contents}) {
11456:         $count ++;
11457:         @{$dirorder->{$count}} = @hierarchy;
11458:         $titles->{$count} = $item;
11459:         &archive_hierarchy($depth,$count,$parent,$children);
11460:         if ($wantform) {
11461:             $datatable .= &archive_row($is_dir->{$item},$item,
11462:                                        $currdir,$depth,$count);
11463:         }
11464:         if ($is_dir->{$item}) {
11465:             $depth ++;
11466:             push(@hierarchy,$count);
11467:             $parent->{$depth} = $count;
11468:             $datatable .=
11469:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11470:                                            \$depth,\$count,\@hierarchy,$dirorder,
11471:                                            $children,$parent,$titles,$wantform);
11472:             $depth --;
11473:             pop(@hierarchy);
11474:         }
11475:     }
11476:     return ($count,$datatable);
11477: }
11478: 
11479: sub recurse_extracted_archive {
11480:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11481:         $children,$parent,$titles,$wantform) = @_;
11482:     my $result='';
11483:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11484:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11485:             (ref($dirorder) eq 'HASH')) {
11486:         return $result;
11487:     }
11488:     my $dirptr = 16384;
11489:     my ($newdirlistref,$newlisterror) =
11490:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11491:     if (ref($newdirlistref) eq 'ARRAY') {
11492:         foreach my $dir_line (@{$newdirlistref}) {
11493:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11494:             unless ($item =~ /^\.+$/) {
11495:                 $$count ++;
11496:                 @{$dirorder->{$$count}} = @{$hierarchy};
11497:                 $titles->{$$count} = $item;
11498:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11499: 
11500:                 my $is_dir;
11501:                 if ($dirptr&$testdir) {
11502:                     $is_dir = 1;
11503:                 }
11504:                 if ($wantform) {
11505:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11506:                 }
11507:                 if ($is_dir) {
11508:                     $$depth ++;
11509:                     push(@{$hierarchy},$$count);
11510:                     $parent->{$$depth} = $$count;
11511:                     $result .=
11512:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11513:                                                    $docuname,$depth,$count,
11514:                                                    $hierarchy,$dirorder,$children,
11515:                                                    $parent,$titles,$wantform);
11516:                     $$depth --;
11517:                     pop(@{$hierarchy});
11518:                 }
11519:             }
11520:         }
11521:     }
11522:     return $result;
11523: }
11524: 
11525: sub archive_hierarchy {
11526:     my ($depth,$count,$parent,$children) =@_;
11527:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11528:         if (exists($parent->{$depth})) {
11529:              $children->{$parent->{$depth}} .= $count.':';
11530:         }
11531:     }
11532:     return;
11533: }
11534: 
11535: sub archive_row {
11536:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11537:     my ($name) = ($item =~ m{([^/]+)$});
11538:     my %choices = &Apache::lonlocal::texthash (
11539:                                        'display'    => 'Add as file',
11540:                                        'dependency' => 'Include as dependency',
11541:                                        'discard'    => 'Discard',
11542:                                       );
11543:     if ($is_dir) {
11544:         $choices{'display'} = &mt('Add as folder'); 
11545:     }
11546:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11547:     my $offset = 0;
11548:     foreach my $action ('display','dependency','discard') {
11549:         $offset ++;
11550:         if ($action ne 'display') {
11551:             $offset ++;
11552:         }  
11553:         $output .= '<td><span class="LC_nobreak">'.
11554:                    '<label><input type="radio" name="archive_'.$count.
11555:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11556:         my $text = $choices{$action};
11557:         if ($is_dir) {
11558:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11559:             if ($action eq 'display') {
11560:                 $text = &mt('Add as folder');
11561:             }
11562:         } else {
11563:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11564: 
11565:         }
11566:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11567:         if ($action eq 'dependency') {
11568:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11569:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11570:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11571:                        '<option value=""></option>'."\n".
11572:                        '</select>'."\n".
11573:                        '</div>';
11574:         } elsif ($action eq 'display') {
11575:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11576:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11577:                        '</div>';
11578:         }
11579:         $output .= '</td>';
11580:     }
11581:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11582:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11583:     for (my $i=0; $i<$depth; $i++) {
11584:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11585:     }
11586:     if ($is_dir) {
11587:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11588:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11589:     } else {
11590:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11591:     }
11592:     $output .= '&nbsp;'.$name.'</td>'."\n".
11593:                &end_data_table_row();
11594:     return $output;
11595: }
11596: 
11597: sub archive_options_form {
11598:     my ($form,$display,$count,$hiddenelem) = @_;
11599:     my %lt = &Apache::lonlocal::texthash(
11600:                perm => 'Permanently remove archive file?',
11601:                hows => 'How should each extracted item be incorporated in the course?',
11602:                cont => 'Content actions for all',
11603:                addf => 'Add as folder/file',
11604:                incd => 'Include as dependency for a displayed file',
11605:                disc => 'Discard',
11606:                no   => 'No',
11607:                yes  => 'Yes',
11608:                save => 'Save',
11609:     );
11610:     my $output = <<"END";
11611: <form name="$form" method="post" action="">
11612: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11613: <label>
11614:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11615: </label>
11616: &nbsp;
11617: <label>
11618:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11619: </span>
11620: </p>
11621: <input type="hidden" name="phase" value="decompress_cleanup" />
11622: <br />$lt{'hows'}
11623: <div class="LC_columnSection">
11624:   <fieldset>
11625:     <legend>$lt{'cont'}</legend>
11626:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11627:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11628:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11629:   </fieldset>
11630: </div>
11631: END
11632:     return $output.
11633:            &start_data_table()."\n".
11634:            $display."\n".
11635:            &end_data_table()."\n".
11636:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11637:            $hiddenelem.
11638:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11639:            '</form>';
11640: }
11641: 
11642: sub archive_javascript {
11643:     my ($startcount,$numitems,$titles,$children) = @_;
11644:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11645:     my $maintitle = $env{'form.comment'};
11646:     my $scripttag = <<START;
11647: <script type="text/javascript">
11648: // <![CDATA[
11649: 
11650: function checkAll(form,prefix) {
11651:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11652:     for (var i=0; i < form.elements.length; i++) {
11653:         var id = form.elements[i].id;
11654:         if ((id != '') && (id != undefined)) {
11655:             if (idstr.test(id)) {
11656:                 if (form.elements[i].type == 'radio') {
11657:                     form.elements[i].checked = true;
11658:                     var nostart = i-$startcount;
11659:                     var offset = nostart%7;
11660:                     var count = (nostart-offset)/7;    
11661:                     dependencyCheck(form,count,offset);
11662:                 }
11663:             }
11664:         }
11665:     }
11666: }
11667: 
11668: function propagateCheck(form,count) {
11669:     if (count > 0) {
11670:         var startelement = $startcount + ((count-1) * 7);
11671:         for (var j=1; j<6; j++) {
11672:             if ((j != 2) && (j != 4)) {
11673:                 var item = startelement + j; 
11674:                 if (form.elements[item].type == 'radio') {
11675:                     if (form.elements[item].checked) {
11676:                         containerCheck(form,count,j);
11677:                         break;
11678:                     }
11679:                 }
11680:             }
11681:         }
11682:     }
11683: }
11684: 
11685: numitems = $numitems
11686: var titles = new Array(numitems);
11687: var parents = new Array(numitems);
11688: for (var i=0; i<numitems; i++) {
11689:     parents[i] = new Array;
11690: }
11691: var maintitle = '$maintitle';
11692: 
11693: START
11694: 
11695:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11696:         my @contents = split(/:/,$children->{$container});
11697:         for (my $i=0; $i<@contents; $i ++) {
11698:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11699:         }
11700:     }
11701: 
11702:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11703:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11704:     }
11705: 
11706:     $scripttag .= <<END;
11707: 
11708: function containerCheck(form,count,offset) {
11709:     if (count > 0) {
11710:         dependencyCheck(form,count,offset);
11711:         var item = (offset+$startcount)+7*(count-1);
11712:         form.elements[item].checked = true;
11713:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11714:             if (parents[count].length > 0) {
11715:                 for (var j=0; j<parents[count].length; j++) {
11716:                     containerCheck(form,parents[count][j],offset);
11717:                 }
11718:             }
11719:         }
11720:     }
11721: }
11722: 
11723: function dependencyCheck(form,count,offset) {
11724:     if (count > 0) {
11725:         var chosen = (offset+$startcount)+7*(count-1);
11726:         var depitem = $startcount + ((count-1) * 7) + 4;
11727:         var currtype = form.elements[depitem].type;
11728:         if (form.elements[chosen].value == 'dependency') {
11729:             document.getElementById('arc_depon_'+count).style.display='block'; 
11730:             form.elements[depitem].options.length = 0;
11731:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11732:             for (var i=1; i<=numitems; i++) {
11733:                 if (i == count) {
11734:                     continue;
11735:                 }
11736:                 var startelement = $startcount + (i-1) * 7;
11737:                 for (var j=1; j<6; j++) {
11738:                     if ((j != 2) && (j!= 4)) {
11739:                         var item = startelement + j;
11740:                         if (form.elements[item].type == 'radio') {
11741:                             if (form.elements[item].checked) {
11742:                                 if (form.elements[item].value == 'display') {
11743:                                     var n = form.elements[depitem].options.length;
11744:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11745:                                 }
11746:                             }
11747:                         }
11748:                     }
11749:                 }
11750:             }
11751:         } else {
11752:             document.getElementById('arc_depon_'+count).style.display='none';
11753:             form.elements[depitem].options.length = 0;
11754:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11755:         }
11756:         titleCheck(form,count,offset);
11757:     }
11758: }
11759: 
11760: function propagateSelect(form,count,offset) {
11761:     if (count > 0) {
11762:         var item = (1+offset+$startcount)+7*(count-1);
11763:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11764:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11765:             if (parents[count].length > 0) {
11766:                 for (var j=0; j<parents[count].length; j++) {
11767:                     containerSelect(form,parents[count][j],offset,picked);
11768:                 }
11769:             }
11770:         }
11771:     }
11772: }
11773: 
11774: function containerSelect(form,count,offset,picked) {
11775:     if (count > 0) {
11776:         var item = (offset+$startcount)+7*(count-1);
11777:         if (form.elements[item].type == 'radio') {
11778:             if (form.elements[item].value == 'dependency') {
11779:                 if (form.elements[item+1].type == 'select-one') {
11780:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11781:                         if (form.elements[item+1].options[i].value == picked) {
11782:                             form.elements[item+1].selectedIndex = i;
11783:                             break;
11784:                         }
11785:                     }
11786:                 }
11787:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11788:                     if (parents[count].length > 0) {
11789:                         for (var j=0; j<parents[count].length; j++) {
11790:                             containerSelect(form,parents[count][j],offset,picked);
11791:                         }
11792:                     }
11793:                 }
11794:             }
11795:         }
11796:     }
11797: }
11798: 
11799: function titleCheck(form,count,offset) {
11800:     if (count > 0) {
11801:         var chosen = (offset+$startcount)+7*(count-1);
11802:         var depitem = $startcount + ((count-1) * 7) + 2;
11803:         var currtype = form.elements[depitem].type;
11804:         if (form.elements[chosen].value == 'display') {
11805:             document.getElementById('arc_title_'+count).style.display='block';
11806:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11807:                 document.getElementById('archive_title_'+count).value=maintitle;
11808:             }
11809:         } else {
11810:             document.getElementById('arc_title_'+count).style.display='none';
11811:             if (currtype == 'text') { 
11812:                 document.getElementById('archive_title_'+count).value='';
11813:             }
11814:         }
11815:     }
11816:     return;
11817: }
11818: 
11819: // ]]>
11820: </script>
11821: END
11822:     return $scripttag;
11823: }
11824: 
11825: sub process_extracted_files {
11826:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11827:     my $numitems = $env{'form.archive_count'};
11828:     return unless ($numitems);
11829:     my @ids=&Apache::lonnet::current_machine_ids();
11830:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11831:         %folders,%containers,%mapinner,%prompttofetch);
11832:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11833:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11834:         $prefix = &LONCAPA::propath($docudom,$docuname);
11835:         $pathtocheck = "$dir_root/$destination";
11836:         $dir = $dir_root;
11837:         $ishome = 1;
11838:     } else {
11839:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11840:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11841:         $dir = "$dir_root/$docudom/$docuname";    
11842:     }
11843:     my $currdir = "$dir_root/$destination";
11844:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11845:     if ($env{'form.folderpath'}) {
11846:         my @items = split('&',$env{'form.folderpath'});
11847:         $folders{'0'} = $items[-2];
11848:         if ($env{'form.folderpath'} =~ /\:1$/) {
11849:             $containers{'0'}='page';
11850:         } else {
11851:             $containers{'0'}='sequence';
11852:         }
11853:     }
11854:     my @archdirs = &get_env_multiple('form.archive_directory');
11855:     if ($numitems) {
11856:         for (my $i=1; $i<=$numitems; $i++) {
11857:             my $path = $env{'form.archive_content_'.$i};
11858:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11859:                 my $item = $1;
11860:                 $toplevelitems{$item} = $i;
11861:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11862:                     $is_dir{$item} = 1;
11863:                 }
11864:             }
11865:         }
11866:     }
11867:     my ($output,%children,%parent,%titles,%dirorder,$result);
11868:     if (keys(%toplevelitems) > 0) {
11869:         my @contents = sort(keys(%toplevelitems));
11870:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11871:                                            \%parent,\@contents,\%dirorder,\%titles);
11872:     }
11873:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11874:     if ($numitems) {
11875:         for (my $i=1; $i<=$numitems; $i++) {
11876:             next if ($env{'form.archive_'.$i} eq 'dependency');
11877:             my $path = $env{'form.archive_content_'.$i};
11878:             if ($path =~ /^\Q$pathtocheck\E/) {
11879:                 if ($env{'form.archive_'.$i} eq 'discard') {
11880:                     if ($prefix ne '' && $path ne '') {
11881:                         if (-e $prefix.$path) {
11882:                             if ((@archdirs > 0) && 
11883:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11884:                                 $todeletedir{$prefix.$path} = 1;
11885:                             } else {
11886:                                 $todelete{$prefix.$path} = 1;
11887:                             }
11888:                         }
11889:                     }
11890:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11891:                     my ($docstitle,$title,$url,$outer);
11892:                     ($title) = ($path =~ m{/([^/]+)$});
11893:                     $docstitle = $env{'form.archive_title_'.$i};
11894:                     if ($docstitle eq '') {
11895:                         $docstitle = $title;
11896:                     }
11897:                     $outer = 0;
11898:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11899:                         if (@{$dirorder{$i}} > 0) {
11900:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11901:                                 if ($env{'form.archive_'.$item} eq 'display') {
11902:                                     $outer = $item;
11903:                                     last;
11904:                                 }
11905:                             }
11906:                         }
11907:                     }
11908:                     my ($errtext,$fatal) = 
11909:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11910:                                                '/'.$folders{$outer}.'.'.
11911:                                                $containers{$outer});
11912:                     next if ($fatal);
11913:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11914:                         if ($context eq 'coursedocs') {
11915:                             $mapinner{$i} = time;
11916:                             $folders{$i} = 'default_'.$mapinner{$i};
11917:                             $containers{$i} = 'sequence';
11918:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11919:                                       $folders{$i}.'.'.$containers{$i};
11920:                             my $newidx = &LONCAPA::map::getresidx();
11921:                             $LONCAPA::map::resources[$newidx]=
11922:                                 $docstitle.':'.$url.':false:normal:res';
11923:                             push(@LONCAPA::map::order,$newidx);
11924:                             my ($outtext,$errtext) =
11925:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11926:                                                         $docuname.'/'.$folders{$outer}.
11927:                                                         '.'.$containers{$outer},1,1);
11928:                             $newseqid{$i} = $newidx;
11929:                             unless ($errtext) {
11930:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11931:                             }
11932:                         }
11933:                     } else {
11934:                         if ($context eq 'coursedocs') {
11935:                             my $newidx=&LONCAPA::map::getresidx();
11936:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11937:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11938:                                       $title;
11939:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11940:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11941:                             }
11942:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11943:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11944:                             }
11945:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11946:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11947:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11948:                                 unless ($ishome) {
11949:                                     my $fetch = "$newdest{$i}/$title";
11950:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11951:                                     $prompttofetch{$fetch} = 1;
11952:                                 }
11953:                             }
11954:                             $LONCAPA::map::resources[$newidx]=
11955:                                 $docstitle.':'.$url.':false:normal:res';
11956:                             push(@LONCAPA::map::order, $newidx);
11957:                             my ($outtext,$errtext)=
11958:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11959:                                                         $docuname.'/'.$folders{$outer}.
11960:                                                         '.'.$containers{$outer},1,1);
11961:                             unless ($errtext) {
11962:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11963:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11964:                                 }
11965:                             }
11966:                         }
11967:                     }
11968:                 }
11969:             } else {
11970:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11971:             }
11972:         }
11973:         for (my $i=1; $i<=$numitems; $i++) {
11974:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11975:             my $path = $env{'form.archive_content_'.$i};
11976:             if ($path =~ /^\Q$pathtocheck\E/) {
11977:                 my ($title) = ($path =~ m{/([^/]+)$});
11978:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11979:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11980:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11981:                         my ($itemidx,$fullpath,$relpath);
11982:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11983:                             my $container = $dirorder{$referrer{$i}}->[-1];
11984:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11985:                                 if ($dirorder{$i}->[$j] eq $container) {
11986:                                     $itemidx = $j;
11987:                                 }
11988:                             }
11989:                         }
11990:                         if ($itemidx eq '') {
11991:                             $itemidx =  0;
11992:                         }
11993:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11994:                             if ($mapinner{$referrer{$i}}) {
11995:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11996:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11997:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11998:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11999:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12000:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12001:                                             if (!-e $fullpath) {
12002:                                                 mkdir($fullpath,0755);
12003:                                             }
12004:                                         }
12005:                                     } else {
12006:                                         last;
12007:                                     }
12008:                                 }
12009:                             }
12010:                         } elsif ($newdest{$referrer{$i}}) {
12011:                             $fullpath = $newdest{$referrer{$i}};
12012:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12013:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12014:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12015:                                     last;
12016:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12017:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12018:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12019:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12020:                                         if (!-e $fullpath) {
12021:                                             mkdir($fullpath,0755);
12022:                                         }
12023:                                     }
12024:                                 } else {
12025:                                     last;
12026:                                 }
12027:                             }
12028:                         }
12029:                         if ($fullpath ne '') {
12030:                             if (-e "$prefix$path") {
12031:                                 system("mv $prefix$path $fullpath/$title");
12032:                             }
12033:                             if (-e "$fullpath/$title") {
12034:                                 my $showpath;
12035:                                 if ($relpath ne '') {
12036:                                     $showpath = "$relpath/$title";
12037:                                 } else {
12038:                                     $showpath = "/$title";
12039:                                 }
12040:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12041:                             }
12042:                             unless ($ishome) {
12043:                                 my $fetch = "$fullpath/$title";
12044:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12045:                                 $prompttofetch{$fetch} = 1;
12046:                             }
12047:                         }
12048:                     }
12049:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12050:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12051:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12052:                 }
12053:             } else {
12054:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12055:             }
12056:         }
12057:         if (keys(%todelete)) {
12058:             foreach my $key (keys(%todelete)) {
12059:                 unlink($key);
12060:             }
12061:         }
12062:         if (keys(%todeletedir)) {
12063:             foreach my $key (keys(%todeletedir)) {
12064:                 rmdir($key);
12065:             }
12066:         }
12067:         foreach my $dir (sort(keys(%is_dir))) {
12068:             if (($pathtocheck ne '') && ($dir ne ''))  {
12069:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12070:             }
12071:         }
12072:         if ($result ne '') {
12073:             $output .= '<ul>'."\n".
12074:                        $result."\n".
12075:                        '</ul>';
12076:         }
12077:         unless ($ishome) {
12078:             my $replicationfail;
12079:             foreach my $item (keys(%prompttofetch)) {
12080:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12081:                 unless ($fetchresult eq 'ok') {
12082:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12083:                 }
12084:             }
12085:             if ($replicationfail) {
12086:                 $output .= '<p class="LC_error">'.
12087:                            &mt('Course home server failed to retrieve:').'<ul>'.
12088:                            $replicationfail.
12089:                            '</ul></p>';
12090:             }
12091:         }
12092:     } else {
12093:         $warning = &mt('No items found in archive.');
12094:     }
12095:     if ($error) {
12096:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12097:                    $error.'</p>'."\n";
12098:     }
12099:     if ($warning) {
12100:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12101:     }
12102:     return $output;
12103: }
12104: 
12105: sub cleanup_empty_dirs {
12106:     my ($path) = @_;
12107:     if (($path ne '') && (-d $path)) {
12108:         if (opendir(my $dirh,$path)) {
12109:             my @dircontents = grep(!/^\./,readdir($dirh));
12110:             my $numitems = 0;
12111:             foreach my $item (@dircontents) {
12112:                 if (-d "$path/$item") {
12113:                     &cleanup_empty_dirs("$path/$item");
12114:                     if (-e "$path/$item") {
12115:                         $numitems ++;
12116:                     }
12117:                 } else {
12118:                     $numitems ++;
12119:                 }
12120:             }
12121:             if ($numitems == 0) {
12122:                 rmdir($path);
12123:             }
12124:             closedir($dirh);
12125:         }
12126:     }
12127:     return;
12128: }
12129: 
12130: =pod
12131: 
12132: =item * &get_folder_hierarchy()
12133: 
12134: Provides hierarchy of names of folders/sub-folders containing the current
12135: item,
12136: 
12137: Inputs: 3
12138:      - $navmap - navmaps object
12139: 
12140:      - $map - url for map (either the trigger itself, or map containing
12141:                            the resource, which is the trigger).
12142: 
12143:      - $showitem - 1 => show title for map itself; 0 => do not show.
12144: 
12145: Outputs: 1 @pathitems - array of folder/subfolder names.
12146: 
12147: =cut
12148: 
12149: sub get_folder_hierarchy {
12150:     my ($navmap,$map,$showitem) = @_;
12151:     my @pathitems;
12152:     if (ref($navmap)) {
12153:         my $mapres = $navmap->getResourceByUrl($map);
12154:         if (ref($mapres)) {
12155:             my $pcslist = $mapres->map_hierarchy();
12156:             if ($pcslist ne '') {
12157:                 my @pcs = split(/,/,$pcslist);
12158:                 foreach my $pc (@pcs) {
12159:                     if ($pc == 1) {
12160:                         push(@pathitems,&mt('Main Content'));
12161:                     } else {
12162:                         my $res = $navmap->getByMapPc($pc);
12163:                         if (ref($res)) {
12164:                             my $title = $res->compTitle();
12165:                             $title =~ s/\W+/_/g;
12166:                             if ($title ne '') {
12167:                                 push(@pathitems,$title);
12168:                             }
12169:                         }
12170:                     }
12171:                 }
12172:             }
12173:             if ($showitem) {
12174:                 if ($mapres->{ID} eq '0.0') {
12175:                     push(@pathitems,&mt('Main Content'));
12176:                 } else {
12177:                     my $maptitle = $mapres->compTitle();
12178:                     $maptitle =~ s/\W+/_/g;
12179:                     if ($maptitle ne '') {
12180:                         push(@pathitems,$maptitle);
12181:                     }
12182:                 }
12183:             }
12184:         }
12185:     }
12186:     return @pathitems;
12187: }
12188: 
12189: =pod
12190: 
12191: =item * &get_turnedin_filepath()
12192: 
12193: Determines path in a user's portfolio file for storage of files uploaded
12194: to a specific essayresponse or dropbox item.
12195: 
12196: Inputs: 3 required + 1 optional.
12197: $symb is symb for resource, $uname and $udom are for current user (required).
12198: $caller is optional (can be "submission", if routine is called when storing
12199: an upoaded file when "Submit Answer" button was pressed).
12200: 
12201: Returns array containing $path and $multiresp. 
12202: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12203: than one file upload item.  Callers of routine should append partid as a 
12204: subdirectory to $path in cases where $multiresp is 1.
12205: 
12206: Called by: homework/essayresponse.pm and homework/structuretags.pm
12207: 
12208: =cut
12209: 
12210: sub get_turnedin_filepath {
12211:     my ($symb,$uname,$udom,$caller) = @_;
12212:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12213:     my $turnindir;
12214:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12215:     $turnindir = $userhash{'turnindir'};
12216:     my ($path,$multiresp);
12217:     if ($turnindir eq '') {
12218:         if ($caller eq 'submission') {
12219:             $turnindir = &mt('turned in');
12220:             $turnindir =~ s/\W+/_/g;
12221:             my %newhash = (
12222:                             'turnindir' => $turnindir,
12223:                           );
12224:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12225:         }
12226:     }
12227:     if ($turnindir ne '') {
12228:         $path = '/'.$turnindir.'/';
12229:         my ($multipart,$turnin,@pathitems);
12230:         my $navmap = Apache::lonnavmaps::navmap->new();
12231:         if (defined($navmap)) {
12232:             my $mapres = $navmap->getResourceByUrl($map);
12233:             if (ref($mapres)) {
12234:                 my $pcslist = $mapres->map_hierarchy();
12235:                 if ($pcslist ne '') {
12236:                     foreach my $pc (split(/,/,$pcslist)) {
12237:                         my $res = $navmap->getByMapPc($pc);
12238:                         if (ref($res)) {
12239:                             my $title = $res->compTitle();
12240:                             $title =~ s/\W+/_/g;
12241:                             if ($title ne '') {
12242:                                 if (($pc > 1) && (length($title) > 12)) {
12243:                                     $title = substr($title,0,12);
12244:                                 }
12245:                                 push(@pathitems,$title);
12246:                             }
12247:                         }
12248:                     }
12249:                 }
12250:                 my $maptitle = $mapres->compTitle();
12251:                 $maptitle =~ s/\W+/_/g;
12252:                 if ($maptitle ne '') {
12253:                     if (length($maptitle) > 12) {
12254:                         $maptitle = substr($maptitle,0,12);
12255:                     }
12256:                     push(@pathitems,$maptitle);
12257:                 }
12258:                 unless ($env{'request.state'} eq 'construct') {
12259:                     my $res = $navmap->getBySymb($symb);
12260:                     if (ref($res)) {
12261:                         my $partlist = $res->parts();
12262:                         my $totaluploads = 0;
12263:                         if (ref($partlist) eq 'ARRAY') {
12264:                             foreach my $part (@{$partlist}) {
12265:                                 my @types = $res->responseType($part);
12266:                                 my @ids = $res->responseIds($part);
12267:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12268:                                     if ($types[$i] eq 'essay') {
12269:                                         my $partid = $part.'_'.$ids[$i];
12270:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12271:                                             $totaluploads ++;
12272:                                         }
12273:                                     }
12274:                                 }
12275:                             }
12276:                             if ($totaluploads > 1) {
12277:                                 $multiresp = 1;
12278:                             }
12279:                         }
12280:                     }
12281:                 }
12282:             } else {
12283:                 return;
12284:             }
12285:         } else {
12286:             return;
12287:         }
12288:         my $restitle=&Apache::lonnet::gettitle($symb);
12289:         $restitle =~ s/\W+/_/g;
12290:         if ($restitle eq '') {
12291:             $restitle = ($resurl =~ m{/[^/]+$});
12292:             if ($restitle eq '') {
12293:                 $restitle = time;
12294:             }
12295:         }
12296:         if (length($restitle) > 12) {
12297:             $restitle = substr($restitle,0,12);
12298:         }
12299:         push(@pathitems,$restitle);
12300:         $path .= join('/',@pathitems);
12301:     }
12302:     return ($path,$multiresp);
12303: }
12304: 
12305: =pod
12306: 
12307: =back
12308: 
12309: =head1 CSV Upload/Handling functions
12310: 
12311: =over 4
12312: 
12313: =item * &upfile_store($r)
12314: 
12315: Store uploaded file, $r should be the HTTP Request object,
12316: needs $env{'form.upfile'}
12317: returns $datatoken to be put into hidden field
12318: 
12319: =cut
12320: 
12321: sub upfile_store {
12322:     my $r=shift;
12323:     $env{'form.upfile'}=~s/\r/\n/gs;
12324:     $env{'form.upfile'}=~s/\f/\n/gs;
12325:     $env{'form.upfile'}=~s/\n+/\n/gs;
12326:     $env{'form.upfile'}=~s/\n+$//gs;
12327: 
12328:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12329: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12330:     {
12331:         my $datafile = $r->dir_config('lonDaemons').
12332:                            '/tmp/'.$datatoken.'.tmp';
12333:         if ( open(my $fh,">$datafile") ) {
12334:             print $fh $env{'form.upfile'};
12335:             close($fh);
12336:         }
12337:     }
12338:     return $datatoken;
12339: }
12340: 
12341: =pod
12342: 
12343: =item * &load_tmp_file($r)
12344: 
12345: Load uploaded file from tmp, $r should be the HTTP Request object,
12346: needs $env{'form.datatoken'},
12347: sets $env{'form.upfile'} to the contents of the file
12348: 
12349: =cut
12350: 
12351: sub load_tmp_file {
12352:     my $r=shift;
12353:     my @studentdata=();
12354:     {
12355:         my $studentfile = $r->dir_config('lonDaemons').
12356:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12357:         if ( open(my $fh,"<$studentfile") ) {
12358:             @studentdata=<$fh>;
12359:             close($fh);
12360:         }
12361:     }
12362:     $env{'form.upfile'}=join('',@studentdata);
12363: }
12364: 
12365: =pod
12366: 
12367: =item * &upfile_record_sep()
12368: 
12369: Separate uploaded file into records
12370: returns array of records,
12371: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12372: 
12373: =cut
12374: 
12375: sub upfile_record_sep {
12376:     if ($env{'form.upfiletype'} eq 'xml') {
12377:     } else {
12378: 	my @records;
12379: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12380: 	    if ($line=~/^\s*$/) { next; }
12381: 	    push(@records,$line);
12382: 	}
12383: 	return @records;
12384:     }
12385: }
12386: 
12387: =pod
12388: 
12389: =item * &record_sep($record)
12390: 
12391: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12392: 
12393: =cut
12394: 
12395: sub takeleft {
12396:     my $index=shift;
12397:     return substr('0000'.$index,-4,4);
12398: }
12399: 
12400: sub record_sep {
12401:     my $record=shift;
12402:     my %components=();
12403:     if ($env{'form.upfiletype'} eq 'xml') {
12404:     } elsif ($env{'form.upfiletype'} eq 'space') {
12405:         my $i=0;
12406:         foreach my $field (split(/\s+/,$record)) {
12407:             $field=~s/^(\"|\')//;
12408:             $field=~s/(\"|\')$//;
12409:             $components{&takeleft($i)}=$field;
12410:             $i++;
12411:         }
12412:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12413:         my $i=0;
12414:         foreach my $field (split(/\t/,$record)) {
12415:             $field=~s/^(\"|\')//;
12416:             $field=~s/(\"|\')$//;
12417:             $components{&takeleft($i)}=$field;
12418:             $i++;
12419:         }
12420:     } else {
12421:         my $separator=',';
12422:         if ($env{'form.upfiletype'} eq 'semisv') {
12423:             $separator=';';
12424:         }
12425:         my $i=0;
12426: # the character we are looking for to indicate the end of a quote or a record 
12427:         my $looking_for=$separator;
12428: # do not add the characters to the fields
12429:         my $ignore=0;
12430: # we just encountered a separator (or the beginning of the record)
12431:         my $just_found_separator=1;
12432: # store the field we are working on here
12433:         my $field='';
12434: # work our way through all characters in record
12435:         foreach my $character ($record=~/(.)/g) {
12436:             if ($character eq $looking_for) {
12437:                if ($character ne $separator) {
12438: # Found the end of a quote, again looking for separator
12439:                   $looking_for=$separator;
12440:                   $ignore=1;
12441:                } else {
12442: # Found a separator, store away what we got
12443:                   $components{&takeleft($i)}=$field;
12444: 	          $i++;
12445:                   $just_found_separator=1;
12446:                   $ignore=0;
12447:                   $field='';
12448:                }
12449:                next;
12450:             }
12451: # single or double quotation marks after a separator indicate beginning of a quote
12452: # we are now looking for the end of the quote and need to ignore separators
12453:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12454:                $looking_for=$character;
12455:                next;
12456:             }
12457: # ignore would be true after we reached the end of a quote
12458:             if ($ignore) { next; }
12459:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12460:             $field.=$character;
12461:             $just_found_separator=0; 
12462:         }
12463: # catch the very last entry, since we never encountered the separator
12464:         $components{&takeleft($i)}=$field;
12465:     }
12466:     return %components;
12467: }
12468: 
12469: ######################################################
12470: ######################################################
12471: 
12472: =pod
12473: 
12474: =item * &upfile_select_html()
12475: 
12476: Return HTML code to select a file from the users machine and specify 
12477: the file type.
12478: 
12479: =cut
12480: 
12481: ######################################################
12482: ######################################################
12483: sub upfile_select_html {
12484:     my %Types = (
12485:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12486:                  semisv => &mt('Semicolon separated values'),
12487:                  space => &mt('Space separated'),
12488:                  tab   => &mt('Tabulator separated'),
12489: #                 xml   => &mt('HTML/XML'),
12490:                  );
12491:     my $Str = '<input type="file" name="upfile" size="50" />'.
12492:         '<br />'.&mt('Type').': <select name="upfiletype">';
12493:     foreach my $type (sort(keys(%Types))) {
12494:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12495:     }
12496:     $Str .= "</select>\n";
12497:     return $Str;
12498: }
12499: 
12500: sub get_samples {
12501:     my ($records,$toget) = @_;
12502:     my @samples=({});
12503:     my $got=0;
12504:     foreach my $rec (@$records) {
12505: 	my %temp = &record_sep($rec);
12506: 	if (! grep(/\S/, values(%temp))) { next; }
12507: 	if (%temp) {
12508: 	    $samples[$got]=\%temp;
12509: 	    $got++;
12510: 	    if ($got == $toget) { last; }
12511: 	}
12512:     }
12513:     return \@samples;
12514: }
12515: 
12516: ######################################################
12517: ######################################################
12518: 
12519: =pod
12520: 
12521: =item * &csv_print_samples($r,$records)
12522: 
12523: Prints a table of sample values from each column uploaded $r is an
12524: Apache Request ref, $records is an arrayref from
12525: &Apache::loncommon::upfile_record_sep
12526: 
12527: =cut
12528: 
12529: ######################################################
12530: ######################################################
12531: sub csv_print_samples {
12532:     my ($r,$records) = @_;
12533:     my $samples = &get_samples($records,5);
12534: 
12535:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12536:               &start_data_table_header_row());
12537:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12538:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12539:     $r->print(&end_data_table_header_row());
12540:     foreach my $hash (@$samples) {
12541: 	$r->print(&start_data_table_row());
12542: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12543: 	    $r->print('<td>');
12544: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12545: 	    $r->print('</td>');
12546: 	}
12547: 	$r->print(&end_data_table_row());
12548:     }
12549:     $r->print(&end_data_table().'<br />'."\n");
12550: }
12551: 
12552: ######################################################
12553: ######################################################
12554: 
12555: =pod
12556: 
12557: =item * &csv_print_select_table($r,$records,$d)
12558: 
12559: Prints a table to create associations between values and table columns.
12560: 
12561: $r is an Apache Request ref,
12562: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12563: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12564: 
12565: =cut
12566: 
12567: ######################################################
12568: ######################################################
12569: sub csv_print_select_table {
12570:     my ($r,$records,$d) = @_;
12571:     my $i=0;
12572:     my $samples = &get_samples($records,1);
12573:     $r->print(&mt('Associate columns with student attributes.')."\n".
12574: 	      &start_data_table().&start_data_table_header_row().
12575:               '<th>'.&mt('Attribute').'</th>'.
12576:               '<th>'.&mt('Column').'</th>'.
12577:               &end_data_table_header_row()."\n");
12578:     foreach my $array_ref (@$d) {
12579: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12580: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12581: 
12582: 	$r->print('<td><select name="f'.$i.'"'.
12583: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12584: 	$r->print('<option value="none"></option>');
12585: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12586: 	    $r->print('<option value="'.$sample.'"'.
12587:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12588:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12589: 	}
12590: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12591: 	$i++;
12592:     }
12593:     $r->print(&end_data_table());
12594:     $i--;
12595:     return $i;
12596: }
12597: 
12598: ######################################################
12599: ######################################################
12600: 
12601: =pod
12602: 
12603: =item * &csv_samples_select_table($r,$records,$d)
12604: 
12605: Prints a table of sample values from the upload and can make associate samples to internal names.
12606: 
12607: $r is an Apache Request ref,
12608: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12609: $d is an array of 2 element arrays (internal name, displayed name)
12610: 
12611: =cut
12612: 
12613: ######################################################
12614: ######################################################
12615: sub csv_samples_select_table {
12616:     my ($r,$records,$d) = @_;
12617:     my $i=0;
12618:     #
12619:     my $max_samples = 5;
12620:     my $samples = &get_samples($records,$max_samples);
12621:     $r->print(&start_data_table().
12622:               &start_data_table_header_row().'<th>'.
12623:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12624:               &end_data_table_header_row());
12625: 
12626:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12627: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12628: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12629: 	foreach my $option (@$d) {
12630: 	    my ($value,$display,$defaultcol)=@{ $option };
12631: 	    $r->print('<option value="'.$value.'"'.
12632:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12633:                       $display.'</option>');
12634: 	}
12635: 	$r->print('</select></td><td>');
12636: 	foreach my $line (0..($max_samples-1)) {
12637: 	    if (defined($samples->[$line]{$key})) { 
12638: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12639: 	    }
12640: 	}
12641: 	$r->print('</td>'.&end_data_table_row());
12642: 	$i++;
12643:     }
12644:     $r->print(&end_data_table());
12645:     $i--;
12646:     return($i);
12647: }
12648: 
12649: ######################################################
12650: ######################################################
12651: 
12652: =pod
12653: 
12654: =item * &clean_excel_name($name)
12655: 
12656: Returns a replacement for $name which does not contain any illegal characters.
12657: 
12658: =cut
12659: 
12660: ######################################################
12661: ######################################################
12662: sub clean_excel_name {
12663:     my ($name) = @_;
12664:     $name =~ s/[:\*\?\/\\]//g;
12665:     if (length($name) > 31) {
12666:         $name = substr($name,0,31);
12667:     }
12668:     return $name;
12669: }
12670: 
12671: =pod
12672: 
12673: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12674: 
12675: Returns either 1 or undef
12676: 
12677: 1 if the part is to be hidden, undef if it is to be shown
12678: 
12679: Arguments are:
12680: 
12681: $id the id of the part to be checked
12682: $symb, optional the symb of the resource to check
12683: $udom, optional the domain of the user to check for
12684: $uname, optional the username of the user to check for
12685: 
12686: =cut
12687: 
12688: sub check_if_partid_hidden {
12689:     my ($id,$symb,$udom,$uname) = @_;
12690:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12691: 					 $symb,$udom,$uname);
12692:     my $truth=1;
12693:     #if the string starts with !, then the list is the list to show not hide
12694:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12695:     my @hiddenlist=split(/,/,$hiddenparts);
12696:     foreach my $checkid (@hiddenlist) {
12697: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12698:     }
12699:     return !$truth;
12700: }
12701: 
12702: 
12703: ############################################################
12704: ############################################################
12705: 
12706: =pod
12707: 
12708: =back 
12709: 
12710: =head1 cgi-bin script and graphing routines
12711: 
12712: =over 4
12713: 
12714: =item * &get_cgi_id()
12715: 
12716: Inputs: none
12717: 
12718: Returns an id which can be used to pass environment variables
12719: to various cgi-bin scripts.  These environment variables will
12720: be removed from the users environment after a given time by
12721: the routine &Apache::lonnet::transfer_profile_to_env.
12722: 
12723: =cut
12724: 
12725: ############################################################
12726: ############################################################
12727: my $uniq=0;
12728: sub get_cgi_id {
12729:     $uniq=($uniq+1)%100000;
12730:     return (time.'_'.$$.'_'.$uniq);
12731: }
12732: 
12733: ############################################################
12734: ############################################################
12735: 
12736: =pod
12737: 
12738: =item * &DrawBarGraph()
12739: 
12740: Facilitates the plotting of data in a (stacked) bar graph.
12741: Puts plot definition data into the users environment in order for 
12742: graph.png to plot it.  Returns an <img> tag for the plot.
12743: The bars on the plot are labeled '1','2',...,'n'.
12744: 
12745: Inputs:
12746: 
12747: =over 4
12748: 
12749: =item $Title: string, the title of the plot
12750: 
12751: =item $xlabel: string, text describing the X-axis of the plot
12752: 
12753: =item $ylabel: string, text describing the Y-axis of the plot
12754: 
12755: =item $Max: scalar, the maximum Y value to use in the plot
12756: If $Max is < any data point, the graph will not be rendered.
12757: 
12758: =item $colors: array ref holding the colors to be used for the data sets when
12759: they are plotted.  If undefined, default values will be used.
12760: 
12761: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12762: 
12763: =item @Values: An array of array references.  Each array reference holds data
12764: to be plotted in a stacked bar chart.
12765: 
12766: =item If the final element of @Values is a hash reference the key/value
12767: pairs will be added to the graph definition.
12768: 
12769: =back
12770: 
12771: Returns:
12772: 
12773: An <img> tag which references graph.png and the appropriate identifying
12774: information for the plot.
12775: 
12776: =cut
12777: 
12778: ############################################################
12779: ############################################################
12780: sub DrawBarGraph {
12781:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12782:     #
12783:     if (! defined($colors)) {
12784:         $colors = ['#33ff00', 
12785:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12786:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12787:                   ]; 
12788:     }
12789:     my $extra_settings = {};
12790:     if (ref($Values[-1]) eq 'HASH') {
12791:         $extra_settings = pop(@Values);
12792:     }
12793:     #
12794:     my $identifier = &get_cgi_id();
12795:     my $id = 'cgi.'.$identifier;        
12796:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12797:         return '';
12798:     }
12799:     #
12800:     my @Labels;
12801:     if (defined($labels)) {
12802:         @Labels = @$labels;
12803:     } else {
12804:         for (my $i=0;$i<@{$Values[0]};$i++) {
12805:             push (@Labels,$i+1);
12806:         }
12807:     }
12808:     #
12809:     my $NumBars = scalar(@{$Values[0]});
12810:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12811:     my %ValuesHash;
12812:     my $NumSets=1;
12813:     foreach my $array (@Values) {
12814:         next if (! ref($array));
12815:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12816:             join(',',@$array);
12817:     }
12818:     #
12819:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12820:     if ($NumBars < 3) {
12821:         $width = 120+$NumBars*32;
12822:         $xskip = 1;
12823:         $bar_width = 30;
12824:     } elsif ($NumBars < 5) {
12825:         $width = 120+$NumBars*20;
12826:         $xskip = 1;
12827:         $bar_width = 20;
12828:     } elsif ($NumBars < 10) {
12829:         $width = 120+$NumBars*15;
12830:         $xskip = 1;
12831:         $bar_width = 15;
12832:     } elsif ($NumBars <= 25) {
12833:         $width = 120+$NumBars*11;
12834:         $xskip = 5;
12835:         $bar_width = 8;
12836:     } elsif ($NumBars <= 50) {
12837:         $width = 120+$NumBars*8;
12838:         $xskip = 5;
12839:         $bar_width = 4;
12840:     } else {
12841:         $width = 120+$NumBars*8;
12842:         $xskip = 5;
12843:         $bar_width = 4;
12844:     }
12845:     #
12846:     $Max = 1 if ($Max < 1);
12847:     if ( int($Max) < $Max ) {
12848:         $Max++;
12849:         $Max = int($Max);
12850:     }
12851:     $Title  = '' if (! defined($Title));
12852:     $xlabel = '' if (! defined($xlabel));
12853:     $ylabel = '' if (! defined($ylabel));
12854:     $ValuesHash{$id.'.title'}    = &escape($Title);
12855:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12856:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12857:     $ValuesHash{$id.'.y_max_value'} = $Max;
12858:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12859:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12860:     $ValuesHash{$id.'.PlotType'} = 'bar';
12861:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12862:     $ValuesHash{$id.'.height'}   = $height;
12863:     $ValuesHash{$id.'.width'}    = $width;
12864:     $ValuesHash{$id.'.xskip'}    = $xskip;
12865:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12866:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12867:     #
12868:     # Deal with other parameters
12869:     while (my ($key,$value) = each(%$extra_settings)) {
12870:         $ValuesHash{$id.'.'.$key} = $value;
12871:     }
12872:     #
12873:     &Apache::lonnet::appenv(\%ValuesHash);
12874:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12875: }
12876: 
12877: ############################################################
12878: ############################################################
12879: 
12880: =pod
12881: 
12882: =item * &DrawXYGraph()
12883: 
12884: Facilitates the plotting of data in an XY graph.
12885: Puts plot definition data into the users environment in order for 
12886: graph.png to plot it.  Returns an <img> tag for the plot.
12887: 
12888: Inputs:
12889: 
12890: =over 4
12891: 
12892: =item $Title: string, the title of the plot
12893: 
12894: =item $xlabel: string, text describing the X-axis of the plot
12895: 
12896: =item $ylabel: string, text describing the Y-axis of the plot
12897: 
12898: =item $Max: scalar, the maximum Y value to use in the plot
12899: If $Max is < any data point, the graph will not be rendered.
12900: 
12901: =item $colors: Array ref containing the hex color codes for the data to be 
12902: plotted in.  If undefined, default values will be used.
12903: 
12904: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12905: 
12906: =item $Ydata: Array ref containing Array refs.  
12907: Each of the contained arrays will be plotted as a separate curve.
12908: 
12909: =item %Values: hash indicating or overriding any default values which are 
12910: passed to graph.png.  
12911: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12912: 
12913: =back
12914: 
12915: Returns:
12916: 
12917: An <img> tag which references graph.png and the appropriate identifying
12918: information for the plot.
12919: 
12920: =cut
12921: 
12922: ############################################################
12923: ############################################################
12924: sub DrawXYGraph {
12925:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12926:     #
12927:     # Create the identifier for the graph
12928:     my $identifier = &get_cgi_id();
12929:     my $id = 'cgi.'.$identifier;
12930:     #
12931:     $Title  = '' if (! defined($Title));
12932:     $xlabel = '' if (! defined($xlabel));
12933:     $ylabel = '' if (! defined($ylabel));
12934:     my %ValuesHash = 
12935:         (
12936:          $id.'.title'  => &escape($Title),
12937:          $id.'.xlabel' => &escape($xlabel),
12938:          $id.'.ylabel' => &escape($ylabel),
12939:          $id.'.y_max_value'=> $Max,
12940:          $id.'.labels'     => join(',',@$Xlabels),
12941:          $id.'.PlotType'   => 'XY',
12942:          );
12943:     #
12944:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12945:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12946:     }
12947:     #
12948:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12949:         return '';
12950:     }
12951:     my $NumSets=1;
12952:     foreach my $array (@{$Ydata}){
12953:         next if (! ref($array));
12954:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12955:     }
12956:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12957:     #
12958:     # Deal with other parameters
12959:     while (my ($key,$value) = each(%Values)) {
12960:         $ValuesHash{$id.'.'.$key} = $value;
12961:     }
12962:     #
12963:     &Apache::lonnet::appenv(\%ValuesHash);
12964:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12965: }
12966: 
12967: ############################################################
12968: ############################################################
12969: 
12970: =pod
12971: 
12972: =item * &DrawXYYGraph()
12973: 
12974: Facilitates the plotting of data in an XY graph with two Y axes.
12975: Puts plot definition data into the users environment in order for 
12976: graph.png to plot it.  Returns an <img> tag for the plot.
12977: 
12978: Inputs:
12979: 
12980: =over 4
12981: 
12982: =item $Title: string, the title of the plot
12983: 
12984: =item $xlabel: string, text describing the X-axis of the plot
12985: 
12986: =item $ylabel: string, text describing the Y-axis of the plot
12987: 
12988: =item $colors: Array ref containing the hex color codes for the data to be 
12989: plotted in.  If undefined, default values will be used.
12990: 
12991: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12992: 
12993: =item $Ydata1: The first data set
12994: 
12995: =item $Min1: The minimum value of the left Y-axis
12996: 
12997: =item $Max1: The maximum value of the left Y-axis
12998: 
12999: =item $Ydata2: The second data set
13000: 
13001: =item $Min2: The minimum value of the right Y-axis
13002: 
13003: =item $Max2: The maximum value of the left Y-axis
13004: 
13005: =item %Values: hash indicating or overriding any default values which are 
13006: passed to graph.png.  
13007: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13008: 
13009: =back
13010: 
13011: Returns:
13012: 
13013: An <img> tag which references graph.png and the appropriate identifying
13014: information for the plot.
13015: 
13016: =cut
13017: 
13018: ############################################################
13019: ############################################################
13020: sub DrawXYYGraph {
13021:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13022:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13023:     #
13024:     # Create the identifier for the graph
13025:     my $identifier = &get_cgi_id();
13026:     my $id = 'cgi.'.$identifier;
13027:     #
13028:     $Title  = '' if (! defined($Title));
13029:     $xlabel = '' if (! defined($xlabel));
13030:     $ylabel = '' if (! defined($ylabel));
13031:     my %ValuesHash = 
13032:         (
13033:          $id.'.title'  => &escape($Title),
13034:          $id.'.xlabel' => &escape($xlabel),
13035:          $id.'.ylabel' => &escape($ylabel),
13036:          $id.'.labels' => join(',',@$Xlabels),
13037:          $id.'.PlotType' => 'XY',
13038:          $id.'.NumSets' => 2,
13039:          $id.'.two_axes' => 1,
13040:          $id.'.y1_max_value' => $Max1,
13041:          $id.'.y1_min_value' => $Min1,
13042:          $id.'.y2_max_value' => $Max2,
13043:          $id.'.y2_min_value' => $Min2,
13044:          );
13045:     #
13046:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13047:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13048:     }
13049:     #
13050:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13051:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13052:         return '';
13053:     }
13054:     my $NumSets=1;
13055:     foreach my $array ($Ydata1,$Ydata2){
13056:         next if (! ref($array));
13057:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13058:     }
13059:     #
13060:     # Deal with other parameters
13061:     while (my ($key,$value) = each(%Values)) {
13062:         $ValuesHash{$id.'.'.$key} = $value;
13063:     }
13064:     #
13065:     &Apache::lonnet::appenv(\%ValuesHash);
13066:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13067: }
13068: 
13069: ############################################################
13070: ############################################################
13071: 
13072: =pod
13073: 
13074: =back 
13075: 
13076: =head1 Statistics helper routines?  
13077: 
13078: Bad place for them but what the hell.
13079: 
13080: =over 4
13081: 
13082: =item * &chartlink()
13083: 
13084: Returns a link to the chart for a specific student.  
13085: 
13086: Inputs:
13087: 
13088: =over 4
13089: 
13090: =item $linktext: The text of the link
13091: 
13092: =item $sname: The students username
13093: 
13094: =item $sdomain: The students domain
13095: 
13096: =back
13097: 
13098: =back
13099: 
13100: =cut
13101: 
13102: ############################################################
13103: ############################################################
13104: sub chartlink {
13105:     my ($linktext, $sname, $sdomain) = @_;
13106:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13107:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13108:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13109:        '">'.$linktext.'</a>';
13110: }
13111: 
13112: #######################################################
13113: #######################################################
13114: 
13115: =pod
13116: 
13117: =head1 Course Environment Routines
13118: 
13119: =over 4
13120: 
13121: =item * &restore_course_settings()
13122: 
13123: =item * &store_course_settings()
13124: 
13125: Restores/Store indicated form parameters from the course environment.
13126: Will not overwrite existing values of the form parameters.
13127: 
13128: Inputs: 
13129: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13130: 
13131: a hash ref describing the data to be stored.  For example:
13132:    
13133: %Save_Parameters = ('Status' => 'scalar',
13134:     'chartoutputmode' => 'scalar',
13135:     'chartoutputdata' => 'scalar',
13136:     'Section' => 'array',
13137:     'Group' => 'array',
13138:     'StudentData' => 'array',
13139:     'Maps' => 'array');
13140: 
13141: Returns: both routines return nothing
13142: 
13143: =back
13144: 
13145: =cut
13146: 
13147: #######################################################
13148: #######################################################
13149: sub store_course_settings {
13150:     return &store_settings($env{'request.course.id'},@_);
13151: }
13152: 
13153: sub store_settings {
13154:     # save to the environment
13155:     # appenv the same items, just to be safe
13156:     my $udom  = $env{'user.domain'};
13157:     my $uname = $env{'user.name'};
13158:     my ($context,$prefix,$Settings) = @_;
13159:     my %SaveHash;
13160:     my %AppHash;
13161:     while (my ($setting,$type) = each(%$Settings)) {
13162:         my $basename = join('.','internal',$context,$prefix,$setting);
13163:         my $envname = 'environment.'.$basename;
13164:         if (exists($env{'form.'.$setting})) {
13165:             # Save this value away
13166:             if ($type eq 'scalar' &&
13167:                 (! exists($env{$envname}) || 
13168:                  $env{$envname} ne $env{'form.'.$setting})) {
13169:                 $SaveHash{$basename} = $env{'form.'.$setting};
13170:                 $AppHash{$envname}   = $env{'form.'.$setting};
13171:             } elsif ($type eq 'array') {
13172:                 my $stored_form;
13173:                 if (ref($env{'form.'.$setting})) {
13174:                     $stored_form = join(',',
13175:                                         map {
13176:                                             &escape($_);
13177:                                         } sort(@{$env{'form.'.$setting}}));
13178:                 } else {
13179:                     $stored_form = 
13180:                         &escape($env{'form.'.$setting});
13181:                 }
13182:                 # Determine if the array contents are the same.
13183:                 if ($stored_form ne $env{$envname}) {
13184:                     $SaveHash{$basename} = $stored_form;
13185:                     $AppHash{$envname}   = $stored_form;
13186:                 }
13187:             }
13188:         }
13189:     }
13190:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13191:                                           $udom,$uname);
13192:     if ($put_result !~ /^(ok|delayed)/) {
13193:         &Apache::lonnet::logthis('unable to save form parameters, '.
13194:                                  'got error:'.$put_result);
13195:     }
13196:     # Make sure these settings stick around in this session, too
13197:     &Apache::lonnet::appenv(\%AppHash);
13198:     return;
13199: }
13200: 
13201: sub restore_course_settings {
13202:     return &restore_settings($env{'request.course.id'},@_);
13203: }
13204: 
13205: sub restore_settings {
13206:     my ($context,$prefix,$Settings) = @_;
13207:     while (my ($setting,$type) = each(%$Settings)) {
13208:         next if (exists($env{'form.'.$setting}));
13209:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13210:             '.'.$setting;
13211:         if (exists($env{$envname})) {
13212:             if ($type eq 'scalar') {
13213:                 $env{'form.'.$setting} = $env{$envname};
13214:             } elsif ($type eq 'array') {
13215:                 $env{'form.'.$setting} = [ 
13216:                                            map { 
13217:                                                &unescape($_); 
13218:                                            } split(',',$env{$envname})
13219:                                            ];
13220:             }
13221:         }
13222:     }
13223: }
13224: 
13225: #######################################################
13226: #######################################################
13227: 
13228: =pod
13229: 
13230: =head1 Domain E-mail Routines  
13231: 
13232: =over 4
13233: 
13234: =item * &build_recipient_list()
13235: 
13236: Build recipient lists for following types of e-mail:
13237: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13238: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13239: module change checking, student/employee ID conflict checks, as
13240: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13241: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13242: 
13243: Inputs:
13244: defmail (scalar - email address of default recipient),
13245: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13246: requestsmail, updatesmail, or idconflictsmail).
13247: 
13248: defdom (domain for which to retrieve configuration settings),
13249: 
13250: origmail (scalar - email address of recipient from loncapa.conf,
13251: i.e., predates configuration by DC via domainprefs.pm
13252: 
13253: Returns: comma separated list of addresses to which to send e-mail.
13254: 
13255: =back
13256: 
13257: =cut
13258: 
13259: ############################################################
13260: ############################################################
13261: sub build_recipient_list {
13262:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13263:     my @recipients;
13264:     my $otheremails;
13265:     my %domconfig =
13266:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13267:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13268:         if (exists($domconfig{'contacts'}{$mailing})) {
13269:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13270:                 my @contacts = ('adminemail','supportemail');
13271:                 foreach my $item (@contacts) {
13272:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13273:                         my $addr = $domconfig{'contacts'}{$item}; 
13274:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13275:                             push(@recipients,$addr);
13276:                         }
13277:                     }
13278:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13279:                 }
13280:             }
13281:         } elsif ($origmail ne '') {
13282:             push(@recipients,$origmail);
13283:         }
13284:     } elsif ($origmail ne '') {
13285:         push(@recipients,$origmail);
13286:     }
13287:     if (defined($defmail)) {
13288:         if ($defmail ne '') {
13289:             push(@recipients,$defmail);
13290:         }
13291:     }
13292:     if ($otheremails) {
13293:         my @others;
13294:         if ($otheremails =~ /,/) {
13295:             @others = split(/,/,$otheremails);
13296:         } else {
13297:             push(@others,$otheremails);
13298:         }
13299:         foreach my $addr (@others) {
13300:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13301:                 push(@recipients,$addr);
13302:             }
13303:         }
13304:     }
13305:     my $recipientlist = join(',',@recipients); 
13306:     return $recipientlist;
13307: }
13308: 
13309: ############################################################
13310: ############################################################
13311: 
13312: =pod
13313: 
13314: =head1 Course Catalog Routines
13315: 
13316: =over 4
13317: 
13318: =item * &gather_categories()
13319: 
13320: Converts category definitions - keys of categories hash stored in  
13321: coursecategories in configuration.db on the primary library server in a 
13322: domain - to an array.  Also generates javascript and idx hash used to 
13323: generate Domain Coordinator interface for editing Course Categories.
13324: 
13325: Inputs:
13326: 
13327: categories (reference to hash of category definitions).
13328: 
13329: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13330:       categories and subcategories).
13331: 
13332: idx (reference to hash of counters used in Domain Coordinator interface for 
13333:       editing Course Categories).
13334: 
13335: jsarray (reference to array of categories used to create Javascript arrays for
13336:          Domain Coordinator interface for editing Course Categories).
13337: 
13338: Returns: nothing
13339: 
13340: Side effects: populates cats, idx and jsarray. 
13341: 
13342: =cut
13343: 
13344: sub gather_categories {
13345:     my ($categories,$cats,$idx,$jsarray) = @_;
13346:     my %counters;
13347:     my $num = 0;
13348:     foreach my $item (keys(%{$categories})) {
13349:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13350:         if ($container eq '' && $depth == 0) {
13351:             $cats->[$depth][$categories->{$item}] = $cat;
13352:         } else {
13353:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13354:         }
13355:         my ($escitem,$tail) = split(/:/,$item,2);
13356:         if ($counters{$tail} eq '') {
13357:             $counters{$tail} = $num;
13358:             $num ++;
13359:         }
13360:         if (ref($idx) eq 'HASH') {
13361:             $idx->{$item} = $counters{$tail};
13362:         }
13363:         if (ref($jsarray) eq 'ARRAY') {
13364:             push(@{$jsarray->[$counters{$tail}]},$item);
13365:         }
13366:     }
13367:     return;
13368: }
13369: 
13370: =pod
13371: 
13372: =item * &extract_categories()
13373: 
13374: Used to generate breadcrumb trails for course categories.
13375: 
13376: Inputs:
13377: 
13378: categories (reference to hash of category definitions).
13379: 
13380: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13381:       categories and subcategories).
13382: 
13383: trails (reference to array of breacrumb trails for each category).
13384: 
13385: allitems (reference to hash - key is category key 
13386:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13387: 
13388: idx (reference to hash of counters used in Domain Coordinator interface for
13389:       editing Course Categories).
13390: 
13391: jsarray (reference to array of categories used to create Javascript arrays for
13392:          Domain Coordinator interface for editing Course Categories).
13393: 
13394: subcats (reference to hash of arrays containing all subcategories within each 
13395:          category, -recursive)
13396: 
13397: Returns: nothing
13398: 
13399: Side effects: populates trails and allitems hash references.
13400: 
13401: =cut
13402: 
13403: sub extract_categories {
13404:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13405:     if (ref($categories) eq 'HASH') {
13406:         &gather_categories($categories,$cats,$idx,$jsarray);
13407:         if (ref($cats->[0]) eq 'ARRAY') {
13408:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13409:                 my $name = $cats->[0][$i];
13410:                 my $item = &escape($name).'::0';
13411:                 my $trailstr;
13412:                 if ($name eq 'instcode') {
13413:                     $trailstr = &mt('Official courses (with institutional codes)');
13414:                 } elsif ($name eq 'communities') {
13415:                     $trailstr = &mt('Communities');
13416:                 } else {
13417:                     $trailstr = $name;
13418:                 }
13419:                 if ($allitems->{$item} eq '') {
13420:                     push(@{$trails},$trailstr);
13421:                     $allitems->{$item} = scalar(@{$trails})-1;
13422:                 }
13423:                 my @parents = ($name);
13424:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13425:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13426:                         my $category = $cats->[1]{$name}[$j];
13427:                         if (ref($subcats) eq 'HASH') {
13428:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13429:                         }
13430:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13431:                     }
13432:                 } else {
13433:                     if (ref($subcats) eq 'HASH') {
13434:                         $subcats->{$item} = [];
13435:                     }
13436:                 }
13437:             }
13438:         }
13439:     }
13440:     return;
13441: }
13442: 
13443: =pod
13444: 
13445: =item * &recurse_categories()
13446: 
13447: Recursively used to generate breadcrumb trails for course categories.
13448: 
13449: Inputs:
13450: 
13451: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13452:       categories and subcategories).
13453: 
13454: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13455: 
13456: category (current course category, for which breadcrumb trail is being generated).
13457: 
13458: trails (reference to array of breadcrumb trails for each category).
13459: 
13460: allitems (reference to hash - key is category key
13461:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13462: 
13463: parents (array containing containers directories for current category, 
13464:          back to top level). 
13465: 
13466: Returns: nothing
13467: 
13468: Side effects: populates trails and allitems hash references
13469: 
13470: =cut
13471: 
13472: sub recurse_categories {
13473:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13474:     my $shallower = $depth - 1;
13475:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13476:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13477:             my $name = $cats->[$depth]{$category}[$k];
13478:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13479:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13480:             if ($allitems->{$item} eq '') {
13481:                 push(@{$trails},$trailstr);
13482:                 $allitems->{$item} = scalar(@{$trails})-1;
13483:             }
13484:             my $deeper = $depth+1;
13485:             push(@{$parents},$category);
13486:             if (ref($subcats) eq 'HASH') {
13487:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13488:                 for (my $j=@{$parents}; $j>=0; $j--) {
13489:                     my $higher;
13490:                     if ($j > 0) {
13491:                         $higher = &escape($parents->[$j]).':'.
13492:                                   &escape($parents->[$j-1]).':'.$j;
13493:                     } else {
13494:                         $higher = &escape($parents->[$j]).'::'.$j;
13495:                     }
13496:                     push(@{$subcats->{$higher}},$subcat);
13497:                 }
13498:             }
13499:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13500:                                 $subcats);
13501:             pop(@{$parents});
13502:         }
13503:     } else {
13504:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13505:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13506:         if ($allitems->{$item} eq '') {
13507:             push(@{$trails},$trailstr);
13508:             $allitems->{$item} = scalar(@{$trails})-1;
13509:         }
13510:     }
13511:     return;
13512: }
13513: 
13514: =pod
13515: 
13516: =item * &assign_categories_table()
13517: 
13518: Create a datatable for display of hierarchical categories in a domain,
13519: with checkboxes to allow a course to be categorized. 
13520: 
13521: Inputs:
13522: 
13523: cathash - reference to hash of categories defined for the domain (from
13524:           configuration.db)
13525: 
13526: currcat - scalar with an & separated list of categories assigned to a course. 
13527: 
13528: type    - scalar contains course type (Course or Community).
13529: 
13530: Returns: $output (markup to be displayed) 
13531: 
13532: =cut
13533: 
13534: sub assign_categories_table {
13535:     my ($cathash,$currcat,$type) = @_;
13536:     my $output;
13537:     if (ref($cathash) eq 'HASH') {
13538:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13539:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13540:         $maxdepth = scalar(@cats);
13541:         if (@cats > 0) {
13542:             my $itemcount = 0;
13543:             if (ref($cats[0]) eq 'ARRAY') {
13544:                 my @currcategories;
13545:                 if ($currcat ne '') {
13546:                     @currcategories = split('&',$currcat);
13547:                 }
13548:                 my $table;
13549:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13550:                     my $parent = $cats[0][$i];
13551:                     next if ($parent eq 'instcode');
13552:                     if ($type eq 'Community') {
13553:                         next unless ($parent eq 'communities');
13554:                     } else {
13555:                         next if ($parent eq 'communities');
13556:                     }
13557:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13558:                     my $item = &escape($parent).'::0';
13559:                     my $checked = '';
13560:                     if (@currcategories > 0) {
13561:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13562:                             $checked = ' checked="checked"';
13563:                         }
13564:                     }
13565:                     my $parent_title = $parent;
13566:                     if ($parent eq 'communities') {
13567:                         $parent_title = &mt('Communities');
13568:                     }
13569:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13570:                               '<input type="checkbox" name="usecategory" value="'.
13571:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13572:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13573:                     my $depth = 1;
13574:                     push(@path,$parent);
13575:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13576:                     pop(@path);
13577:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13578:                     $itemcount ++;
13579:                 }
13580:                 if ($itemcount) {
13581:                     $output = &Apache::loncommon::start_data_table().
13582:                               $table.
13583:                               &Apache::loncommon::end_data_table();
13584:                 }
13585:             }
13586:         }
13587:     }
13588:     return $output;
13589: }
13590: 
13591: =pod
13592: 
13593: =item * &assign_category_rows()
13594: 
13595: Create a datatable row for display of nested categories in a domain,
13596: with checkboxes to allow a course to be categorized,called recursively.
13597: 
13598: Inputs:
13599: 
13600: itemcount - track row number for alternating colors
13601: 
13602: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13603:       categories and subcategories.
13604: 
13605: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13606: 
13607: parent - parent of current category item
13608: 
13609: path - Array containing all categories back up through the hierarchy from the
13610:        current category to the top level.
13611: 
13612: currcategories - reference to array of current categories assigned to the course
13613: 
13614: Returns: $output (markup to be displayed).
13615: 
13616: =cut
13617: 
13618: sub assign_category_rows {
13619:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13620:     my ($text,$name,$item,$chgstr);
13621:     if (ref($cats) eq 'ARRAY') {
13622:         my $maxdepth = scalar(@{$cats});
13623:         if (ref($cats->[$depth]) eq 'HASH') {
13624:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13625:                 my $numchildren = @{$cats->[$depth]{$parent}};
13626:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13627:                 $text .= '<td><table class="LC_data_table">';
13628:                 for (my $j=0; $j<$numchildren; $j++) {
13629:                     $name = $cats->[$depth]{$parent}[$j];
13630:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13631:                     my $deeper = $depth+1;
13632:                     my $checked = '';
13633:                     if (ref($currcategories) eq 'ARRAY') {
13634:                         if (@{$currcategories} > 0) {
13635:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13636:                                 $checked = ' checked="checked"';
13637:                             }
13638:                         }
13639:                     }
13640:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13641:                              '<input type="checkbox" name="usecategory" value="'.
13642:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13643:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13644:                              '</td><td>';
13645:                     if (ref($path) eq 'ARRAY') {
13646:                         push(@{$path},$name);
13647:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13648:                         pop(@{$path});
13649:                     }
13650:                     $text .= '</td></tr>';
13651:                 }
13652:                 $text .= '</table></td>';
13653:             }
13654:         }
13655:     }
13656:     return $text;
13657: }
13658: 
13659: ############################################################
13660: ############################################################
13661: 
13662: 
13663: sub commit_customrole {
13664:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13665:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13666:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13667:                          ($end?', ending '.localtime($end):'').': <b>'.
13668:               &Apache::lonnet::assigncustomrole(
13669:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13670:                  '</b><br />';
13671:     return $output;
13672: }
13673: 
13674: sub commit_standardrole {
13675:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13676:     my ($output,$logmsg,$linefeed);
13677:     if ($context eq 'auto') {
13678:         $linefeed = "\n";
13679:     } else {
13680:         $linefeed = "<br />\n";
13681:     }  
13682:     if ($three eq 'st') {
13683:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13684:                                          $one,$two,$sec,$context,$credits);
13685:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13686:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13687:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13688:         } else {
13689:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13690:                ($start?', '.&mt('starting').' '.localtime($start):'').
13691:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13692:             if ($context eq 'auto') {
13693:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13694:             } else {
13695:                $output .= '<b>'.$result.'</b>'.$linefeed.
13696:                &mt('Add to classlist').': <b>ok</b>';
13697:             }
13698:             $output .= $linefeed;
13699:         }
13700:     } else {
13701:         $output = &mt('Assigning').' '.$three.' in '.$url.
13702:                ($start?', '.&mt('starting').' '.localtime($start):'').
13703:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13704:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13705:         if ($context eq 'auto') {
13706:             $output .= $result.$linefeed;
13707:         } else {
13708:             $output .= '<b>'.$result.'</b>'.$linefeed;
13709:         }
13710:     }
13711:     return $output;
13712: }
13713: 
13714: sub commit_studentrole {
13715:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13716:         $credits) = @_;
13717:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13718:     if ($context eq 'auto') {
13719:         $linefeed = "\n";
13720:     } else {
13721:         $linefeed = '<br />'."\n";
13722:     }
13723:     if (defined($one) && defined($two)) {
13724:         my $cid=$one.'_'.$two;
13725:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13726:         my $secchange = 0;
13727:         my $expire_role_result;
13728:         my $modify_section_result;
13729:         if ($oldsec ne '-1') { 
13730:             if ($oldsec ne $sec) {
13731:                 $secchange = 1;
13732:                 my $now = time;
13733:                 my $uurl='/'.$cid;
13734:                 $uurl=~s/\_/\//g;
13735:                 if ($oldsec) {
13736:                     $uurl.='/'.$oldsec;
13737:                 }
13738:                 $oldsecurl = $uurl;
13739:                 $expire_role_result = 
13740:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13741:                 if ($env{'request.course.sec'} ne '') { 
13742:                     if ($expire_role_result eq 'refused') {
13743:                         my @roles = ('st');
13744:                         my @statuses = ('previous');
13745:                         my @roledoms = ($one);
13746:                         my $withsec = 1;
13747:                         my %roleshash = 
13748:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13749:                                               \@statuses,\@roles,\@roledoms,$withsec);
13750:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13751:                             my ($oldstart,$oldend) = 
13752:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13753:                             if ($oldend > 0 && $oldend <= $now) {
13754:                                 $expire_role_result = 'ok';
13755:                             }
13756:                         }
13757:                     }
13758:                 }
13759:                 $result = $expire_role_result;
13760:             }
13761:         }
13762:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13763:             $modify_section_result = 
13764:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13765:                                                            undef,undef,undef,$sec,
13766:                                                            $end,$start,'','',$cid,
13767:                                                            '',$context,$credits);
13768:             if ($modify_section_result =~ /^ok/) {
13769:                 if ($secchange == 1) {
13770:                     if ($sec eq '') {
13771:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13772:                     } else {
13773:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13774:                     }
13775:                 } elsif ($oldsec eq '-1') {
13776:                     if ($sec eq '') {
13777:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13778:                     } else {
13779:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13780:                     }
13781:                 } else {
13782:                     if ($sec eq '') {
13783:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13784:                     } else {
13785:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13786:                     }
13787:                 }
13788:             } else {
13789:                 if ($secchange) {       
13790:                     $$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;
13791:                 } else {
13792:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13793:                 }
13794:             }
13795:             $result = $modify_section_result;
13796:         } elsif ($secchange == 1) {
13797:             if ($oldsec eq '') {
13798:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13799:             } else {
13800:                 $$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;
13801:             }
13802:             if ($expire_role_result eq 'refused') {
13803:                 my $newsecurl = '/'.$cid;
13804:                 $newsecurl =~ s/\_/\//g;
13805:                 if ($sec ne '') {
13806:                     $newsecurl.='/'.$sec;
13807:                 }
13808:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13809:                     if ($sec eq '') {
13810:                         $$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;
13811:                     } else {
13812:                         $$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;
13813:                     }
13814:                 }
13815:             }
13816:         }
13817:     } else {
13818:         $$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;
13819:         $result = "error: incomplete course id\n";
13820:     }
13821:     return $result;
13822: }
13823: 
13824: sub show_role_extent {
13825:     my ($scope,$context,$role) = @_;
13826:     $scope =~ s{^/}{};
13827:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13828:     push(@courseroles,'co');
13829:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13830:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13831:         $scope =~ s{/}{_};
13832:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13833:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13834:         my ($audom,$auname) = split(/\//,$scope);
13835:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13836:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13837:     } else {
13838:         $scope =~ s{/$}{};
13839:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13840:                    &Apache::lonnet::domain($scope,'description').'</span>');
13841:     }
13842: }
13843: 
13844: ############################################################
13845: ############################################################
13846: 
13847: sub check_clone {
13848:     my ($args,$linefeed) = @_;
13849:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13850:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13851:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13852:     my $clonemsg;
13853:     my $can_clone = 0;
13854:     my $lctype = lc($args->{'crstype'});
13855:     if ($lctype ne 'community') {
13856:         $lctype = 'course';
13857:     }
13858:     if ($clonehome eq 'no_host') {
13859:         if ($args->{'crstype'} eq 'Community') {
13860:             $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'});
13861:         } else {
13862:             $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'});
13863:         }     
13864:     } else {
13865: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13866:         if ($args->{'crstype'} eq 'Community') {
13867:             if ($clonedesc{'type'} ne 'Community') {
13868:                  $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'});
13869:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13870:             }
13871:         }
13872: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13873:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13874: 	    $can_clone = 1;
13875: 	} else {
13876: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13877: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13878: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13879:             if (grep(/^\*$/,@cloners)) {
13880:                 $can_clone = 1;
13881:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13882:                 $can_clone = 1;
13883:             } else {
13884:                 my $ccrole = 'cc';
13885:                 if ($args->{'crstype'} eq 'Community') {
13886:                     $ccrole = 'co';
13887:                 }
13888: 	        my %roleshash =
13889: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13890: 					 $args->{'ccdomain'},
13891:                                          'userroles',['active'],[$ccrole],
13892: 					 [$args->{'clonedomain'}]);
13893: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13894:                     $can_clone = 1;
13895:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13896:                     $can_clone = 1;
13897:                 } else {
13898:                     if ($args->{'crstype'} eq 'Community') {
13899:                         $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'});
13900:                     } else {
13901:                         $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'});
13902:                     }
13903: 	        }
13904: 	    }
13905:         }
13906:     }
13907:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13908: }
13909: 
13910: sub construct_course {
13911:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
13912:     my $outcome;
13913:     my $linefeed =  '<br />'."\n";
13914:     if ($context eq 'auto') {
13915:         $linefeed = "\n";
13916:     }
13917: 
13918: #
13919: # Are we cloning?
13920: #
13921:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13922:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13923: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13924: 	if ($context ne 'auto') {
13925:             if ($clonemsg ne '') {
13926: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13927:             }
13928: 	}
13929: 	$outcome .= $clonemsg.$linefeed;
13930: 
13931:         if (!$can_clone) {
13932: 	    return (0,$outcome);
13933: 	}
13934:     }
13935: 
13936: #
13937: # Open course
13938: #
13939:     my $crstype = lc($args->{'crstype'});
13940:     my %cenv=();
13941:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13942:                                              $args->{'cdescr'},
13943:                                              $args->{'curl'},
13944:                                              $args->{'course_home'},
13945:                                              $args->{'nonstandard'},
13946:                                              $args->{'crscode'},
13947:                                              $args->{'ccuname'}.':'.
13948:                                              $args->{'ccdomain'},
13949:                                              $args->{'crstype'},
13950:                                              $cnum,$context,$category);
13951: 
13952:     # Note: The testing routines depend on this being output; see 
13953:     # Utils::Course. This needs to at least be output as a comment
13954:     # if anyone ever decides to not show this, and Utils::Course::new
13955:     # will need to be suitably modified.
13956:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13957:     if ($$courseid =~ /^error:/) {
13958:         return (0,$outcome);
13959:     }
13960: 
13961: #
13962: # Check if created correctly
13963: #
13964:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13965:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13966:     if ($crsuhome eq 'no_host') {
13967:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13968:         return (0,$outcome);
13969:     }
13970:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13971: 
13972: #
13973: # Do the cloning
13974: #   
13975:     if ($can_clone && $cloneid) {
13976: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13977: 	if ($context ne 'auto') {
13978: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13979: 	}
13980: 	$outcome .= $clonemsg.$linefeed;
13981: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13982: # Copy all files
13983: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13984: # Restore URL
13985: 	$cenv{'url'}=$oldcenv{'url'};
13986: # Restore title
13987: 	$cenv{'description'}=$oldcenv{'description'};
13988: # Restore creation date, creator and creation context.
13989:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13990:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13991:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13992: # Mark as cloned
13993: 	$cenv{'clonedfrom'}=$cloneid;
13994: # Need to clone grading mode
13995:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13996:         $cenv{'grading'}=$newenv{'grading'};
13997: # Do not clone these environment entries
13998:         &Apache::lonnet::del('environment',
13999:                   ['default_enrollment_start_date',
14000:                    'default_enrollment_end_date',
14001:                    'question.email',
14002:                    'policy.email',
14003:                    'comment.email',
14004:                    'pch.users.denied',
14005:                    'plc.users.denied',
14006:                    'hidefromcat',
14007:                    'checkforpriv',
14008:                    'categories',
14009:                    'internal.uniquecode'],
14010:                    $$crsudom,$$crsunum);
14011:         if ($args->{'textbook'}) {
14012:             $cenv{'internal.textbook'} = $args->{'textbook'};
14013:         }
14014:     }
14015: 
14016: #
14017: # Set environment (will override cloned, if existing)
14018: #
14019:     my @sections = ();
14020:     my @xlists = ();
14021:     if ($args->{'crstype'}) {
14022:         $cenv{'type'}=$args->{'crstype'};
14023:     }
14024:     if ($args->{'crsid'}) {
14025:         $cenv{'courseid'}=$args->{'crsid'};
14026:     }
14027:     if ($args->{'crscode'}) {
14028:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14029:     }
14030:     if ($args->{'crsquota'} ne '') {
14031:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14032:     } else {
14033:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14034:     }
14035:     if ($args->{'ccuname'}) {
14036:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14037:                                         ':'.$args->{'ccdomain'};
14038:     } else {
14039:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14040:     }
14041:     if ($args->{'defaultcredits'}) {
14042:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14043:     }
14044:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14045:     if ($args->{'crssections'}) {
14046:         $cenv{'internal.sectionnums'} = '';
14047:         if ($args->{'crssections'} =~ m/,/) {
14048:             @sections = split/,/,$args->{'crssections'};
14049:         } else {
14050:             $sections[0] = $args->{'crssections'};
14051:         }
14052:         if (@sections > 0) {
14053:             foreach my $item (@sections) {
14054:                 my ($sec,$gp) = split/:/,$item;
14055:                 my $class = $args->{'crscode'}.$sec;
14056:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14057:                 $cenv{'internal.sectionnums'} .= $item.',';
14058:                 unless ($addcheck eq 'ok') {
14059:                     push @badclasses, $class;
14060:                 }
14061:             }
14062:             $cenv{'internal.sectionnums'} =~ s/,$//;
14063:         }
14064:     }
14065: # do not hide course coordinator from staff listing, 
14066: # even if privileged
14067:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14068: # add course coordinator's domain to domains to check for privileged users
14069: # if different to course domain
14070:     if ($$crsudom ne $args->{'ccdomain'}) {
14071:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14072:     }
14073: # add crosslistings
14074:     if ($args->{'crsxlist'}) {
14075:         $cenv{'internal.crosslistings'}='';
14076:         if ($args->{'crsxlist'} =~ m/,/) {
14077:             @xlists = split/,/,$args->{'crsxlist'};
14078:         } else {
14079:             $xlists[0] = $args->{'crsxlist'};
14080:         }
14081:         if (@xlists > 0) {
14082:             foreach my $item (@xlists) {
14083:                 my ($xl,$gp) = split/:/,$item;
14084:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14085:                 $cenv{'internal.crosslistings'} .= $item.',';
14086:                 unless ($addcheck eq 'ok') {
14087:                     push @badclasses, $xl;
14088:                 }
14089:             }
14090:             $cenv{'internal.crosslistings'} =~ s/,$//;
14091:         }
14092:     }
14093:     if ($args->{'autoadds'}) {
14094:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14095:     }
14096:     if ($args->{'autodrops'}) {
14097:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14098:     }
14099: # check for notification of enrollment changes
14100:     my @notified = ();
14101:     if ($args->{'notify_owner'}) {
14102:         if ($args->{'ccuname'} ne '') {
14103:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14104:         }
14105:     }
14106:     if ($args->{'notify_dc'}) {
14107:         if ($uname ne '') { 
14108:             push(@notified,$uname.':'.$udom);
14109:         }
14110:     }
14111:     if (@notified > 0) {
14112:         my $notifylist;
14113:         if (@notified > 1) {
14114:             $notifylist = join(',',@notified);
14115:         } else {
14116:             $notifylist = $notified[0];
14117:         }
14118:         $cenv{'internal.notifylist'} = $notifylist;
14119:     }
14120:     if (@badclasses > 0) {
14121:         my %lt=&Apache::lonlocal::texthash(
14122:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
14123:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14124:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14125:         );
14126:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14127:                            ' ('.$lt{'adby'}.')';
14128:         if ($context eq 'auto') {
14129:             $outcome .= $badclass_msg.$linefeed;
14130:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14131:             foreach my $item (@badclasses) {
14132:                 if ($context eq 'auto') {
14133:                     $outcome .= " - $item\n";
14134:                 } else {
14135:                     $outcome .= "<li>$item</li>\n";
14136:                 }
14137:             }
14138:             if ($context eq 'auto') {
14139:                 $outcome .= $linefeed;
14140:             } else {
14141:                 $outcome .= "</ul><br /><br /></div>\n";
14142:             }
14143:         } 
14144:     }
14145:     if ($args->{'no_end_date'}) {
14146:         $args->{'endaccess'} = 0;
14147:     }
14148:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14149:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14150:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14151:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14152:     if ($args->{'showphotos'}) {
14153:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14154:     }
14155:     $cenv{'internal.authtype'} = $args->{'authtype'};
14156:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14157:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14158:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14159:             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'); 
14160:             if ($context eq 'auto') {
14161:                 $outcome .= $krb_msg;
14162:             } else {
14163:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14164:             }
14165:             $outcome .= $linefeed;
14166:         }
14167:     }
14168:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14169:        if ($args->{'setpolicy'}) {
14170:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14171:        }
14172:        if ($args->{'setcontent'}) {
14173:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14174:        }
14175:     }
14176:     if ($args->{'reshome'}) {
14177: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14178: 	$cenv{'reshome'}=~s/\/+$/\//;
14179:     }
14180: #
14181: # course has keyed access
14182: #
14183:     if ($args->{'setkeys'}) {
14184:        $cenv{'keyaccess'}='yes';
14185:     }
14186: # if specified, key authority is not course, but user
14187: # only active if keyaccess is yes
14188:     if ($args->{'keyauth'}) {
14189: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14190: 	$user = &LONCAPA::clean_username($user);
14191: 	$domain = &LONCAPA::clean_username($domain);
14192: 	if ($user ne '' && $domain ne '') {
14193: 	    $cenv{'keyauth'}=$user.':'.$domain;
14194: 	}
14195:     }
14196: 
14197: #
14198: #  generate and store uniquecode (available to course requester), if course should have one.
14199: #
14200:     if ($args->{'uniquecode'}) {
14201:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14202:         if ($code) {
14203:             $cenv{'internal.uniquecode'} = $code;
14204:             my %crsinfo =
14205:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14206:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14207:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14208:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14209:             }
14210:             if (ref($coderef)) {
14211:                 $$coderef = $code;
14212:             }
14213:         }
14214:     }
14215: 
14216:     if ($args->{'disresdis'}) {
14217:         $cenv{'pch.roles.denied'}='st';
14218:     }
14219:     if ($args->{'disablechat'}) {
14220:         $cenv{'plc.roles.denied'}='st';
14221:     }
14222: 
14223:     # Record we've not yet viewed the Course Initialization Helper for this 
14224:     # course
14225:     $cenv{'course.helper.not.run'} = 1;
14226:     #
14227:     # Use new Randomseed
14228:     #
14229:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14230:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14231:     #
14232:     # The encryption code and receipt prefix for this course
14233:     #
14234:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14235:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14236:     #
14237:     # By default, use standard grading
14238:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14239: 
14240:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14241:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14242: #
14243: # Open all assignments
14244: #
14245:     if ($args->{'openall'}) {
14246:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14247:        my %storecontent = ($storeunder         => time,
14248:                            $storeunder.'.type' => 'date_start');
14249:        
14250:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14251:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14252:    }
14253: #
14254: # Set first page
14255: #
14256:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14257: 	    || ($cloneid)) {
14258: 	use LONCAPA::map;
14259: 	$outcome .= &mt('Setting first resource').': ';
14260: 
14261: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14262:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14263: 
14264:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14265:         my $title; my $url;
14266:         if ($args->{'firstres'} eq 'syl') {
14267: 	    $title=&mt('Syllabus');
14268:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14269:         } else {
14270:             $title=&mt('Table of Contents');
14271:             $url='/adm/navmaps';
14272:         }
14273: 
14274:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14275: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14276: 
14277: 	if ($errtext) { $fatal=2; }
14278:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14279:     }
14280: 
14281:     return (1,$outcome);
14282: }
14283: 
14284: sub make_unique_code {
14285:     my ($cdom,$cnum) = @_;
14286:     # get lock on uniquecodes db
14287:     my $lockhash = {
14288:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
14289:                                                   ':'.$env{'user.domain'},
14290:                    };
14291:     my $tries = 0;
14292:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14293:     my ($code,$error);
14294: 
14295:     while (($gotlock ne 'ok') && ($tries<3)) {
14296:         $tries ++;
14297:         sleep 1;
14298:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14299:     }
14300:     if ($gotlock eq 'ok') {
14301:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14302:         my $gotcode;
14303:         my $attempts = 0;
14304:         while ((!$gotcode) && ($attempts < 100)) {
14305:             $code = &generate_code();
14306:             if (!exists($currcodes{$code})) {
14307:                 $gotcode = 1;
14308:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14309:                     $error = 'nostore';
14310:                 }
14311:             }
14312:             $attempts ++;
14313:         }
14314:         my @del_lock = ($cnum."\0".'uniquecodes');
14315:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14316:     } else {
14317:         $error = 'nolock';
14318:     }
14319:     return ($code,$error);
14320: }
14321: 
14322: sub generate_code {
14323:     my $code;
14324:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14325:     for (my $i=0; $i<6; $i++) {
14326:         my $lettnum = int (rand 2);
14327:         my $item = '';
14328:         if ($lettnum) {
14329:             $item = $letts[int( rand(18) )];
14330:         } else {
14331:             $item = 1+int( rand(8) );
14332:         }
14333:         $code .= $item;
14334:     }
14335:     return $code;
14336: }
14337: 
14338: ############################################################
14339: ############################################################
14340: 
14341: #SD
14342: # only Community and Course, or anything else?
14343: sub course_type {
14344:     my ($cid) = @_;
14345:     if (!defined($cid)) {
14346:         $cid = $env{'request.course.id'};
14347:     }
14348:     if (defined($env{'course.'.$cid.'.type'})) {
14349:         return $env{'course.'.$cid.'.type'};
14350:     } else {
14351:         return 'Course';
14352:     }
14353: }
14354: 
14355: sub group_term {
14356:     my $crstype = &course_type();
14357:     my %names = (
14358:                   'Course' => 'group',
14359:                   'Community' => 'group',
14360:                 );
14361:     return $names{$crstype};
14362: }
14363: 
14364: sub course_types {
14365:     my @types = ('official','unofficial','community','textbook');
14366:     my %typename = (
14367:                          official   => 'Official course',
14368:                          unofficial => 'Unofficial course',
14369:                          community  => 'Community',
14370:                          textbook   => 'Textbook course',
14371:                    );
14372:     return (\@types,\%typename);
14373: }
14374: 
14375: sub icon {
14376:     my ($file)=@_;
14377:     my $curfext = lc((split(/\./,$file))[-1]);
14378:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14379:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14380:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14381: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14382: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14383: 	            $curfext.".gif") {
14384: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14385: 		$curfext.".gif";
14386: 	}
14387:     }
14388:     return &lonhttpdurl($iconname);
14389: } 
14390: 
14391: sub lonhttpdurl {
14392: #
14393: # Had been used for "small fry" static images on separate port 8080.
14394: # Modify here if lightweight http functionality desired again.
14395: # Currently eliminated due to increasing firewall issues.
14396: #
14397:     my ($url)=@_;
14398:     return $url;
14399: }
14400: 
14401: sub connection_aborted {
14402:     my ($r)=@_;
14403:     $r->print(" ");$r->rflush();
14404:     my $c = $r->connection;
14405:     return $c->aborted();
14406: }
14407: 
14408: #    Escapes strings that may have embedded 's that will be put into
14409: #    strings as 'strings'.
14410: sub escape_single {
14411:     my ($input) = @_;
14412:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14413:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14414:     return $input;
14415: }
14416: 
14417: #  Same as escape_single, but escape's "'s  This 
14418: #  can be used for  "strings"
14419: sub escape_double {
14420:     my ($input) = @_;
14421:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14422:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14423:     return $input;
14424: }
14425:  
14426: #   Escapes the last element of a full URL.
14427: sub escape_url {
14428:     my ($url)   = @_;
14429:     my @urlslices = split(/\//, $url,-1);
14430:     my $lastitem = &escape(pop(@urlslices));
14431:     return join('/',@urlslices).'/'.$lastitem;
14432: }
14433: 
14434: sub compare_arrays {
14435:     my ($arrayref1,$arrayref2) = @_;
14436:     my (@difference,%count);
14437:     @difference = ();
14438:     %count = ();
14439:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14440:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14441:         foreach my $element (keys(%count)) {
14442:             if ($count{$element} == 1) {
14443:                 push(@difference,$element);
14444:             }
14445:         }
14446:     }
14447:     return @difference;
14448: }
14449: 
14450: # -------------------------------------------------------- Initialize user login
14451: sub init_user_environment {
14452:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14453:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14454: 
14455:     my $public=($username eq 'public' && $domain eq 'public');
14456: 
14457: # See if old ID present, if so, remove
14458: 
14459:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14460:     my $now=time;
14461: 
14462:     if ($public) {
14463: 	my $max_public=100;
14464: 	my $oldest;
14465: 	my $oldest_time=0;
14466: 	for(my $next=1;$next<=$max_public;$next++) {
14467: 	    if (-e $lonids."/publicuser_$next.id") {
14468: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14469: 		if ($mtime<$oldest_time || !$oldest_time) {
14470: 		    $oldest_time=$mtime;
14471: 		    $oldest=$next;
14472: 		}
14473: 	    } else {
14474: 		$cookie="publicuser_$next";
14475: 		last;
14476: 	    }
14477: 	}
14478: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14479:     } else {
14480: 	# if this isn't a robot, kill any existing non-robot sessions
14481: 	if (!$args->{'robot'}) {
14482: 	    opendir(DIR,$lonids);
14483: 	    while ($filename=readdir(DIR)) {
14484: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14485: 		    unlink($lonids.'/'.$filename);
14486: 		}
14487: 	    }
14488: 	    closedir(DIR);
14489: 	}
14490: # Give them a new cookie
14491: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14492: 		                   : $now.$$.int(rand(10000)));
14493: 	$cookie="$username\_$id\_$domain\_$authhost";
14494:     
14495: # Initialize roles
14496: 
14497: 	($userroles,$firstaccenv,$timerintenv) = 
14498:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14499:     }
14500: # ------------------------------------ Check browser type and MathML capability
14501: 
14502:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14503:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14504: 
14505: # ------------------------------------------------------------- Get environment
14506: 
14507:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14508:     my ($tmp) = keys(%userenv);
14509:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14510:     } else {
14511: 	undef(%userenv);
14512:     }
14513:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14514: 	$form->{'interface'}=$userenv{'interface'};
14515:     }
14516:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14517: 
14518: # --------------- Do not trust query string to be put directly into environment
14519:     foreach my $option ('interface','localpath','localres') {
14520:         $form->{$option}=~s/[\n\r\=]//gs;
14521:     }
14522: # --------------------------------------------------------- Write first profile
14523: 
14524:     {
14525: 	my %initial_env = 
14526: 	    ("user.name"          => $username,
14527: 	     "user.domain"        => $domain,
14528: 	     "user.home"          => $authhost,
14529: 	     "browser.type"       => $clientbrowser,
14530: 	     "browser.version"    => $clientversion,
14531: 	     "browser.mathml"     => $clientmathml,
14532: 	     "browser.unicode"    => $clientunicode,
14533: 	     "browser.os"         => $clientos,
14534:              "browser.mobile"     => $clientmobile,
14535:              "browser.info"       => $clientinfo,
14536: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14537: 	     "request.course.fn"  => '',
14538: 	     "request.course.uri" => '',
14539: 	     "request.course.sec" => '',
14540: 	     "request.role"       => 'cm',
14541: 	     "request.role.adv"   => $env{'user.adv'},
14542: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14543: 
14544:         if ($form->{'localpath'}) {
14545: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14546: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14547:         }
14548: 	
14549: 	if ($form->{'interface'}) {
14550: 	    $form->{'interface'}=~s/\W//gs;
14551: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14552: 	    $env{'browser.interface'}=$form->{'interface'};
14553: 	}
14554: 
14555:         if ($form->{'iptoken'}) {
14556:             my $lonhost = $r->dir_config('lonHostID');
14557:             $initial_env{"user.noloadbalance"} = $lonhost;
14558:             $env{'user.noloadbalance'} = $lonhost;
14559:         }
14560: 
14561:         my %is_adv = ( is_adv => $env{'user.adv'} );
14562:         my %domdef;
14563:         unless ($domain eq 'public') {
14564:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14565:         }
14566: 
14567:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14568:             $userenv{'availabletools.'.$tool} = 
14569:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14570:                                                   undef,\%userenv,\%domdef,\%is_adv);
14571:         }
14572: 
14573:         foreach my $crstype ('official','unofficial','community','textbook') {
14574:             $userenv{'canrequest.'.$crstype} =
14575:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14576:                                                   'reload','requestcourses',
14577:                                                   \%userenv,\%domdef,\%is_adv);
14578:         }
14579: 
14580:         $userenv{'canrequest.author'} =
14581:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14582:                                         'reload','requestauthor',
14583:                                         \%userenv,\%domdef,\%is_adv);
14584:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14585:                                              $domain,$username);
14586:         my $reqstatus = $reqauthor{'author_status'};
14587:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14588:             if (ref($reqauthor{'author'}) eq 'HASH') {
14589:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14590:                                                   $reqauthor{'author'}{'timestamp'};
14591:             }
14592:         }
14593: 
14594: 	$env{'user.environment'} = "$lonids/$cookie.id";
14595: 
14596: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14597: 		 &GDBM_WRCREAT(),0640)) {
14598: 	    &_add_to_env(\%disk_env,\%initial_env);
14599: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14600: 	    &_add_to_env(\%disk_env,$userroles);
14601:             if (ref($firstaccenv) eq 'HASH') {
14602:                 &_add_to_env(\%disk_env,$firstaccenv);
14603:             }
14604:             if (ref($timerintenv) eq 'HASH') {
14605:                 &_add_to_env(\%disk_env,$timerintenv);
14606:             }
14607: 	    if (ref($args->{'extra_env'})) {
14608: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14609: 	    }
14610: 	    untie(%disk_env);
14611: 	} else {
14612: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14613: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14614: 	    return 'error: '.$!;
14615: 	}
14616:     }
14617:     $env{'request.role'}='cm';
14618:     $env{'request.role.adv'}=$env{'user.adv'};
14619:     $env{'browser.type'}=$clientbrowser;
14620: 
14621:     return $cookie;
14622: 
14623: }
14624: 
14625: sub _add_to_env {
14626:     my ($idf,$env_data,$prefix) = @_;
14627:     if (ref($env_data) eq 'HASH') {
14628:         while (my ($key,$value) = each(%$env_data)) {
14629: 	    $idf->{$prefix.$key} = $value;
14630: 	    $env{$prefix.$key}   = $value;
14631:         }
14632:     }
14633: }
14634: 
14635: # --- Get the symbolic name of a problem and the url
14636: sub get_symb {
14637:     my ($request,$silent) = @_;
14638:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14639:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14640:     if ($symb eq '') {
14641:         if (!$silent) {
14642:             if (ref($request)) { 
14643:                 $request->print("Unable to handle ambiguous references:$url:.");
14644:             }
14645:             return ();
14646:         }
14647:     }
14648:     &Apache::lonenc::check_decrypt(\$symb);
14649:     return ($symb);
14650: }
14651: 
14652: # --------------------------------------------------------------Get annotation
14653: 
14654: sub get_annotation {
14655:     my ($symb,$enc) = @_;
14656: 
14657:     my $key = $symb;
14658:     if (!$enc) {
14659:         $key =
14660:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14661:     }
14662:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14663:     return $annotation{$key};
14664: }
14665: 
14666: sub clean_symb {
14667:     my ($symb,$delete_enc) = @_;
14668: 
14669:     &Apache::lonenc::check_decrypt(\$symb);
14670:     my $enc = $env{'request.enc'};
14671:     if ($delete_enc) {
14672:         delete($env{'request.enc'});
14673:     }
14674: 
14675:     return ($symb,$enc);
14676: }
14677: 
14678: sub build_release_hashes {
14679:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14680:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14681:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14682:                   (ref($randomizetry) eq 'HASH'));
14683:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14684:         my ($item,$name,$value) = split(/:/,$key);
14685:         if ($item eq 'parameter') {
14686:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14687:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14688:                     push(@{$checkparms->{$name}},$value);
14689:                 }
14690:             } else {
14691:                 push(@{$checkparms->{$name}},$value);
14692:             }
14693:         } elsif ($item eq 'resourcetag') {
14694:             if ($name eq 'responsetype') {
14695:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14696:             }
14697:         } elsif ($item eq 'course') {
14698:             if ($name eq 'crstype') {
14699:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14700:             }
14701:         }
14702:     }
14703:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14704:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14705:     return;
14706: }
14707: 
14708: sub update_content_constraints {
14709:     my ($cdom,$cnum,$chome,$cid) = @_;
14710:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14711:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14712:     my %checkresponsetypes;
14713:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14714:         my ($item,$name,$value) = split(/:/,$key);
14715:         if ($item eq 'resourcetag') {
14716:             if ($name eq 'responsetype') {
14717:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14718:             }
14719:         }
14720:     }
14721:     my $navmap = Apache::lonnavmaps::navmap->new();
14722:     if (defined($navmap)) {
14723:         my %allresponses;
14724:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14725:             my %responses = $res->responseTypes();
14726:             foreach my $key (keys(%responses)) {
14727:                 next unless(exists($checkresponsetypes{$key}));
14728:                 $allresponses{$key} += $responses{$key};
14729:             }
14730:         }
14731:         foreach my $key (keys(%allresponses)) {
14732:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14733:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14734:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14735:             }
14736:         }
14737:         undef($navmap);
14738:     }
14739:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14740:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14741:     }
14742:     return;
14743: }
14744: 
14745: sub allmaps_incourse {
14746:     my ($cdom,$cnum,$chome,$cid) = @_;
14747:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14748:         $cid = $env{'request.course.id'};
14749:         $cdom = $env{'course.'.$cid.'.domain'};
14750:         $cnum = $env{'course.'.$cid.'.num'};
14751:         $chome = $env{'course.'.$cid.'.home'};
14752:     }
14753:     my %allmaps = ();
14754:     my $lastchange =
14755:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14756:     if ($lastchange > $env{'request.course.tied'}) {
14757:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14758:         unless ($ferr) {
14759:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14760:         }
14761:     }
14762:     my $navmap = Apache::lonnavmaps::navmap->new();
14763:     if (defined($navmap)) {
14764:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14765:             $allmaps{$res->src()} = 1;
14766:         }
14767:     }
14768:     return \%allmaps;
14769: }
14770: 
14771: sub parse_supplemental_title {
14772:     my ($title) = @_;
14773: 
14774:     my ($foldertitle,$renametitle);
14775:     if ($title =~ /&amp;&amp;&amp;/) {
14776:         $title = &HTML::Entites::decode($title);
14777:     }
14778:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14779:         $renametitle=$4;
14780:         my ($time,$uname,$udom) = ($1,$2,$3);
14781:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14782:         my $name =  &plainname($uname,$udom);
14783:         $name = &HTML::Entities::encode($name,'"<>&\'');
14784:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14785:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14786:             $name.': <br />'.$foldertitle;
14787:     }
14788:     if (wantarray) {
14789:         return ($title,$foldertitle,$renametitle);
14790:     }
14791:     return $title;
14792: }
14793: 
14794: sub recurse_supplemental {
14795:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14796:     if ($suppmap) {
14797:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14798:         if ($fatal) {
14799:             $errors ++;
14800:         } else {
14801:             if ($#LONCAPA::map::resources > 0) {
14802:                 foreach my $res (@LONCAPA::map::resources) {
14803:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14804:                     if (($src ne '') && ($status eq 'res')) {
14805:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
14806:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
14807:                         } else {
14808:                             $numfiles ++;
14809:                         }
14810:                     }
14811:                 }
14812:             }
14813:         }
14814:     }
14815:     return ($numfiles,$errors);
14816: }
14817: 
14818: sub symb_to_docspath {
14819:     my ($symb) = @_;
14820:     return unless ($symb);
14821:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14822:     if ($resurl=~/\.(sequence|page)$/) {
14823:         $mapurl=$resurl;
14824:     } elsif ($resurl eq 'adm/navmaps') {
14825:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14826:     }
14827:     my $mapresobj;
14828:     my $navmap = Apache::lonnavmaps::navmap->new();
14829:     if (ref($navmap)) {
14830:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14831:     }
14832:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14833:     my $type=$2;
14834:     my $path;
14835:     if (ref($mapresobj)) {
14836:         my $pcslist = $mapresobj->map_hierarchy();
14837:         if ($pcslist ne '') {
14838:             foreach my $pc (split(/,/,$pcslist)) {
14839:                 next if ($pc <= 1);
14840:                 my $res = $navmap->getByMapPc($pc);
14841:                 if (ref($res)) {
14842:                     my $thisurl = $res->src();
14843:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14844:                     my $thistitle = $res->title();
14845:                     $path .= '&'.
14846:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14847:                              &escape($thistitle).
14848:                              ':'.$res->randompick().
14849:                              ':'.$res->randomout().
14850:                              ':'.$res->encrypted().
14851:                              ':'.$res->randomorder().
14852:                              ':'.$res->is_page();
14853:                 }
14854:             }
14855:         }
14856:         $path =~ s/^\&//;
14857:         my $maptitle = $mapresobj->title();
14858:         if ($mapurl eq 'default') {
14859:             $maptitle = 'Main Content';
14860:         }
14861:         $path .= (($path ne '')? '&' : '').
14862:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14863:                  &escape($maptitle).
14864:                  ':'.$mapresobj->randompick().
14865:                  ':'.$mapresobj->randomout().
14866:                  ':'.$mapresobj->encrypted().
14867:                  ':'.$mapresobj->randomorder().
14868:                  ':'.$mapresobj->is_page();
14869:     } else {
14870:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14871:         my $ispage = (($type eq 'page')? 1 : '');
14872:         if ($mapurl eq 'default') {
14873:             $maptitle = 'Main Content';
14874:         }
14875:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14876:                 &escape($maptitle).':::::'.$ispage;
14877:     }
14878:     unless ($mapurl eq 'default') {
14879:         $path = 'default&'.
14880:                 &escape('Main Content').
14881:                 ':::::&'.$path;
14882:     }
14883:     return $path;
14884: }
14885: 
14886: sub captcha_display {
14887:     my ($context,$lonhost) = @_;
14888:     my ($output,$error);
14889:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14890:     if ($captcha eq 'original') {
14891:         $output = &create_captcha();
14892:         unless ($output) {
14893:             $error = 'captcha';
14894:         }
14895:     } elsif ($captcha eq 'recaptcha') {
14896:         $output = &create_recaptcha($pubkey);
14897:         unless ($output) {
14898:             $error = 'recaptcha';
14899:         }
14900:     }
14901:     return ($output,$error,$captcha);
14902: }
14903: 
14904: sub captcha_response {
14905:     my ($context,$lonhost) = @_;
14906:     my ($captcha_chk,$captcha_error);
14907:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14908:     if ($captcha eq 'original') {
14909:         ($captcha_chk,$captcha_error) = &check_captcha();
14910:     } elsif ($captcha eq 'recaptcha') {
14911:         $captcha_chk = &check_recaptcha($privkey);
14912:     } else {
14913:         $captcha_chk = 1;
14914:     }
14915:     return ($captcha_chk,$captcha_error);
14916: }
14917: 
14918: sub get_captcha_config {
14919:     my ($context,$lonhost) = @_;
14920:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14921:     my $hostname = &Apache::lonnet::hostname($lonhost);
14922:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14923:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14924:     if ($context eq 'usercreation') {
14925:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14926:         if (ref($domconfig{$context}) eq 'HASH') {
14927:             $hashtocheck = $domconfig{$context}{'cancreate'};
14928:             if (ref($hashtocheck) eq 'HASH') {
14929:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14930:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14931:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14932:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14933:                     }
14934:                     if ($privkey && $pubkey) {
14935:                         $captcha = 'recaptcha';
14936:                     } else {
14937:                         $captcha = 'original';
14938:                     }
14939:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14940:                     $captcha = 'original';
14941:                 }
14942:             }
14943:         } else {
14944:             $captcha = 'captcha';
14945:         }
14946:     } elsif ($context eq 'login') {
14947:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14948:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14949:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14950:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14951:             if ($privkey && $pubkey) {
14952:                 $captcha = 'recaptcha';
14953:             } else {
14954:                 $captcha = 'original';
14955:             }
14956:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14957:             $captcha = 'original';
14958:         }
14959:     }
14960:     return ($captcha,$pubkey,$privkey);
14961: }
14962: 
14963: sub create_captcha {
14964:     my %captcha_params = &captcha_settings();
14965:     my ($output,$maxtries,$tries) = ('',10,0);
14966:     while ($tries < $maxtries) {
14967:         $tries ++;
14968:         my $captcha = Authen::Captcha->new (
14969:                                            output_folder => $captcha_params{'output_dir'},
14970:                                            data_folder   => $captcha_params{'db_dir'},
14971:                                           );
14972:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14973: 
14974:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14975:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14976:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14977:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
14978:                       '<br />'.
14979:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
14980:             last;
14981:         }
14982:     }
14983:     return $output;
14984: }
14985: 
14986: sub captcha_settings {
14987:     my %captcha_params = (
14988:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14989:                            www_output_dir => "/captchaspool",
14990:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14991:                            numchars       => '5',
14992:                          );
14993:     return %captcha_params;
14994: }
14995: 
14996: sub check_captcha {
14997:     my ($captcha_chk,$captcha_error);
14998:     my $code = $env{'form.code'};
14999:     my $md5sum = $env{'form.crypt'};
15000:     my %captcha_params = &captcha_settings();
15001:     my $captcha = Authen::Captcha->new(
15002:                       output_folder => $captcha_params{'output_dir'},
15003:                       data_folder   => $captcha_params{'db_dir'},
15004:                   );
15005:     $captcha_chk = $captcha->check_code($code,$md5sum);
15006:     my %captcha_hash = (
15007:                         0       => 'Code not checked (file error)',
15008:                        -1      => 'Failed: code expired',
15009:                        -2      => 'Failed: invalid code (not in database)',
15010:                        -3      => 'Failed: invalid code (code does not match crypt)',
15011:     );
15012:     if ($captcha_chk != 1) {
15013:         $captcha_error = $captcha_hash{$captcha_chk}
15014:     }
15015:     return ($captcha_chk,$captcha_error);
15016: }
15017: 
15018: sub create_recaptcha {
15019:     my ($pubkey) = @_;
15020:     my $use_ssl;
15021:     if ($ENV{'SERVER_PORT'} == 443) {
15022:         $use_ssl = 1;
15023:     }
15024:     my $captcha = Captcha::reCAPTCHA->new;
15025:     return $captcha->get_options_setter({theme => 'white'})."\n".
15026:            $captcha->get_html($pubkey,undef,$use_ssl).
15027:            &mt('If either word is hard to read, [_1] will replace them.',
15028:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
15029:            '<br /><br />';
15030: }
15031: 
15032: sub check_recaptcha {
15033:     my ($privkey) = @_;
15034:     my $captcha_chk;
15035:     my $captcha = Captcha::reCAPTCHA->new;
15036:     my $captcha_result =
15037:         $captcha->check_answer(
15038:                                 $privkey,
15039:                                 $ENV{'REMOTE_ADDR'},
15040:                                 $env{'form.recaptcha_challenge_field'},
15041:                                 $env{'form.recaptcha_response_field'},
15042:                               );
15043:     if ($captcha_result->{is_valid}) {
15044:         $captcha_chk = 1;
15045:     }
15046:     return $captcha_chk;
15047: }
15048: 
15049: sub emailusername_info {
15050:     my @fields = ('lastname','firstname','institution','web','location','officialemail');
15051:     my %titles = &Apache::lonlocal::texthash (
15052:                      lastname      => 'Last Name',
15053:                      firstname     => 'First Name',
15054:                      institution   => 'School/college/university',
15055:                      location      => "School's city, state/province, country",
15056:                      web           => "School's web address",
15057:                      officialemail => 'E-mail address at institution (if different)',
15058:                  );
15059:     return (\@fields,\%titles);
15060: }
15061: 
15062: sub cleanup_html {
15063:     my ($incoming) = @_;
15064:     my $outgoing;
15065:     if ($incoming ne '') {
15066:         $outgoing = $incoming;
15067:         $outgoing =~ s/;/&#059;/g;
15068:         $outgoing =~ s/\#/&#035;/g;
15069:         $outgoing =~ s/\&/&#038;/g;
15070:         $outgoing =~ s/</&#060;/g;
15071:         $outgoing =~ s/>/&#062;/g;
15072:         $outgoing =~ s/\(/&#040/g;
15073:         $outgoing =~ s/\)/&#041;/g;
15074:         $outgoing =~ s/"/&#034;/g;
15075:         $outgoing =~ s/'/&#039;/g;
15076:         $outgoing =~ s/\$/&#036;/g;
15077:         $outgoing =~ s{/}{&#047;}g;
15078:         $outgoing =~ s/=/&#061;/g;
15079:         $outgoing =~ s/\\/&#092;/g
15080:     }
15081:     return $outgoing;
15082: }
15083: 
15084: # Use:
15085: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
15086: #
15087: ##################################################
15088: #          password associated functions         #
15089: ##################################################
15090: sub des_keys {
15091:     # Make a new key for DES encryption.
15092:     # Each key has two parts which are returned separately.
15093:     # Please note:  Each key must be passed through the &hex function
15094:     # before it is output to the web browser.  The hex versions cannot
15095:     # be used to decrypt.
15096:     my @hexstr=('0','1','2','3','4','5','6','7',
15097:                 '8','9','a','b','c','d','e','f');
15098:     my $lkey='';
15099:     for (0..7) {
15100:         $lkey.=$hexstr[rand(15)];
15101:     }
15102:     my $ukey='';
15103:     for (0..7) {
15104:         $ukey.=$hexstr[rand(15)];
15105:     }
15106:     return ($lkey,$ukey);
15107: }
15108: 
15109: sub des_decrypt {
15110:     my ($key,$cyphertext) = @_;
15111:     my $keybin=pack("H16",$key);
15112:     my $cypher;
15113:     if ($Crypt::DES::VERSION>=2.03) {
15114:         $cypher=new Crypt::DES $keybin;
15115:     } else {
15116:         $cypher=new DES $keybin;
15117:     }
15118:     my $plaintext=
15119:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
15120:     $plaintext.=
15121:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
15122:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
15123:     return $plaintext;
15124: }
15125: 
15126: =pod
15127: 
15128: =back
15129: 
15130: =cut
15131: 
15132: 1;
15133: __END__;
15134: 

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