File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1164: download - view: text, annotated - select for diffs
Fri Dec 20 00:08:22 2013 UTC (10 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Extraction of contents of archive files (zip, tar etc.) from a file
  - Option to process contents automatically for Camtasia zip files now
    supported for conten packaging used in Camtasia 8, as well as (different)
    packaging used in older Camtasia versions.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1164 2013/12/20 00:08:22 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use LONCAPA qw(:DEFAULT :match);
   73: use DateTime::TimeZone;
   74: use DateTime::Locale::Catalog;
   75: use Text::Aspell;
   76: use Authen::Captcha;
   77: use Captcha::reCAPTCHA;
   78: 
   79: # ---------------------------------------------- Designs
   80: use vars qw(%defaultdesign);
   81: 
   82: my $readit;
   83: 
   84: 
   85: ##
   86: ## Global Variables
   87: ##
   88: 
   89: 
   90: # ----------------------------------------------- SSI with retries:
   91: #
   92: 
   93: =pod
   94: 
   95: =head1 Server Side include with retries:
   96: 
   97: =over 4
   98: 
   99: =item * &ssi_with_retries(resource,retries form)
  100: 
  101: Performs an ssi with some number of retries.  Retries continue either
  102: until the result is ok or until the retry count supplied by the
  103: caller is exhausted.  
  104: 
  105: Inputs:
  106: 
  107: =over 4
  108: 
  109: resource   - Identifies the resource to insert.
  110: 
  111: retries    - Count of the number of retries allowed.
  112: 
  113: form       - Hash that identifies the rendering options.
  114: 
  115: =back
  116: 
  117: Returns:
  118: 
  119: =over 4
  120: 
  121: content    - The content of the response.  If retries were exhausted this is empty.
  122: 
  123: response   - The response from the last attempt (which may or may not have been successful.
  124: 
  125: =back
  126: 
  127: =back
  128: 
  129: =cut
  130: 
  131: sub ssi_with_retries {
  132:     my ($resource, $retries, %form) = @_;
  133: 
  134: 
  135:     my $ok = 0;			# True if we got a good response.
  136:     my $content;
  137:     my $response;
  138: 
  139:     # Try to get the ssi done. within the retries count:
  140: 
  141:     do {
  142: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  143: 	$ok      = $response->is_success;
  144:         if (!$ok) {
  145:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  146:         }
  147: 	$retries--;
  148:     } while (!$ok && ($retries > 0));
  149: 
  150:     if (!$ok) {
  151: 	$content = '';		# On error return an empty content.
  152:     }
  153:     return ($content, $response);
  154: 
  155: }
  156: 
  157: 
  158: 
  159: # ----------------------------------------------- Filetypes/Languages/Copyright
  160: my %language;
  161: my %supported_language;
  162: my %supported_codes;
  163: my %latex_language;		# For choosing hyphenation in <transl..>
  164: my %latex_language_bykey;	# for choosing hyphenation from metadata
  165: my %cprtag;
  166: my %scprtag;
  167: my %fe; my %fd; my %fm;
  168: my %category_extensions;
  169: 
  170: # ---------------------------------------------- Thesaurus variables
  171: #
  172: # %Keywords:
  173: #      A hash used by &keyword to determine if a word is considered a keyword.
  174: # $thesaurus_db_file 
  175: #      Scalar containing the full path to the thesaurus database.
  176: 
  177: my %Keywords;
  178: my $thesaurus_db_file;
  179: 
  180: #
  181: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  182: # thesaurus.tab, and filecategories.tab.
  183: #
  184: BEGIN {
  185:     # Variable initialization
  186:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  187:     #
  188:     unless ($readit) {
  189: # ------------------------------------------------------------------- languages
  190:     {
  191:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  192:                                    '/language.tab';
  193:         if ( open(my $fh,"<$langtabfile") ) {
  194:             while (my $line = <$fh>) {
  195:                 next if ($line=~/^\#/);
  196:                 chomp($line);
  197:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  198:                 $language{$key}=$val.' - '.$enc;
  199:                 if ($sup) {
  200:                     $supported_language{$key}=$sup;
  201: 		    $supported_codes{$key}   = $code;
  202:                 }
  203: 		if ($latex) {
  204: 		    $latex_language_bykey{$key} = $latex;
  205: 		    $latex_language{$code} = $latex;
  206: 		}
  207:             }
  208:             close($fh);
  209:         }
  210:     }
  211: # ------------------------------------------------------------------ copyrights
  212:     {
  213:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  214:                                   '/copyright.tab';
  215:         if ( open (my $fh,"<$copyrightfile") ) {
  216:             while (my $line = <$fh>) {
  217:                 next if ($line=~/^\#/);
  218:                 chomp($line);
  219:                 my ($key,$val)=(split(/\s+/,$line,2));
  220:                 $cprtag{$key}=$val;
  221:             }
  222:             close($fh);
  223:         }
  224:     }
  225: # ----------------------------------------------------------- source copyrights
  226:     {
  227:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  228:                                   '/source_copyright.tab';
  229:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  230:             while (my $line = <$fh>) {
  231:                 next if ($line =~ /^\#/);
  232:                 chomp($line);
  233:                 my ($key,$val)=(split(/\s+/,$line,2));
  234:                 $scprtag{$key}=$val;
  235:             }
  236:             close($fh);
  237:         }
  238:     }
  239: 
  240: # -------------------------------------------------------------- default domain designs
  241:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  242:     my $designfile = $designdir.'/default.tab';
  243:     if ( open (my $fh,"<$designfile") ) {
  244:         while (my $line = <$fh>) {
  245:             next if ($line =~ /^\#/);
  246:             chomp($line);
  247:             my ($key,$val)=(split(/\=/,$line));
  248:             if ($val) { $defaultdesign{$key}=$val; }
  249:         }
  250:         close($fh);
  251:     }
  252: 
  253: # ------------------------------------------------------------- file categories
  254:     {
  255:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  256:                                   '/filecategories.tab';
  257:         if ( open (my $fh,"<$categoryfile") ) {
  258: 	    while (my $line = <$fh>) {
  259: 		next if ($line =~ /^\#/);
  260: 		chomp($line);
  261:                 my ($extension,$category)=(split(/\s+/,$line,2));
  262:                 push @{$category_extensions{lc($category)}},$extension;
  263:             }
  264:             close($fh);
  265:         }
  266: 
  267:     }
  268: # ------------------------------------------------------------------ file types
  269:     {
  270:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  271:                '/filetypes.tab';
  272:         if ( open (my $fh,"<$typesfile") ) {
  273:             while (my $line = <$fh>) {
  274: 		next if ($line =~ /^\#/);
  275: 		chomp($line);
  276:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  277:                 if ($descr ne '') {
  278:                     $fe{$ending}=lc($emb);
  279:                     $fd{$ending}=$descr;
  280:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  281:                 }
  282:             }
  283:             close($fh);
  284:         }
  285:     }
  286:     &Apache::lonnet::logthis(
  287:              "<span style='color:yellow;'>INFO: Read file types</span>");
  288:     $readit=1;
  289:     }  # end of unless($readit) 
  290:     
  291: }
  292: 
  293: ###############################################################
  294: ##           HTML and Javascript Helper Functions            ##
  295: ###############################################################
  296: 
  297: =pod 
  298: 
  299: =head1 HTML and Javascript Functions
  300: 
  301: =over 4
  302: 
  303: =item * &browser_and_searcher_javascript()
  304: 
  305: X<browsing, javascript>X<searching, javascript>Returns a string
  306: containing javascript with two functions, C<openbrowser> and
  307: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  308: tags.
  309: 
  310: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  311: 
  312: inputs: formname, elementname, only, omit
  313: 
  314: formname and elementname indicate the name of the html form and name of
  315: the element that the results of the browsing selection are to be placed in. 
  316: 
  317: Specifying 'only' will restrict the browser to displaying only files
  318: with the given extension.  Can be a comma separated list.
  319: 
  320: Specifying 'omit' will restrict the browser to NOT displaying files
  321: with the given extension.  Can be a comma separated list.
  322: 
  323: =item * &opensearcher(formname,elementname) [javascript]
  324: 
  325: Inputs: formname, elementname
  326: 
  327: formname and elementname specify the name of the html form and the name
  328: of the element the selection from the search results will be placed in.
  329: 
  330: =cut
  331: 
  332: sub browser_and_searcher_javascript {
  333:     my ($mode)=@_;
  334:     if (!defined($mode)) { $mode='edit'; }
  335:     my $resurl=&escape_single(&lastresurl());
  336:     return <<END;
  337: // <!-- BEGIN LON-CAPA Internal
  338:     var editbrowser = null;
  339:     function openbrowser(formname,elementname,only,omit,titleelement) {
  340:         var url = '$resurl/?';
  341:         if (editbrowser == null) {
  342:             url += 'launch=1&';
  343:         }
  344:         url += 'catalogmode=interactive&';
  345:         url += 'mode=$mode&';
  346:         url += 'inhibitmenu=yes&';
  347:         url += 'form=' + formname + '&';
  348:         if (only != null) {
  349:             url += 'only=' + only + '&';
  350:         } else {
  351:             url += 'only=&';
  352: 	}
  353:         if (omit != null) {
  354:             url += 'omit=' + omit + '&';
  355:         } else {
  356:             url += 'omit=&';
  357: 	}
  358:         if (titleelement != null) {
  359:             url += 'titleelement=' + titleelement + '&';
  360:         } else {
  361: 	    url += 'titleelement=&';
  362: 	}
  363:         url += 'element=' + elementname + '';
  364:         var title = 'Browser';
  365:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  366:         options += ',width=700,height=600';
  367:         editbrowser = open(url,title,options,'1');
  368:         editbrowser.focus();
  369:     }
  370:     var editsearcher;
  371:     function opensearcher(formname,elementname,titleelement) {
  372:         var url = '/adm/searchcat?';
  373:         if (editsearcher == null) {
  374:             url += 'launch=1&';
  375:         }
  376:         url += 'catalogmode=interactive&';
  377:         url += 'mode=$mode&';
  378:         url += 'form=' + formname + '&';
  379:         if (titleelement != null) {
  380:             url += 'titleelement=' + titleelement + '&';
  381:         } else {
  382: 	    url += 'titleelement=&';
  383: 	}
  384:         url += 'element=' + elementname + '';
  385:         var title = 'Search';
  386:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  387:         options += ',width=700,height=600';
  388:         editsearcher = open(url,title,options,'1');
  389:         editsearcher.focus();
  390:     }
  391: // END LON-CAPA Internal -->
  392: END
  393: }
  394: 
  395: sub lastresurl {
  396:     if ($env{'environment.lastresurl'}) {
  397: 	return $env{'environment.lastresurl'}
  398:     } else {
  399: 	return '/res';
  400:     }
  401: }
  402: 
  403: sub storeresurl {
  404:     my $resurl=&Apache::lonnet::clutter(shift);
  405:     unless ($resurl=~/^\/res/) { return 0; }
  406:     $resurl=~s/\/$//;
  407:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  408:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  409:     return 1;
  410: }
  411: 
  412: sub studentbrowser_javascript {
  413:    unless (
  414:             (($env{'request.course.id'}) && 
  415:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  416: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  417: 					  '/'.$env{'request.course.sec'})
  418: 	      ))
  419:          || ($env{'request.role'}=~/^(au|dc|su)/)
  420:           ) { return ''; }  
  421:    return (<<'ENDSTDBRW');
  422: <script type="text/javascript" language="Javascript">
  423: // <![CDATA[
  424:     var stdeditbrowser;
  425:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  426:         var url = '/adm/pickstudent?';
  427:         var filter;
  428: 	if (!ignorefilter) {
  429: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  430: 	}
  431:         if (filter != null) {
  432:            if (filter != '') {
  433:                url += 'filter='+filter+'&';
  434: 	   }
  435:         }
  436:         url += 'form=' + formname + '&unameelement='+uname+
  437:                                     '&udomelement='+udom+
  438:                                     '&clicker='+clicker;
  439: 	if (roleflag) { url+="&roles=1"; }
  440:         if (courseadvonly) { url+="&courseadvonly=1"; }
  441:         var title = 'Student_Browser';
  442:         var options = 'scrollbars=1,resizable=1,menubar=0';
  443:         options += ',width=700,height=600';
  444:         stdeditbrowser = open(url,title,options,'1');
  445:         stdeditbrowser.focus();
  446:     }
  447: // ]]>
  448: </script>
  449: ENDSTDBRW
  450: }
  451: 
  452: sub resourcebrowser_javascript {
  453:    unless ($env{'request.course.id'}) { return ''; }
  454:    return (<<'ENDRESBRW');
  455: <script type="text/javascript" language="Javascript">
  456: // <![CDATA[
  457:     var reseditbrowser;
  458:     function openresbrowser(formname,reslink) {
  459:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  460:         var title = 'Resource_Browser';
  461:         var options = 'scrollbars=1,resizable=1,menubar=0';
  462:         options += ',width=700,height=500';
  463:         reseditbrowser = open(url,title,options,'1');
  464:         reseditbrowser.focus();
  465:     }
  466: // ]]>
  467: </script>
  468: ENDRESBRW
  469: }
  470: 
  471: sub selectstudent_link {
  472:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  473:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  474:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  475:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  476:    if ($env{'request.course.id'}) {  
  477:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  478: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  479: 					'/'.$env{'request.course.sec'})) {
  480: 	   return '';
  481:        }
  482:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  483:        if ($courseadvonly)  {
  484:            $callargs .= ",'',1,1";
  485:        }
  486:        return '<span class="LC_nobreak">'.
  487:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  488:               &mt('Select User').'</a></span>';
  489:    }
  490:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  491:        $callargs .= ",'',1"; 
  492:        return '<span class="LC_nobreak">'.
  493:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  494:               &mt('Select User').'</a></span>';
  495:    }
  496:    return '';
  497: }
  498: 
  499: sub selectresource_link {
  500:    my ($form,$reslink,$arg)=@_;
  501:    
  502:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  503:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  504:    unless ($env{'request.course.id'}) { return $arg; }
  505:    return '<span class="LC_nobreak">'.
  506:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  507:               $arg.'</a></span>';
  508: }
  509: 
  510: 
  511: 
  512: sub authorbrowser_javascript {
  513:     return <<"ENDAUTHORBRW";
  514: <script type="text/javascript" language="JavaScript">
  515: // <![CDATA[
  516: var stdeditbrowser;
  517: 
  518: function openauthorbrowser(formname,udom) {
  519:     var url = '/adm/pickauthor?';
  520:     url += 'form='+formname+'&roledom='+udom;
  521:     var title = 'Author_Browser';
  522:     var options = 'scrollbars=1,resizable=1,menubar=0';
  523:     options += ',width=700,height=600';
  524:     stdeditbrowser = open(url,title,options,'1');
  525:     stdeditbrowser.focus();
  526: }
  527: 
  528: // ]]>
  529: </script>
  530: ENDAUTHORBRW
  531: }
  532: 
  533: sub coursebrowser_javascript {
  534:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  535:         $credits_element) = @_;
  536:     my $wintitle = 'Course_Browser';
  537:     if ($crstype eq 'Community') {
  538:         $wintitle = 'Community_Browser';
  539:     }
  540:     my $id_functions = &javascript_index_functions();
  541:     my $output = '
  542: <script type="text/javascript" language="JavaScript">
  543: // <![CDATA[
  544:     var stdeditbrowser;'."\n";
  545: 
  546:     $output .= <<"ENDSTDBRW";
  547:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  548:         var url = '/adm/pickcourse?';
  549:         var formid = getFormIdByName(formname);
  550:         var domainfilter = getDomainFromSelectbox(formname,udom);
  551:         if (domainfilter != null) {
  552:            if (domainfilter != '') {
  553:                url += 'domainfilter='+domainfilter+'&';
  554: 	   }
  555:         }
  556:         url += 'form=' + formname + '&cnumelement='+uname+
  557: 	                            '&cdomelement='+udom+
  558:                                     '&cnameelement='+desc;
  559:         if (extra_element !=null && extra_element != '') {
  560:             if (formname == 'rolechoice' || formname == 'studentform') {
  561:                 url += '&roleelement='+extra_element;
  562:                 if (domainfilter == null || domainfilter == '') {
  563:                     url += '&domainfilter='+extra_element;
  564:                 }
  565:             }
  566:             else {
  567:                 if (formname == 'portform') {
  568:                     url += '&setroles='+extra_element;
  569:                 } else {
  570:                     if (formname == 'rules') {
  571:                         url += '&fixeddom='+extra_element; 
  572:                     }
  573:                 }
  574:             }     
  575:         }
  576:         if (type != null && type != '') {
  577:             url += '&type='+type;
  578:         }
  579:         if (type_elem != null && type_elem != '') {
  580:             url += '&typeelement='+type_elem;
  581:         }
  582:         if (formname == 'ccrs') {
  583:             var ownername = document.forms[formid].ccuname.value;
  584:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  585:             url += '&cloner='+ownername+':'+ownerdom;
  586:         }
  587:         if (multflag !=null && multflag != '') {
  588:             url += '&multiple='+multflag;
  589:         }
  590:         var title = '$wintitle';
  591:         var options = 'scrollbars=1,resizable=1,menubar=0';
  592:         options += ',width=700,height=600';
  593:         stdeditbrowser = open(url,title,options,'1');
  594:         stdeditbrowser.focus();
  595:     }
  596: $id_functions
  597: ENDSTDBRW
  598:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  599:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  600:                                       $credits_element);
  601:     }
  602:     $output .= '
  603: // ]]>
  604: </script>';
  605:     return $output;
  606: }
  607: 
  608: sub javascript_index_functions {
  609:     return <<"ENDJS";
  610: 
  611: function getFormIdByName(formname) {
  612:     for (var i=0;i<document.forms.length;i++) {
  613:         if (document.forms[i].name == formname) {
  614:             return i;
  615:         }
  616:     }
  617:     return -1;
  618: }
  619: 
  620: function getIndexByName(formid,item) {
  621:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  622:         if (document.forms[formid].elements[i].name == item) {
  623:             return i;
  624:         }
  625:     }
  626:     return -1;
  627: }
  628: 
  629: function getDomainFromSelectbox(formname,udom) {
  630:     var userdom;
  631:     var formid = getFormIdByName(formname);
  632:     if (formid > -1) {
  633:         var domid = getIndexByName(formid,udom);
  634:         if (domid > -1) {
  635:             if (document.forms[formid].elements[domid].type == 'select-one') {
  636:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  637:             }
  638:             if (document.forms[formid].elements[domid].type == 'hidden') {
  639:                 userdom=document.forms[formid].elements[domid].value;
  640:             }
  641:         }
  642:     }
  643:     return userdom;
  644: }
  645: 
  646: ENDJS
  647: 
  648: }
  649: 
  650: sub javascript_array_indexof {
  651:     return <<ENDJS;
  652: <script type="text/javascript" language="JavaScript">
  653: // <![CDATA[
  654: 
  655: if (!Array.prototype.indexOf) {
  656:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  657:         "use strict";
  658:         if (this === void 0 || this === null) {
  659:             throw new TypeError();
  660:         }
  661:         var t = Object(this);
  662:         var len = t.length >>> 0;
  663:         if (len === 0) {
  664:             return -1;
  665:         }
  666:         var n = 0;
  667:         if (arguments.length > 0) {
  668:             n = Number(arguments[1]);
  669:             if (n !== n) { // shortcut for verifying if it is NaN
  670:                 n = 0;
  671:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  672:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  673:             }
  674:         }
  675:         if (n >= len) {
  676:             return -1;
  677:         }
  678:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  679:         for (; k < len; k++) {
  680:             if (k in t && t[k] === searchElement) {
  681:                 return k;
  682:             }
  683:         }
  684:         return -1;
  685:     }
  686: }
  687: 
  688: // ]]>
  689: </script>
  690: 
  691: ENDJS
  692: 
  693: }
  694: 
  695: sub userbrowser_javascript {
  696:     my $id_functions = &javascript_index_functions();
  697:     return <<"ENDUSERBRW";
  698: 
  699: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  700:     var url = '/adm/pickuser?';
  701:     var userdom = getDomainFromSelectbox(formname,udom);
  702:     if (userdom != null) {
  703:        if (userdom != '') {
  704:            url += 'srchdom='+userdom+'&';
  705:        }
  706:     }
  707:     url += 'form=' + formname + '&unameelement='+uname+
  708:                                 '&udomelement='+udom+
  709:                                 '&ulastelement='+ulast+
  710:                                 '&ufirstelement='+ufirst+
  711:                                 '&uemailelement='+uemail+
  712:                                 '&hideudomelement='+hideudom+
  713:                                 '&coursedom='+crsdom;
  714:     if ((caller != null) && (caller != undefined)) {
  715:         url += '&caller='+caller;
  716:     }
  717:     var title = 'User_Browser';
  718:     var options = 'scrollbars=1,resizable=1,menubar=0';
  719:     options += ',width=700,height=600';
  720:     var stdeditbrowser = open(url,title,options,'1');
  721:     stdeditbrowser.focus();
  722: }
  723: 
  724: function fix_domain (formname,udom,origdom,uname) {
  725:     var formid = getFormIdByName(formname);
  726:     if (formid > -1) {
  727:         var unameid = getIndexByName(formid,uname);
  728:         var domid = getIndexByName(formid,udom);
  729:         var hidedomid = getIndexByName(formid,origdom);
  730:         if (hidedomid > -1) {
  731:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  732:             var unameval = document.forms[formid].elements[unameid].value;
  733:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  734:                 if (domid > -1) {
  735:                     var slct = document.forms[formid].elements[domid];
  736:                     if (slct.type == 'select-one') {
  737:                         var i;
  738:                         for (i=0;i<slct.length;i++) {
  739:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  740:                         }
  741:                     }
  742:                     if (slct.type == 'hidden') {
  743:                         slct.value = fixeddom;
  744:                     }
  745:                 }
  746:             }
  747:         }
  748:     }
  749:     return;
  750: }
  751: 
  752: $id_functions
  753: ENDUSERBRW
  754: }
  755: 
  756: sub setsec_javascript {
  757:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  758:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  759:         $communityrolestr);
  760:     if ($role_element ne '') {
  761:         my @allroles = ('st','ta','ep','in','ad');
  762:         foreach my $crstype ('Course','Community') {
  763:             if ($crstype eq 'Community') {
  764:                 foreach my $role (@allroles) {
  765:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  766:                 }
  767:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  768:             } else {
  769:                 foreach my $role (@allroles) {
  770:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  771:                 }
  772:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  773:             }
  774:         }
  775:         $rolestr = '"'.join('","',@allroles).'"';
  776:         $courserolestr = '"'.join('","',@courserolenames).'"';
  777:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  778:     }
  779:     my $setsections = qq|
  780: function setSect(sectionlist) {
  781:     var sectionsArray = new Array();
  782:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  783:         sectionsArray = sectionlist.split(",");
  784:     }
  785:     var numSections = sectionsArray.length;
  786:     document.$formname.$sec_element.length = 0;
  787:     if (numSections == 0) {
  788:         document.$formname.$sec_element.multiple=false;
  789:         document.$formname.$sec_element.size=1;
  790:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  791:     } else {
  792:         if (numSections == 1) {
  793:             document.$formname.$sec_element.multiple=false;
  794:             document.$formname.$sec_element.size=1;
  795:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  796:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  797:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  798:         } else {
  799:             for (var i=0; i<numSections; i++) {
  800:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  801:             }
  802:             document.$formname.$sec_element.multiple=true
  803:             if (numSections < 3) {
  804:                 document.$formname.$sec_element.size=numSections;
  805:             } else {
  806:                 document.$formname.$sec_element.size=3;
  807:             }
  808:             document.$formname.$sec_element.options[0].selected = false
  809:         }
  810:     }
  811: }
  812: 
  813: function setRole(crstype) {
  814: |;
  815:     if ($role_element eq '') {
  816:         $setsections .= '    return;
  817: }
  818: ';
  819:     } else {
  820:         $setsections .= qq|
  821:     var elementLength = document.$formname.$role_element.length;
  822:     var allroles = Array($rolestr);
  823:     var courserolenames = Array($courserolestr);
  824:     var communityrolenames = Array($communityrolestr);
  825:     if (elementLength != undefined) {
  826:         if (document.$formname.$role_element.options[5].value == 'cc') {
  827:             if (crstype == 'Course') {
  828:                 return;
  829:             } else {
  830:                 allroles[5] = 'co';
  831:                 for (var i=0; i<6; i++) {
  832:                     document.$formname.$role_element.options[i].value = allroles[i];
  833:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  834:                 }
  835:             }
  836:         } else {
  837:             if (crstype == 'Community') {
  838:                 return;
  839:             } else {
  840:                 allroles[5] = 'cc';
  841:                 for (var i=0; i<6; i++) {
  842:                     document.$formname.$role_element.options[i].value = allroles[i];
  843:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  844:                 }
  845:             }
  846:         }
  847:     }
  848:     return;
  849: }
  850: |;
  851:     }
  852:     if ($credits_element) {
  853:         $setsections .= qq|
  854: function setCredits(defaultcredits) {
  855:     document.$formname.$credits_element.value = defaultcredits;
  856:     return;
  857: }
  858: |;
  859:     }
  860:     return $setsections;
  861: }
  862: 
  863: sub selectcourse_link {
  864:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  865:        $typeelement) = @_;
  866:    my $type = $selecttype;
  867:    my $linktext = &mt('Select Course');
  868:    if ($selecttype eq 'Community') {
  869:        $linktext = &mt('Select Community');
  870:    } elsif ($selecttype eq 'Course/Community') {
  871:        $linktext = &mt('Select Course/Community');
  872:        $type = '';
  873:    } elsif ($selecttype eq 'Select') {
  874:        $linktext = &mt('Select');
  875:        $type = '';
  876:    }
  877:    return '<span class="LC_nobreak">'
  878:          ."<a href='"
  879:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  880:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  881:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  882:          ."'>".$linktext.'</a>'
  883:          .'</span>';
  884: }
  885: 
  886: sub selectauthor_link {
  887:    my ($form,$udom)=@_;
  888:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  889:           &mt('Select Author').'</a>';
  890: }
  891: 
  892: sub selectuser_link {
  893:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  894:         $coursedom,$linktext,$caller) = @_;
  895:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  896:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  897:            ');">'.$linktext.'</a>';
  898: }
  899: 
  900: sub check_uncheck_jscript {
  901:     my $jscript = <<"ENDSCRT";
  902: function checkAll(field) {
  903:     if (field.length > 0) {
  904:         for (i = 0; i < field.length; i++) {
  905:             if (!field[i].disabled) { 
  906:                 field[i].checked = true;
  907:             }
  908:         }
  909:     } else {
  910:         if (!field.disabled) { 
  911:             field.checked = true;
  912:         }
  913:     }
  914: }
  915:  
  916: function uncheckAll(field) {
  917:     if (field.length > 0) {
  918:         for (i = 0; i < field.length; i++) {
  919:             field[i].checked = false ;
  920:         }
  921:     } else {
  922:         field.checked = false ;
  923:     }
  924: }
  925: ENDSCRT
  926:     return $jscript;
  927: }
  928: 
  929: sub select_timezone {
  930:    my ($name,$selected,$onchange,$includeempty)=@_;
  931:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  932:    if ($includeempty) {
  933:        $output .= '<option value=""';
  934:        if (($selected eq '') || ($selected eq 'local')) {
  935:            $output .= ' selected="selected" ';
  936:        }
  937:        $output .= '> </option>';
  938:    }
  939:    my @timezones = DateTime::TimeZone->all_names;
  940:    foreach my $tzone (@timezones) {
  941:        $output.= '<option value="'.$tzone.'"';
  942:        if ($tzone eq $selected) {
  943:            $output.=' selected="selected"';
  944:        }
  945:        $output.=">$tzone</option>\n";
  946:    }
  947:    $output.="</select>";
  948:    return $output;
  949: }
  950: 
  951: sub select_datelocale {
  952:     my ($name,$selected,$onchange,$includeempty)=@_;
  953:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  954:     if ($includeempty) {
  955:         $output .= '<option value=""';
  956:         if ($selected eq '') {
  957:             $output .= ' selected="selected" ';
  958:         }
  959:         $output .= '> </option>';
  960:     }
  961:     my (@possibles,%locale_names);
  962:     my @locales = DateTime::Locale::Catalog::Locales;
  963:     foreach my $locale (@locales) {
  964:         if (ref($locale) eq 'HASH') {
  965:             my $id = $locale->{'id'};
  966:             if ($id ne '') {
  967:                 my $en_terr = $locale->{'en_territory'};
  968:                 my $native_terr = $locale->{'native_territory'};
  969:                 my @languages = &Apache::lonlocal::preferred_languages();
  970:                 if (grep(/^en$/,@languages) || !@languages) {
  971:                     if ($en_terr ne '') {
  972:                         $locale_names{$id} = '('.$en_terr.')';
  973:                     } elsif ($native_terr ne '') {
  974:                         $locale_names{$id} = $native_terr;
  975:                     }
  976:                 } else {
  977:                     if ($native_terr ne '') {
  978:                         $locale_names{$id} = $native_terr.' ';
  979:                     } elsif ($en_terr ne '') {
  980:                         $locale_names{$id} = '('.$en_terr.')';
  981:                     }
  982:                 }
  983:                 push (@possibles,$id);
  984:             }
  985:         }
  986:     }
  987:     foreach my $item (sort(@possibles)) {
  988:         $output.= '<option value="'.$item.'"';
  989:         if ($item eq $selected) {
  990:             $output.=' selected="selected"';
  991:         }
  992:         $output.=">$item";
  993:         if ($locale_names{$item} ne '') {
  994:             $output.="  $locale_names{$item}</option>\n";
  995:         }
  996:         $output.="</option>\n";
  997:     }
  998:     $output.="</select>";
  999:     return $output;
 1000: }
 1001: 
 1002: sub select_language {
 1003:     my ($name,$selected,$includeempty) = @_;
 1004:     my %langchoices;
 1005:     if ($includeempty) {
 1006:         %langchoices = ('' => 'No language preference');
 1007:     }
 1008:     foreach my $id (&languageids()) {
 1009:         my $code = &supportedlanguagecode($id);
 1010:         if ($code) {
 1011:             $langchoices{$code} = &plainlanguagedescription($id);
 1012:         }
 1013:     }
 1014:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1015:     return &select_form($selected,$name,\%langchoices);
 1016: }
 1017: 
 1018: =pod
 1019: 
 1020: 
 1021: =item * &list_languages()
 1022: 
 1023: Returns an array reference that is suitable for use in language prompters.
 1024: Each array element is itself a two element array.  The first element
 1025: is the language code.  The second element a descsriptiuon of the 
 1026: language itself.  This is suitable for use in e.g.
 1027: &Apache::edit::select_arg (once dereferenced that is).
 1028: 
 1029: =cut 
 1030: 
 1031: sub list_languages {
 1032:     my @lang_choices;
 1033: 
 1034:     foreach my $id (&languageids()) {
 1035: 	my $code = &supportedlanguagecode($id);
 1036: 	if ($code) {
 1037: 	    my $selector    = $supported_codes{$id};
 1038: 	    my $description = &plainlanguagedescription($id);
 1039: 	    push (@lang_choices, [$selector, $description]);
 1040: 	}
 1041:     }
 1042:     return \@lang_choices;
 1043: }
 1044: 
 1045: =pod
 1046: 
 1047: =item * &linked_select_forms(...)
 1048: 
 1049: linked_select_forms returns a string containing a <script></script> block
 1050: and html for two <select> menus.  The select menus will be linked in that
 1051: changing the value of the first menu will result in new values being placed
 1052: in the second menu.  The values in the select menu will appear in alphabetical
 1053: order unless a defined order is provided.
 1054: 
 1055: linked_select_forms takes the following ordered inputs:
 1056: 
 1057: =over 4
 1058: 
 1059: =item * $formname, the name of the <form> tag
 1060: 
 1061: =item * $middletext, the text which appears between the <select> tags
 1062: 
 1063: =item * $firstdefault, the default value for the first menu
 1064: 
 1065: =item * $firstselectname, the name of the first <select> tag
 1066: 
 1067: =item * $secondselectname, the name of the second <select> tag
 1068: 
 1069: =item * $hashref, a reference to a hash containing the data for the menus.
 1070: 
 1071: =item * $menuorder, the order of values in the first menu
 1072: 
 1073: =item * $onchangefirst, additional javascript call to execute for an onchange
 1074:         event for the first <select> tag
 1075: 
 1076: =item * $onchangesecond, additional javascript call to execute for an onchange
 1077:         event for the second <select> tag
 1078: 
 1079: =back 
 1080: 
 1081: Below is an example of such a hash.  Only the 'text', 'default', and 
 1082: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1083: values for the first select menu.  The text that coincides with the 
 1084: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1085: and text for the second menu are given in the hash pointed to by 
 1086: $menu{$choice1}->{'select2'}.  
 1087: 
 1088:  my %menu = ( A1 => { text =>"Choice A1" ,
 1089:                        default => "B3",
 1090:                        select2 => { 
 1091:                            B1 => "Choice B1",
 1092:                            B2 => "Choice B2",
 1093:                            B3 => "Choice B3",
 1094:                            B4 => "Choice B4"
 1095:                            },
 1096:                        order => ['B4','B3','B1','B2'],
 1097:                    },
 1098:                A2 => { text =>"Choice A2" ,
 1099:                        default => "C2",
 1100:                        select2 => { 
 1101:                            C1 => "Choice C1",
 1102:                            C2 => "Choice C2",
 1103:                            C3 => "Choice C3"
 1104:                            },
 1105:                        order => ['C2','C1','C3'],
 1106:                    },
 1107:                A3 => { text =>"Choice A3" ,
 1108:                        default => "D6",
 1109:                        select2 => { 
 1110:                            D1 => "Choice D1",
 1111:                            D2 => "Choice D2",
 1112:                            D3 => "Choice D3",
 1113:                            D4 => "Choice D4",
 1114:                            D5 => "Choice D5",
 1115:                            D6 => "Choice D6",
 1116:                            D7 => "Choice D7"
 1117:                            },
 1118:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1119:                    }
 1120:                );
 1121: 
 1122: =cut
 1123: 
 1124: sub linked_select_forms {
 1125:     my ($formname,
 1126:         $middletext,
 1127:         $firstdefault,
 1128:         $firstselectname,
 1129:         $secondselectname, 
 1130:         $hashref,
 1131:         $menuorder,
 1132:         $onchangefirst,
 1133:         $onchangesecond
 1134:         ) = @_;
 1135:     my $second = "document.$formname.$secondselectname";
 1136:     my $first = "document.$formname.$firstselectname";
 1137:     # output the javascript to do the changing
 1138:     my $result = '';
 1139:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1140:     $result.="// <![CDATA[\n";
 1141:     $result.="var select2data = new Object();\n";
 1142:     $" = '","';
 1143:     my $debug = '';
 1144:     foreach my $s1 (sort(keys(%$hashref))) {
 1145:         $result.="select2data.d_$s1 = new Object();\n";        
 1146:         $result.="select2data.d_$s1.def = new String('".
 1147:             $hashref->{$s1}->{'default'}."');\n";
 1148:         $result.="select2data.d_$s1.values = new Array(";
 1149:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1150:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1151:             @s2values = @{$hashref->{$s1}->{'order'}};
 1152:         }
 1153:         $result.="\"@s2values\");\n";
 1154:         $result.="select2data.d_$s1.texts = new Array(";        
 1155:         my @s2texts;
 1156:         foreach my $value (@s2values) {
 1157:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1158:         }
 1159:         $result.="\"@s2texts\");\n";
 1160:     }
 1161:     $"=' ';
 1162:     $result.= <<"END";
 1163: 
 1164: function select1_changed() {
 1165:     // Determine new choice
 1166:     var newvalue = "d_" + $first.value;
 1167:     // update select2
 1168:     var values     = select2data[newvalue].values;
 1169:     var texts      = select2data[newvalue].texts;
 1170:     var select2def = select2data[newvalue].def;
 1171:     var i;
 1172:     // out with the old
 1173:     for (i = 0; i < $second.options.length; i++) {
 1174:         $second.options[i] = null;
 1175:     }
 1176:     // in with the nuclear
 1177:     for (i=0;i<values.length; i++) {
 1178:         $second.options[i] = new Option(values[i]);
 1179:         $second.options[i].value = values[i];
 1180:         $second.options[i].text = texts[i];
 1181:         if (values[i] == select2def) {
 1182:             $second.options[i].selected = true;
 1183:         }
 1184:     }
 1185: }
 1186: // ]]>
 1187: </script>
 1188: END
 1189:     # output the initial values for the selection lists
 1190:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1191:     my @order = sort(keys(%{$hashref}));
 1192:     if (ref($menuorder) eq 'ARRAY') {
 1193:         @order = @{$menuorder};
 1194:     }
 1195:     foreach my $value (@order) {
 1196:         $result.="    <option value=\"$value\" ";
 1197:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1198:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1199:     }
 1200:     $result .= "</select>\n";
 1201:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1202:     $result .= $middletext;
 1203:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1204:     if ($onchangesecond) {
 1205:         $result .= ' onchange="'.$onchangesecond.'"';
 1206:     }
 1207:     $result .= ">\n";
 1208:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1209:     
 1210:     my @secondorder = sort(keys(%select2));
 1211:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1212:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1213:     }
 1214:     foreach my $value (@secondorder) {
 1215:         $result.="    <option value=\"$value\" ";        
 1216:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1217:         $result.=">".&mt($select2{$value})."</option>\n";
 1218:     }
 1219:     $result .= "</select>\n";
 1220:     #    return $debug;
 1221:     return $result;
 1222: }   #  end of sub linked_select_forms {
 1223: 
 1224: =pod
 1225: 
 1226: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1227: 
 1228: Returns a string corresponding to an HTML link to the given help
 1229: $topic, where $topic corresponds to the name of a .tex file in
 1230: /home/httpd/html/adm/help/tex, with underscores replaced by
 1231: spaces. 
 1232: 
 1233: $text will optionally be linked to the same topic, allowing you to
 1234: link text in addition to the graphic. If you do not want to link
 1235: text, but wish to specify one of the later parameters, pass an
 1236: empty string. 
 1237: 
 1238: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1239: the link will not open a new window. If false, the link will open
 1240: a new window using Javascript. (Default is false.) 
 1241: 
 1242: $width and $height are optional numerical parameters that will
 1243: override the width and height of the popped up window, which may
 1244: be useful for certain help topics with big pictures included.
 1245: 
 1246: $imgid is the id of the img tag used for the help icon. This may be
 1247: used in a javascript call to switch the image src.  See 
 1248: lonhtmlcommon::htmlareaselectactive() for an example.
 1249: 
 1250: =cut
 1251: 
 1252: sub help_open_topic {
 1253:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1254:     $text = "" if (not defined $text);
 1255:     $stayOnPage = 0 if (not defined $stayOnPage);
 1256:     $width = 500 if (not defined $width);
 1257:     $height = 400 if (not defined $height);
 1258:     my $filename = $topic;
 1259:     $filename =~ s/ /_/g;
 1260: 
 1261:     my $template = "";
 1262:     my $link;
 1263:     
 1264:     $topic=~s/\W/\_/g;
 1265: 
 1266:     if (!$stayOnPage) {
 1267: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1268:     } elsif ($stayOnPage eq 'popup') {
 1269:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1270:     } else {
 1271: 	$link = "/adm/help/${filename}.hlp";
 1272:     }
 1273: 
 1274:     # Add the text
 1275:     if ($text ne "") {	
 1276: 	$template.='<span class="LC_help_open_topic">'
 1277:                   .'<a target="_top" href="'.$link.'">'
 1278:                   .$text.'</a>';
 1279:     }
 1280: 
 1281:     # (Always) Add the graphic
 1282:     my $title = &mt('Online Help');
 1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1284:     if ($imgid ne '') {
 1285:         $imgid = ' id="'.$imgid.'"';
 1286:     }
 1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1288:               .'<img src="'.$helpicon.'" border="0"'
 1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1291:               .' /></a>';
 1292:     if ($text ne "") {	
 1293:         $template.='</span>';
 1294:     }
 1295:     return $template;
 1296: 
 1297: }
 1298: 
 1299: # This is a quicky function for Latex cheatsheet editing, since it 
 1300: # appears in at least four places
 1301: sub helpLatexCheatsheet {
 1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1303:     my $out;
 1304:     my $addOther = '';
 1305:     if ($topic) {
 1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1307:     }
 1308:     $out = '<span>' # Start cheatsheet
 1309: 	  .$addOther
 1310:           .'<span>'
 1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1312: 	  .'</span> <span>'
 1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1314: 	  .'</span>';
 1315:     unless ($not_author) {
 1316:         $out .= ' <span>'
 1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1318: 	       .'</span>';
 1319:     }
 1320:     $out .= '</span>'; # End cheatsheet
 1321:     return $out;
 1322: }
 1323: 
 1324: sub general_help {
 1325:     my $helptopic='Student_Intro';
 1326:     if ($env{'request.role'}=~/^(ca|au)/) {
 1327: 	$helptopic='Authoring_Intro';
 1328:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1329: 	$helptopic='Course_Coordination_Intro';
 1330:     } elsif ($env{'request.role'}=~/^dc/) {
 1331:         $helptopic='Domain_Coordination_Intro';
 1332:     }
 1333:     return $helptopic;
 1334: }
 1335: 
 1336: sub update_help_link {
 1337:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1338:     my $origurl = $ENV{'REQUEST_URI'};
 1339:     $origurl=~s|^/~|/priv/|;
 1340:     my $timestamp = time;
 1341:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1342:         $$datum = &escape($$datum);
 1343:     }
 1344: 
 1345:     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";
 1346:     my $output .= <<"ENDOUTPUT";
 1347: <script type="text/javascript">
 1348: // <![CDATA[
 1349: banner_link = '$banner_link';
 1350: // ]]>
 1351: </script>
 1352: ENDOUTPUT
 1353:     return $output;
 1354: }
 1355: 
 1356: # now just updates the help link and generates a blue icon
 1357: sub help_open_menu {
 1358:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1359: 	= @_;    
 1360:     $stayOnPage = 1;
 1361:     my $output;
 1362:     if ($component_help) {
 1363: 	if (!$text) {
 1364: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1365: 				       $width,$height);
 1366: 	} else {
 1367: 	    my $help_text;
 1368: 	    $help_text=&unescape($topic);
 1369: 	    $output='<table><tr><td>'.
 1370: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1371: 				 $width,$height).'</td></tr></table>';
 1372: 	}
 1373:     }
 1374:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1375:     return $output.$banner_link;
 1376: }
 1377: 
 1378: sub top_nav_help {
 1379:     my ($text) = @_;
 1380:     $text = &mt($text);
 1381:     my $stay_on_page = 1;
 1382: 
 1383:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1384: 	                     : "javascript:helpMenu('open')";
 1385:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1386: 
 1387:     my $title = &mt('Get help');
 1388: 
 1389:     return <<"END";
 1390: $banner_link
 1391: <a href="$link" title="$title">$text</a>
 1392: END
 1393: }
 1394: 
 1395: sub help_menu_js {
 1396:     my ($httphost) = @_;
 1397:     my $stayOnPage = 1;
 1398:     my $width = 620;
 1399:     my $height = 600;
 1400:     my $helptopic=&general_help();
 1401:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1402:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1403:     my $start_page =
 1404:         &Apache::loncommon::start_page('Help Menu', undef,
 1405: 				       {'frameset'    => 1,
 1406: 					'js_ready'    => 1,
 1407:                                         'use_absolute' => $httphost,
 1408: 					'add_entries' => {
 1409: 					    'border' => '0',
 1410: 					    'rows'   => "110,*",},});
 1411:     my $end_page =
 1412:         &Apache::loncommon::end_page({'frameset' => 1,
 1413: 				      'js_ready' => 1,});
 1414: 
 1415:     my $template .= <<"ENDTEMPLATE";
 1416: <script type="text/javascript">
 1417: // <![CDATA[
 1418: // <!-- BEGIN LON-CAPA Internal
 1419: var banner_link = '';
 1420: function helpMenu(target) {
 1421:     var caller = this;
 1422:     if (target == 'open') {
 1423:         var newWindow = null;
 1424:         try {
 1425:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1426:         }
 1427:         catch(error) {
 1428:             writeHelp(caller);
 1429:             return;
 1430:         }
 1431:         if (newWindow) {
 1432:             caller = newWindow;
 1433:         }
 1434:     }
 1435:     writeHelp(caller);
 1436:     return;
 1437: }
 1438: function writeHelp(caller) {
 1439:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1440:     caller.document.close()
 1441:     caller.focus()
 1442: }
 1443: // END LON-CAPA Internal -->
 1444: // ]]>
 1445: </script>
 1446: ENDTEMPLATE
 1447:     return $template;
 1448: }
 1449: 
 1450: sub help_open_bug {
 1451:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1452:     unless ($env{'user.adv'}) { return ''; }
 1453:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1454:     $text = "" if (not defined $text);
 1455: 	$stayOnPage=1;
 1456:     $width = 600 if (not defined $width);
 1457:     $height = 600 if (not defined $height);
 1458: 
 1459:     $topic=~s/\W+/\+/g;
 1460:     my $link='';
 1461:     my $template='';
 1462:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1463: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1464:     if (!$stayOnPage)
 1465:     {
 1466: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1467:     }
 1468:     else
 1469:     {
 1470: 	$link = $url;
 1471:     }
 1472:     # Add the text
 1473:     if ($text ne "")
 1474:     {
 1475: 	$template .= 
 1476:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1477:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1478:     }
 1479: 
 1480:     # Add the graphic
 1481:     my $title = &mt('Report a Bug');
 1482:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1483:     $template .= <<"ENDTEMPLATE";
 1484:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1485: ENDTEMPLATE
 1486:     if ($text ne '') { $template.='</td></tr></table>' };
 1487:     return $template;
 1488: 
 1489: }
 1490: 
 1491: sub help_open_faq {
 1492:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1493:     unless ($env{'user.adv'}) { return ''; }
 1494:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1495:     $text = "" if (not defined $text);
 1496: 	$stayOnPage=1;
 1497:     $width = 350 if (not defined $width);
 1498:     $height = 400 if (not defined $height);
 1499: 
 1500:     $topic=~s/\W+/\+/g;
 1501:     my $link='';
 1502:     my $template='';
 1503:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1504:     if (!$stayOnPage)
 1505:     {
 1506: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1507:     }
 1508:     else
 1509:     {
 1510: 	$link = $url;
 1511:     }
 1512: 
 1513:     # Add the text
 1514:     if ($text ne "")
 1515:     {
 1516: 	$template .= 
 1517:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1518:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1519:     }
 1520: 
 1521:     # Add the graphic
 1522:     my $title = &mt('View the FAQ');
 1523:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1524:     $template .= <<"ENDTEMPLATE";
 1525:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1526: ENDTEMPLATE
 1527:     if ($text ne '') { $template.='</td></tr></table>' };
 1528:     return $template;
 1529: 
 1530: }
 1531: 
 1532: ###############################################################
 1533: ###############################################################
 1534: 
 1535: =pod
 1536: 
 1537: =item * &change_content_javascript():
 1538: 
 1539: This and the next function allow you to create small sections of an
 1540: otherwise static HTML page that you can update on the fly with
 1541: Javascript, even in Netscape 4.
 1542: 
 1543: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1544: must be written to the HTML page once. It will prove the Javascript
 1545: function "change(name, content)". Calling the change function with the
 1546: name of the section 
 1547: you want to update, matching the name passed to C<changable_area>, and
 1548: the new content you want to put in there, will put the content into
 1549: that area.
 1550: 
 1551: B<Note>: Netscape 4 only reserves enough space for the changable area
 1552: to contain room for the original contents. You need to "make space"
 1553: for whatever changes you wish to make, and be B<sure> to check your
 1554: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1555: it's adequate for updating a one-line status display, but little more.
 1556: This script will set the space to 100% width, so you only need to
 1557: worry about height in Netscape 4.
 1558: 
 1559: Modern browsers are much less limiting, and if you can commit to the
 1560: user not using Netscape 4, this feature may be used freely with
 1561: pretty much any HTML.
 1562: 
 1563: =cut
 1564: 
 1565: sub change_content_javascript {
 1566:     # If we're on Netscape 4, we need to use Layer-based code
 1567:     if ($env{'browser.type'} eq 'netscape' &&
 1568: 	$env{'browser.version'} =~ /^4\./) {
 1569: 	return (<<NETSCAPE4);
 1570: 	function change(name, content) {
 1571: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1572: 	    doc.open();
 1573: 	    doc.write(content);
 1574: 	    doc.close();
 1575: 	}
 1576: NETSCAPE4
 1577:     } else {
 1578: 	# Otherwise, we need to use semi-standards-compliant code
 1579: 	# (technically, "innerHTML" isn't standard but the equivalent
 1580: 	# is really scary, and every useful browser supports it
 1581: 	return (<<DOMBASED);
 1582: 	function change(name, content) {
 1583: 	    element = document.getElementById(name);
 1584: 	    element.innerHTML = content;
 1585: 	}
 1586: DOMBASED
 1587:     }
 1588: }
 1589: 
 1590: =pod
 1591: 
 1592: =item * &changable_area($name,$origContent):
 1593: 
 1594: This provides a "changable area" that can be modified on the fly via
 1595: the Javascript code provided in C<change_content_javascript>. $name is
 1596: the name you will use to reference the area later; do not repeat the
 1597: same name on a given HTML page more then once. $origContent is what
 1598: the area will originally contain, which can be left blank.
 1599: 
 1600: =cut
 1601: 
 1602: sub changable_area {
 1603:     my ($name, $origContent) = @_;
 1604: 
 1605:     if ($env{'browser.type'} eq 'netscape' &&
 1606: 	$env{'browser.version'} =~ /^4\./) {
 1607: 	# If this is netscape 4, we need to use the Layer tag
 1608: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1609:     } else {
 1610: 	return "<span id='$name'>$origContent</span>";
 1611:     }
 1612: }
 1613: 
 1614: =pod
 1615: 
 1616: =item * &viewport_geometry_js 
 1617: 
 1618: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1619: 
 1620: =cut
 1621: 
 1622: 
 1623: sub viewport_geometry_js { 
 1624:     return <<"GEOMETRY";
 1625: var Geometry = {};
 1626: function init_geometry() {
 1627:     if (Geometry.init) { return };
 1628:     Geometry.init=1;
 1629:     if (window.innerHeight) {
 1630:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1631:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1632:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1633:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1634:     }
 1635:     else if (document.documentElement && document.documentElement.clientHeight) {
 1636:         Geometry.getViewportHeight =
 1637:             function() { return document.documentElement.clientHeight; };
 1638:         Geometry.getViewportWidth =
 1639:             function() { return document.documentElement.clientWidth; };
 1640: 
 1641:         Geometry.getHorizontalScroll =
 1642:             function() { return document.documentElement.scrollLeft; };
 1643:         Geometry.getVerticalScroll =
 1644:             function() { return document.documentElement.scrollTop; };
 1645:     }
 1646:     else if (document.body.clientHeight) {
 1647:         Geometry.getViewportHeight =
 1648:             function() { return document.body.clientHeight; };
 1649:         Geometry.getViewportWidth =
 1650:             function() { return document.body.clientWidth; };
 1651:         Geometry.getHorizontalScroll =
 1652:             function() { return document.body.scrollLeft; };
 1653:         Geometry.getVerticalScroll =
 1654:             function() { return document.body.scrollTop; };
 1655:     }
 1656: }
 1657: 
 1658: GEOMETRY
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &viewport_size_js()
 1664: 
 1665: 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. 
 1666: 
 1667: =cut
 1668: 
 1669: sub viewport_size_js {
 1670:     my $geometry = &viewport_geometry_js();
 1671:     return <<"DIMS";
 1672: 
 1673: $geometry
 1674: 
 1675: function getViewportDims(width,height) {
 1676:     init_geometry();
 1677:     width.value = Geometry.getViewportWidth();
 1678:     height.value = Geometry.getViewportHeight();
 1679:     return;
 1680: }
 1681: 
 1682: DIMS
 1683: }
 1684: 
 1685: =pod
 1686: 
 1687: =item * &resize_textarea_js()
 1688: 
 1689: emits the needed javascript to resize a textarea to be as big as possible
 1690: 
 1691: creates a function resize_textrea that takes two IDs first should be
 1692: the id of the element to resize, second should be the id of a div that
 1693: surrounds everything that comes after the textarea, this routine needs
 1694: to be attached to the <body> for the onload and onresize events.
 1695: 
 1696: =back
 1697: 
 1698: =cut
 1699: 
 1700: sub resize_textarea_js {
 1701:     my $geometry = &viewport_geometry_js();
 1702:     return <<"RESIZE";
 1703:     <script type="text/javascript">
 1704: // <![CDATA[
 1705: $geometry
 1706: 
 1707: function getX(element) {
 1708:     var x = 0;
 1709:     while (element) {
 1710: 	x += element.offsetLeft;
 1711: 	element = element.offsetParent;
 1712:     }
 1713:     return x;
 1714: }
 1715: function getY(element) {
 1716:     var y = 0;
 1717:     while (element) {
 1718: 	y += element.offsetTop;
 1719: 	element = element.offsetParent;
 1720:     }
 1721:     return y;
 1722: }
 1723: 
 1724: 
 1725: function resize_textarea(textarea_id,bottom_id) {
 1726:     init_geometry();
 1727:     var textarea        = document.getElementById(textarea_id);
 1728:     //alert(textarea);
 1729: 
 1730:     var textarea_top    = getY(textarea);
 1731:     var textarea_height = textarea.offsetHeight;
 1732:     var bottom          = document.getElementById(bottom_id);
 1733:     var bottom_top      = getY(bottom);
 1734:     var bottom_height   = bottom.offsetHeight;
 1735:     var window_height   = Geometry.getViewportHeight();
 1736:     var fudge           = 23;
 1737:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1738:     if (new_height < 300) {
 1739: 	new_height = 300;
 1740:     }
 1741:     textarea.style.height=new_height+'px';
 1742: }
 1743: // ]]>
 1744: </script>
 1745: RESIZE
 1746: 
 1747: }
 1748: 
 1749: =pod
 1750: 
 1751: =head1 Excel and CSV file utility routines
 1752: 
 1753: =cut
 1754: 
 1755: ###############################################################
 1756: ###############################################################
 1757: 
 1758: =pod
 1759: 
 1760: =over 4
 1761: 
 1762: =item * &csv_translate($text) 
 1763: 
 1764: Translate $text to allow it to be output as a 'comma separated values' 
 1765: format.
 1766: 
 1767: =cut
 1768: 
 1769: ###############################################################
 1770: ###############################################################
 1771: sub csv_translate {
 1772:     my $text = shift;
 1773:     $text =~ s/\"/\"\"/g;
 1774:     $text =~ s/\n/ /g;
 1775:     return $text;
 1776: }
 1777: 
 1778: ###############################################################
 1779: ###############################################################
 1780: 
 1781: =pod
 1782: 
 1783: =item * &define_excel_formats()
 1784: 
 1785: Define some commonly used Excel cell formats.
 1786: 
 1787: Currently supported formats:
 1788: 
 1789: =over 4
 1790: 
 1791: =item header
 1792: 
 1793: =item bold
 1794: 
 1795: =item h1
 1796: 
 1797: =item h2
 1798: 
 1799: =item h3
 1800: 
 1801: =item h4
 1802: 
 1803: =item i
 1804: 
 1805: =item date
 1806: 
 1807: =back
 1808: 
 1809: Inputs: $workbook
 1810: 
 1811: Returns: $format, a hash reference.
 1812: 
 1813: 
 1814: =cut
 1815: 
 1816: ###############################################################
 1817: ###############################################################
 1818: sub define_excel_formats {
 1819:     my ($workbook) = @_;
 1820:     my $format;
 1821:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1822:                                                 bottom    => 1,
 1823:                                                 align     => 'center');
 1824:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1825:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1826:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1827:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1828:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1829:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1830:     $format->{'date'} = $workbook->add_format(num_format=>
 1831:                                             'mm/dd/yyyy hh:mm:ss');
 1832:     return $format;
 1833: }
 1834: 
 1835: ###############################################################
 1836: ###############################################################
 1837: 
 1838: =pod
 1839: 
 1840: =item * &create_workbook()
 1841: 
 1842: Create an Excel worksheet.  If it fails, output message on the
 1843: request object and return undefs.
 1844: 
 1845: Inputs: Apache request object
 1846: 
 1847: Returns (undef) on failure, 
 1848:     Excel worksheet object, scalar with filename, and formats 
 1849:     from &Apache::loncommon::define_excel_formats on success
 1850: 
 1851: =cut
 1852: 
 1853: ###############################################################
 1854: ###############################################################
 1855: sub create_workbook {
 1856:     my ($r) = @_;
 1857:         #
 1858:     # Create the excel spreadsheet
 1859:     my $filename = '/prtspool/'.
 1860:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1861:         time.'_'.rand(1000000000).'.xls';
 1862:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1863:     if (! defined($workbook)) {
 1864:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1865:         $r->print(
 1866:             '<p class="LC_error">'
 1867:            .&mt('Problems occurred in creating the new Excel file.')
 1868:            .' '.&mt('This error has been logged.')
 1869:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1870:            .'</p>'
 1871:         );
 1872:         return (undef);
 1873:     }
 1874:     #
 1875:     $workbook->set_tempdir(LONCAPA::tempdir());
 1876:     #
 1877:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1878:     return ($workbook,$filename,$format);
 1879: }
 1880: 
 1881: ###############################################################
 1882: ###############################################################
 1883: 
 1884: =pod
 1885: 
 1886: =item * &create_text_file()
 1887: 
 1888: Create a file to write to and eventually make available to the user.
 1889: If file creation fails, outputs an error message on the request object and 
 1890: return undefs.
 1891: 
 1892: Inputs: Apache request object, and file suffix
 1893: 
 1894: Returns (undef) on failure, 
 1895:     Filehandle and filename on success.
 1896: 
 1897: =cut
 1898: 
 1899: ###############################################################
 1900: ###############################################################
 1901: sub create_text_file {
 1902:     my ($r,$suffix) = @_;
 1903:     if (! defined($suffix)) { $suffix = 'txt'; };
 1904:     my $fh;
 1905:     my $filename = '/prtspool/'.
 1906:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1907:         time.'_'.rand(1000000000).'.'.$suffix;
 1908:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1909:     if (! defined($fh)) {
 1910:         $r->log_error("Couldn't open $filename for output $!");
 1911:         $r->print(
 1912:             '<p class="LC_error">'
 1913:            .&mt('Problems occurred in creating the output file.')
 1914:            .' '.&mt('This error has been logged.')
 1915:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1916:            .'</p>'
 1917:         );
 1918:     }
 1919:     return ($fh,$filename)
 1920: }
 1921: 
 1922: 
 1923: =pod 
 1924: 
 1925: =back
 1926: 
 1927: =cut
 1928: 
 1929: ###############################################################
 1930: ##        Home server <option> list generating code          ##
 1931: ###############################################################
 1932: 
 1933: # ------------------------------------------
 1934: 
 1935: sub domain_select {
 1936:     my ($name,$value,$multiple)=@_;
 1937:     my %domains=map { 
 1938: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1939:     } &Apache::lonnet::all_domains();
 1940:     if ($multiple) {
 1941: 	$domains{''}=&mt('Any domain');
 1942: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1943: 	return &multiple_select_form($name,$value,4,\%domains);
 1944:     } else {
 1945: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1946: 	return &select_form($name,$value,\%domains);
 1947:     }
 1948: }
 1949: 
 1950: #-------------------------------------------
 1951: 
 1952: =pod
 1953: 
 1954: =head1 Routines for form select boxes
 1955: 
 1956: =over 4
 1957: 
 1958: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1959: 
 1960: Returns a string containing a <select> element int multiple mode
 1961: 
 1962: 
 1963: Args:
 1964:   $name - name of the <select> element
 1965:   $value - scalar or array ref of values that should already be selected
 1966:   $size - number of rows long the select element is
 1967:   $hash - the elements should be 'option' => 'shown text'
 1968:           (shown text should already have been &mt())
 1969:   $order - (optional) array ref of the order to show the elements in
 1970: 
 1971: =cut
 1972: 
 1973: #-------------------------------------------
 1974: sub multiple_select_form {
 1975:     my ($name,$value,$size,$hash,$order)=@_;
 1976:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1977:     my $output='';
 1978:     if (! defined($size)) {
 1979:         $size = 4;
 1980:         if (scalar(keys(%$hash))<4) {
 1981:             $size = scalar(keys(%$hash));
 1982:         }
 1983:     }
 1984:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1985:     my @order;
 1986:     if (ref($order) eq 'ARRAY')  {
 1987:         @order = @{$order};
 1988:     } else {
 1989:         @order = sort(keys(%$hash));
 1990:     }
 1991:     if (exists($$hash{'select_form_order'})) {
 1992:         @order = @{$$hash{'select_form_order'}};
 1993:     }
 1994:         
 1995:     foreach my $key (@order) {
 1996:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1997:         $output.='selected="selected" ' if ($selected{$key});
 1998:         $output.='>'.$hash->{$key}."</option>\n";
 1999:     }
 2000:     $output.="</select>\n";
 2001:     return $output;
 2002: }
 2003: 
 2004: #-------------------------------------------
 2005: 
 2006: =pod
 2007: 
 2008: =item * &select_form($defdom,$name,$hashref,$onchange)
 2009: 
 2010: Returns a string containing a <select name='$name' size='1'> form to 
 2011: allow a user to select options from a ref to a hash containing:
 2012: option_name => displayed text. An optional $onchange can include
 2013: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2014: 
 2015: See lonrights.pm for an example invocation and use.
 2016: 
 2017: =cut
 2018: 
 2019: #-------------------------------------------
 2020: sub select_form {
 2021:     my ($def,$name,$hashref,$onchange) = @_;
 2022:     return unless (ref($hashref) eq 'HASH');
 2023:     if ($onchange) {
 2024:         $onchange = ' onchange="'.$onchange.'"';
 2025:     }
 2026:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2027:     my @keys;
 2028:     if (exists($hashref->{'select_form_order'})) {
 2029: 	@keys=@{$hashref->{'select_form_order'}};
 2030:     } else {
 2031: 	@keys=sort(keys(%{$hashref}));
 2032:     }
 2033:     foreach my $key (@keys) {
 2034:         $selectform.=
 2035: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2036:             ($key eq $def ? 'selected="selected" ' : '').
 2037:                 ">".$hashref->{$key}."</option>\n";
 2038:     }
 2039:     $selectform.="</select>";
 2040:     return $selectform;
 2041: }
 2042: 
 2043: # For display filters
 2044: 
 2045: sub display_filter {
 2046:     my ($context) = @_;
 2047:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2048:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2049:     my $phraseinput = 'hidden';
 2050:     my $includeinput = 'hidden';
 2051:     my ($checked,$includetypestext);
 2052:     if ($env{'form.displayfilter'} eq 'containing') {
 2053:         $phraseinput = 'text'; 
 2054:         if ($context eq 'parmslog') {
 2055:             $includeinput = 'checkbox';
 2056:             if ($env{'form.includetypes'}) {
 2057:                 $checked = ' checked="checked"';
 2058:             }
 2059:             $includetypestext = &mt('Include parameter types');
 2060:         }
 2061:     } else {
 2062:         $includetypestext = '&nbsp;';
 2063:     }
 2064:     my ($additional,$secondid,$thirdid);
 2065:     if ($context eq 'parmslog') {
 2066:         $additional = 
 2067:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2068:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2069:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2070:             '</label>';
 2071:         $secondid = 'includetypes';
 2072:         $thirdid = 'includetypestext';
 2073:     }
 2074:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2075:                                                     '$secondid','$thirdid')";
 2076:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2077: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2078: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2079: 	   '</label></span> <span class="LC_nobreak">'.
 2080:            &mt('Filter: [_1]',
 2081: 	   &select_form($env{'form.displayfilter'},
 2082: 			'displayfilter',
 2083: 			{'currentfolder' => 'Current folder/page',
 2084: 			 'containing' => 'Containing phrase',
 2085: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2086: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2087:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2088:                          '" />'.$additional;
 2089: }
 2090: 
 2091: sub display_filter_js {
 2092:     my $includetext = &mt('Include parameter types');
 2093:     return <<"ENDJS";
 2094:   
 2095: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2096:     var firstType = 'hidden';
 2097:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2098:         firstType = 'text';
 2099:     }
 2100:     firstObject = document.getElementById(firstid);
 2101:     if (typeof(firstObject) == 'object') {
 2102:         if (firstObject.type != firstType) {
 2103:             changeInputType(firstObject,firstType);
 2104:         }
 2105:     }
 2106:     if (context == 'parmslog') {
 2107:         var secondType = 'hidden';
 2108:         if (firstType == 'text') {
 2109:             secondType = 'checkbox';
 2110:         }
 2111:         secondObject = document.getElementById(secondid);  
 2112:         if (typeof(secondObject) == 'object') {
 2113:             if (secondObject.type != secondType) {
 2114:                 changeInputType(secondObject,secondType);
 2115:             }
 2116:         }
 2117:         var textItem = document.getElementById(thirdid);
 2118:         var currtext = textItem.innerHTML;
 2119:         var newtext;
 2120:         if (firstType == 'text') {
 2121:             newtext = '$includetext';
 2122:         } else {
 2123:             newtext = '&nbsp;';
 2124:         }
 2125:         if (currtext != newtext) {
 2126:             textItem.innerHTML = newtext;
 2127:         }
 2128:     }
 2129:     return;
 2130: }
 2131: 
 2132: function changeInputType(oldObject,newType) {
 2133:     var newObject = document.createElement('input');
 2134:     newObject.type = newType;
 2135:     if (oldObject.size) {
 2136:         newObject.size = oldObject.size;
 2137:     }
 2138:     if (oldObject.value) {
 2139:         newObject.value = oldObject.value;
 2140:     }
 2141:     if (oldObject.name) {
 2142:         newObject.name = oldObject.name;
 2143:     }
 2144:     if (oldObject.id) {
 2145:         newObject.id = oldObject.id;
 2146:     }
 2147:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2148:     return;
 2149: }
 2150: 
 2151: ENDJS
 2152: }
 2153: 
 2154: sub gradeleveldescription {
 2155:     my $gradelevel=shift;
 2156:     my %gradelevels=(0 => 'Not specified',
 2157: 		     1 => 'Grade 1',
 2158: 		     2 => 'Grade 2',
 2159: 		     3 => 'Grade 3',
 2160: 		     4 => 'Grade 4',
 2161: 		     5 => 'Grade 5',
 2162: 		     6 => 'Grade 6',
 2163: 		     7 => 'Grade 7',
 2164: 		     8 => 'Grade 8',
 2165: 		     9 => 'Grade 9',
 2166: 		     10 => 'Grade 10',
 2167: 		     11 => 'Grade 11',
 2168: 		     12 => 'Grade 12',
 2169: 		     13 => 'Grade 13',
 2170: 		     14 => '100 Level',
 2171: 		     15 => '200 Level',
 2172: 		     16 => '300 Level',
 2173: 		     17 => '400 Level',
 2174: 		     18 => 'Graduate Level');
 2175:     return &mt($gradelevels{$gradelevel});
 2176: }
 2177: 
 2178: sub select_level_form {
 2179:     my ($deflevel,$name)=@_;
 2180:     unless ($deflevel) { $deflevel=0; }
 2181:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2182:     for (my $i=0; $i<=18; $i++) {
 2183:         $selectform.="<option value=\"$i\" ".
 2184:             ($i==$deflevel ? 'selected="selected" ' : '').
 2185:                 ">".&gradeleveldescription($i)."</option>\n";
 2186:     }
 2187:     $selectform.="</select>";
 2188:     return $selectform;
 2189: }
 2190: 
 2191: #-------------------------------------------
 2192: 
 2193: =pod
 2194: 
 2195: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2196: 
 2197: Returns a string containing a <select name='$name' size='1'> form to 
 2198: allow a user to select the domain to preform an operation in.  
 2199: See loncreateuser.pm for an example invocation and use.
 2200: 
 2201: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2202: selected");
 2203: 
 2204: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2205: 
 2206: 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.
 2207: 
 2208: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2209: 
 2210: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2211: 
 2212: =cut
 2213: 
 2214: #-------------------------------------------
 2215: sub select_dom_form {
 2216:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2217:     if ($onchange) {
 2218:         $onchange = ' onchange="'.$onchange.'"';
 2219:     }
 2220:     my (@domains,%exclude);
 2221:     if (ref($incdoms) eq 'ARRAY') {
 2222:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2223:     } else {
 2224:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2225:     }
 2226:     if ($includeempty) { @domains=('',@domains); }
 2227:     if (ref($excdoms) eq 'ARRAY') {
 2228:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2229:     }
 2230:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2231:     foreach my $dom (@domains) {
 2232:         next if ($exclude{$dom});
 2233:         $selectdomain.="<option value=\"$dom\" ".
 2234:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2235:         if ($showdomdesc) {
 2236:             if ($dom ne '') {
 2237:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2238:                 if ($domdesc ne '') {
 2239:                     $selectdomain .= ' ('.$domdesc.')';
 2240:                 }
 2241:             } 
 2242:         }
 2243:         $selectdomain .= "</option>\n";
 2244:     }
 2245:     $selectdomain.="</select>";
 2246:     return $selectdomain;
 2247: }
 2248: 
 2249: #-------------------------------------------
 2250: 
 2251: =pod
 2252: 
 2253: =item * &home_server_form_item($domain,$name,$defaultflag)
 2254: 
 2255: input: 4 arguments (two required, two optional) - 
 2256:     $domain - domain of new user
 2257:     $name - name of form element
 2258:     $default - Value of 'default' causes a default item to be first 
 2259:                             option, and selected by default. 
 2260:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2261:                             if 1 server found, or default, if 0 found.
 2262: output: returns 2 items: 
 2263: (a) form element which contains either:
 2264:    (i) <select name="$name">
 2265:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2266:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2267:        </select>
 2268:        form item if there are multiple library servers in $domain, or
 2269:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2270:        if there is only one library server in $domain.
 2271: 
 2272: (b) number of library servers found.
 2273: 
 2274: See loncreateuser.pm for example of use.
 2275: 
 2276: =cut
 2277: 
 2278: #-------------------------------------------
 2279: sub home_server_form_item {
 2280:     my ($domain,$name,$default,$hide) = @_;
 2281:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2282:     my $result;
 2283:     my $numlib = keys(%servers);
 2284:     if ($numlib > 1) {
 2285:         $result .= '<select name="'.$name.'" />'."\n";
 2286:         if ($default) {
 2287:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2288:                        '</option>'."\n";
 2289:         }
 2290:         foreach my $hostid (sort(keys(%servers))) {
 2291:             $result.= '<option value="'.$hostid.'">'.
 2292: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2293:         }
 2294:         $result .= '</select>'."\n";
 2295:     } elsif ($numlib == 1) {
 2296:         my $hostid;
 2297:         foreach my $item (keys(%servers)) {
 2298:             $hostid = $item;
 2299:         }
 2300:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2301:                    $hostid.'" />';
 2302:                    if (!$hide) {
 2303:                        $result .= $hostid.' '.$servers{$hostid};
 2304:                    }
 2305:                    $result .= "\n";
 2306:     } elsif ($default) {
 2307:         $result .= '<input type="hidden" name="'.$name.
 2308:                    '" value="default" />';
 2309:                    if (!$hide) {
 2310:                        $result .= &mt('default');
 2311:                    }
 2312:                    $result .= "\n";
 2313:     }
 2314:     return ($result,$numlib);
 2315: }
 2316: 
 2317: =pod
 2318: 
 2319: =back 
 2320: 
 2321: =cut
 2322: 
 2323: ###############################################################
 2324: ##                  Decoding User Agent                      ##
 2325: ###############################################################
 2326: 
 2327: =pod
 2328: 
 2329: =head1 Decoding the User Agent
 2330: 
 2331: =over 4
 2332: 
 2333: =item * &decode_user_agent()
 2334: 
 2335: Inputs: $r
 2336: 
 2337: Outputs:
 2338: 
 2339: =over 4
 2340: 
 2341: =item * $httpbrowser
 2342: 
 2343: =item * $clientbrowser
 2344: 
 2345: =item * $clientversion
 2346: 
 2347: =item * $clientmathml
 2348: 
 2349: =item * $clientunicode
 2350: 
 2351: =item * $clientos
 2352: 
 2353: =item * $clientmobile
 2354: 
 2355: =item * $clientinfo
 2356: 
 2357: =back
 2358: 
 2359: =back 
 2360: 
 2361: =cut
 2362: 
 2363: ###############################################################
 2364: ###############################################################
 2365: sub decode_user_agent {
 2366:     my ($r)=@_;
 2367:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2368:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2369:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2370:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2371:     my $clientbrowser='unknown';
 2372:     my $clientversion='0';
 2373:     my $clientmathml='';
 2374:     my $clientunicode='0';
 2375:     my $clientmobile=0;
 2376:     for (my $i=0;$i<=$#browsertype;$i++) {
 2377:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2378: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2379: 	    $clientbrowser=$bname;
 2380:             $httpbrowser=~/$vreg/i;
 2381: 	    $clientversion=$1;
 2382:             $clientmathml=($clientversion>=$minv);
 2383:             $clientunicode=($clientversion>=$univ);
 2384: 	}
 2385:     }
 2386:     my $clientos='unknown';
 2387:     my $clientinfo;
 2388:     if (($httpbrowser=~/linux/i) ||
 2389:         ($httpbrowser=~/unix/i) ||
 2390:         ($httpbrowser=~/ux/i) ||
 2391:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2392:     if (($httpbrowser=~/vax/i) ||
 2393:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2394:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2395:     if (($httpbrowser=~/mac/i) ||
 2396:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2397:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2398:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2399:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2400:         $clientmobile=lc($1);
 2401:     }
 2402:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2403:         $clientinfo = 'firefox-'.$1;
 2404:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2405:         $clientinfo = 'chromeframe-'.$1;
 2406:     }
 2407:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2408:             $clientunicode,$clientos,$clientmobile,$clientinfo);
 2409: }
 2410: 
 2411: ###############################################################
 2412: ##    Authentication changing form generation subroutines    ##
 2413: ###############################################################
 2414: ##
 2415: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2416: ## hash, and have reasonable default values.
 2417: ##
 2418: ##    formname = the name given in the <form> tag.
 2419: #-------------------------------------------
 2420: 
 2421: =pod
 2422: 
 2423: =head1 Authentication Routines
 2424: 
 2425: =over 4
 2426: 
 2427: =item * &authform_xxxxxx()
 2428: 
 2429: The authform_xxxxxx subroutines provide javascript and html forms which 
 2430: handle some of the conveniences required for authentication forms.  
 2431: This is not an optimal method, but it works.  
 2432: 
 2433: =over 4
 2434: 
 2435: =item * authform_header
 2436: 
 2437: =item * authform_authorwarning
 2438: 
 2439: =item * authform_nochange
 2440: 
 2441: =item * authform_kerberos
 2442: 
 2443: =item * authform_internal
 2444: 
 2445: =item * authform_filesystem
 2446: 
 2447: =back
 2448: 
 2449: See loncreateuser.pm for invocation and use examples.
 2450: 
 2451: =cut
 2452: 
 2453: #-------------------------------------------
 2454: sub authform_header{  
 2455:     my %in = (
 2456:         formname => 'cu',
 2457:         kerb_def_dom => '',
 2458:         @_,
 2459:     );
 2460:     $in{'formname'} = 'document.' . $in{'formname'};
 2461:     my $result='';
 2462: 
 2463: #---------------------------------------------- Code for upper case translation
 2464:     my $Javascript_toUpperCase;
 2465:     unless ($in{kerb_def_dom}) {
 2466:         $Javascript_toUpperCase =<<"END";
 2467:         switch (choice) {
 2468:            case 'krb': currentform.elements[choicearg].value =
 2469:                currentform.elements[choicearg].value.toUpperCase();
 2470:                break;
 2471:            default:
 2472:         }
 2473: END
 2474:     } else {
 2475:         $Javascript_toUpperCase = "";
 2476:     }
 2477: 
 2478:     my $radioval = "'nochange'";
 2479:     if (defined($in{'curr_authtype'})) {
 2480:         if ($in{'curr_authtype'} ne '') {
 2481:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2482:         }
 2483:     }
 2484:     my $argfield = 'null';
 2485:     if (defined($in{'mode'})) {
 2486:         if ($in{'mode'} eq 'modifycourse')  {
 2487:             if (defined($in{'curr_autharg'})) {
 2488:                 if ($in{'curr_autharg'} ne '') {
 2489:                     $argfield = "'$in{'curr_autharg'}'";
 2490:                 }
 2491:             }
 2492:         }
 2493:     }
 2494: 
 2495:     $result.=<<"END";
 2496: var current = new Object();
 2497: current.radiovalue = $radioval;
 2498: current.argfield = $argfield;
 2499: 
 2500: function changed_radio(choice,currentform) {
 2501:     var choicearg = choice + 'arg';
 2502:     // If a radio button in changed, we need to change the argfield
 2503:     if (current.radiovalue != choice) {
 2504:         current.radiovalue = choice;
 2505:         if (current.argfield != null) {
 2506:             currentform.elements[current.argfield].value = '';
 2507:         }
 2508:         if (choice == 'nochange') {
 2509:             current.argfield = null;
 2510:         } else {
 2511:             current.argfield = choicearg;
 2512:             switch(choice) {
 2513:                 case 'krb': 
 2514:                     currentform.elements[current.argfield].value = 
 2515:                         "$in{'kerb_def_dom'}";
 2516:                 break;
 2517:               default:
 2518:                 break;
 2519:             }
 2520:         }
 2521:     }
 2522:     return;
 2523: }
 2524: 
 2525: function changed_text(choice,currentform) {
 2526:     var choicearg = choice + 'arg';
 2527:     if (currentform.elements[choicearg].value !='') {
 2528:         $Javascript_toUpperCase
 2529:         // clear old field
 2530:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2531:             currentform.elements[current.argfield].value = '';
 2532:         }
 2533:         current.argfield = choicearg;
 2534:     }
 2535:     set_auth_radio_buttons(choice,currentform);
 2536:     return;
 2537: }
 2538: 
 2539: function set_auth_radio_buttons(newvalue,currentform) {
 2540:     var numauthchoices = currentform.login.length;
 2541:     if (typeof numauthchoices  == "undefined") {
 2542:         return;
 2543:     } 
 2544:     var i=0;
 2545:     while (i < numauthchoices) {
 2546:         if (currentform.login[i].value == newvalue) { break; }
 2547:         i++;
 2548:     }
 2549:     if (i == numauthchoices) {
 2550:         return;
 2551:     }
 2552:     current.radiovalue = newvalue;
 2553:     currentform.login[i].checked = true;
 2554:     return;
 2555: }
 2556: END
 2557:     return $result;
 2558: }
 2559: 
 2560: sub authform_authorwarning {
 2561:     my $result='';
 2562:     $result='<i>'.
 2563:         &mt('As a general rule, only authors or co-authors should be '.
 2564:             'filesystem authenticated '.
 2565:             '(which allows access to the server filesystem).')."</i>\n";
 2566:     return $result;
 2567: }
 2568: 
 2569: sub authform_nochange {
 2570:     my %in = (
 2571:               formname => 'document.cu',
 2572:               kerb_def_dom => 'MSU.EDU',
 2573:               @_,
 2574:           );
 2575:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2576:     my $result;
 2577:     if (!$authnum) {
 2578:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2579:     } else {
 2580:         $result = '<label>'.&mt('[_1] Do not change login data',
 2581:                   '<input type="radio" name="login" value="nochange" '.
 2582:                   'checked="checked" onclick="'.
 2583:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2584: 	    '</label>';
 2585:     }
 2586:     return $result;
 2587: }
 2588: 
 2589: sub authform_kerberos {
 2590:     my %in = (
 2591:               formname => 'document.cu',
 2592:               kerb_def_dom => 'MSU.EDU',
 2593:               kerb_def_auth => 'krb4',
 2594:               @_,
 2595:               );
 2596:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2597:         $autharg,$jscall);
 2598:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2599:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2600:        $check5 = ' checked="checked"';
 2601:     } else {
 2602:        $check4 = ' checked="checked"';
 2603:     }
 2604:     $krbarg = $in{'kerb_def_dom'};
 2605:     if (defined($in{'curr_authtype'})) {
 2606:         if ($in{'curr_authtype'} eq 'krb') {
 2607:             $krbcheck = ' checked="checked"';
 2608:             if (defined($in{'mode'})) {
 2609:                 if ($in{'mode'} eq 'modifyuser') {
 2610:                     $krbcheck = '';
 2611:                 }
 2612:             }
 2613:             if (defined($in{'curr_kerb_ver'})) {
 2614:                 if ($in{'curr_krb_ver'} eq '5') {
 2615:                     $check5 = ' checked="checked"';
 2616:                     $check4 = '';
 2617:                 } else {
 2618:                     $check4 = ' checked="checked"';
 2619:                     $check5 = '';
 2620:                 }
 2621:             }
 2622:             if (defined($in{'curr_autharg'})) {
 2623:                 $krbarg = $in{'curr_autharg'};
 2624:             }
 2625:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2626:                 if (defined($in{'curr_autharg'})) {
 2627:                     $result = 
 2628:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2629:         $in{'curr_autharg'},$krbver);
 2630:                 } else {
 2631:                     $result =
 2632:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2633:                 }
 2634:                 return $result; 
 2635:             }
 2636:         }
 2637:     } else {
 2638:         if ($authnum == 1) {
 2639:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2640:         }
 2641:     }
 2642:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2643:         return;
 2644:     } elsif ($authtype eq '') {
 2645:         if (defined($in{'mode'})) {
 2646:             if ($in{'mode'} eq 'modifycourse') {
 2647:                 if ($authnum == 1) {
 2648:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2649:                 }
 2650:             }
 2651:         }
 2652:     }
 2653:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2654:     if ($authtype eq '') {
 2655:         $authtype = '<input type="radio" name="login" value="krb" '.
 2656:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2657:                     $krbcheck.' />';
 2658:     }
 2659:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2660:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2661:          $in{'curr_authtype'} eq 'krb5') ||
 2662:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2663:          $in{'curr_authtype'} eq 'krb4')) {
 2664:         $result .= &mt
 2665:         ('[_1] Kerberos authenticated with domain [_2] '.
 2666:          '[_3] Version 4 [_4] Version 5 [_5]',
 2667:          '<label>'.$authtype,
 2668:          '</label><input type="text" size="10" name="krbarg" '.
 2669:              'value="'.$krbarg.'" '.
 2670:              'onchange="'.$jscall.'" />',
 2671:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2672:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2673: 	 '</label>');
 2674:     } elsif ($can_assign{'krb4'}) {
 2675:         $result .= &mt
 2676:         ('[_1] Kerberos authenticated with domain [_2] '.
 2677:          '[_3] Version 4 [_4]',
 2678:          '<label>'.$authtype,
 2679:          '</label><input type="text" size="10" name="krbarg" '.
 2680:              'value="'.$krbarg.'" '.
 2681:              'onchange="'.$jscall.'" />',
 2682:          '<label><input type="hidden" name="krbver" value="4" />',
 2683:          '</label>');
 2684:     } elsif ($can_assign{'krb5'}) {
 2685:         $result .= &mt
 2686:         ('[_1] Kerberos authenticated with domain [_2] '.
 2687:          '[_3] Version 5 [_4]',
 2688:          '<label>'.$authtype,
 2689:          '</label><input type="text" size="10" name="krbarg" '.
 2690:              'value="'.$krbarg.'" '.
 2691:              'onchange="'.$jscall.'" />',
 2692:          '<label><input type="hidden" name="krbver" value="5" />',
 2693:          '</label>');
 2694:     }
 2695:     return $result;
 2696: }
 2697: 
 2698: sub authform_internal {
 2699:     my %in = (
 2700:                 formname => 'document.cu',
 2701:                 kerb_def_dom => 'MSU.EDU',
 2702:                 @_,
 2703:                 );
 2704:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2705:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2706:     if (defined($in{'curr_authtype'})) {
 2707:         if ($in{'curr_authtype'} eq 'int') {
 2708:             if ($can_assign{'int'}) {
 2709:                 $intcheck = 'checked="checked" ';
 2710:                 if (defined($in{'mode'})) {
 2711:                     if ($in{'mode'} eq 'modifyuser') {
 2712:                         $intcheck = '';
 2713:                     }
 2714:                 }
 2715:                 if (defined($in{'curr_autharg'})) {
 2716:                     $intarg = $in{'curr_autharg'};
 2717:                 }
 2718:             } else {
 2719:                 $result = &mt('Currently internally authenticated.');
 2720:                 return $result;
 2721:             }
 2722:         }
 2723:     } else {
 2724:         if ($authnum == 1) {
 2725:             $authtype = '<input type="hidden" name="login" value="int" />';
 2726:         }
 2727:     }
 2728:     if (!$can_assign{'int'}) {
 2729:         return;
 2730:     } elsif ($authtype eq '') {
 2731:         if (defined($in{'mode'})) {
 2732:             if ($in{'mode'} eq 'modifycourse') {
 2733:                 if ($authnum == 1) {
 2734:                     $authtype = '<input type="radio" name="login" value="int" />';
 2735:                 }
 2736:             }
 2737:         }
 2738:     }
 2739:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2740:     if ($authtype eq '') {
 2741:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2742:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2743:     }
 2744:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2745:                $intarg.'" onchange="'.$jscall.'" />';
 2746:     $result = &mt
 2747:         ('[_1] Internally authenticated (with initial password [_2])',
 2748:          '<label>'.$authtype,'</label>'.$autharg);
 2749:     $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>';
 2750:     return $result;
 2751: }
 2752: 
 2753: sub authform_local {
 2754:     my %in = (
 2755:               formname => 'document.cu',
 2756:               kerb_def_dom => 'MSU.EDU',
 2757:               @_,
 2758:               );
 2759:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2760:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2761:     if (defined($in{'curr_authtype'})) {
 2762:         if ($in{'curr_authtype'} eq 'loc') {
 2763:             if ($can_assign{'loc'}) {
 2764:                 $loccheck = 'checked="checked" ';
 2765:                 if (defined($in{'mode'})) {
 2766:                     if ($in{'mode'} eq 'modifyuser') {
 2767:                         $loccheck = '';
 2768:                     }
 2769:                 }
 2770:                 if (defined($in{'curr_autharg'})) {
 2771:                     $locarg = $in{'curr_autharg'};
 2772:                 }
 2773:             } else {
 2774:                 $result = &mt('Currently using local (institutional) authentication.');
 2775:                 return $result;
 2776:             }
 2777:         }
 2778:     } else {
 2779:         if ($authnum == 1) {
 2780:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2781:         }
 2782:     }
 2783:     if (!$can_assign{'loc'}) {
 2784:         return;
 2785:     } elsif ($authtype eq '') {
 2786:         if (defined($in{'mode'})) {
 2787:             if ($in{'mode'} eq 'modifycourse') {
 2788:                 if ($authnum == 1) {
 2789:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2790:                 }
 2791:             }
 2792:         }
 2793:     }
 2794:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2795:     if ($authtype eq '') {
 2796:         $authtype = '<input type="radio" name="login" value="loc" '.
 2797:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2798:                     $jscall.'" />';
 2799:     }
 2800:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2801:                $locarg.'" onchange="'.$jscall.'" />';
 2802:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2803:                   '<label>'.$authtype,'</label>'.$autharg);
 2804:     return $result;
 2805: }
 2806: 
 2807: sub authform_filesystem {
 2808:     my %in = (
 2809:               formname => 'document.cu',
 2810:               kerb_def_dom => 'MSU.EDU',
 2811:               @_,
 2812:               );
 2813:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2814:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2815:     if (defined($in{'curr_authtype'})) {
 2816:         if ($in{'curr_authtype'} eq 'fsys') {
 2817:             if ($can_assign{'fsys'}) {
 2818:                 $fsyscheck = 'checked="checked" ';
 2819:                 if (defined($in{'mode'})) {
 2820:                     if ($in{'mode'} eq 'modifyuser') {
 2821:                         $fsyscheck = '';
 2822:                     }
 2823:                 }
 2824:             } else {
 2825:                 $result = &mt('Currently Filesystem Authenticated.');
 2826:                 return $result;
 2827:             }           
 2828:         }
 2829:     } else {
 2830:         if ($authnum == 1) {
 2831:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2832:         }
 2833:     }
 2834:     if (!$can_assign{'fsys'}) {
 2835:         return;
 2836:     } elsif ($authtype eq '') {
 2837:         if (defined($in{'mode'})) {
 2838:             if ($in{'mode'} eq 'modifycourse') {
 2839:                 if ($authnum == 1) {
 2840:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2841:                 }
 2842:             }
 2843:         }
 2844:     }
 2845:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2846:     if ($authtype eq '') {
 2847:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2848:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2849:                     $jscall.'" />';
 2850:     }
 2851:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2852:                ' onchange="'.$jscall.'" />';
 2853:     $result = &mt
 2854:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2855:          '<label><input type="radio" name="login" value="fsys" '.
 2856:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2857:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2858:                   'onchange="'.$jscall.'" />');
 2859:     return $result;
 2860: }
 2861: 
 2862: sub get_assignable_auth {
 2863:     my ($dom) = @_;
 2864:     if ($dom eq '') {
 2865:         $dom = $env{'request.role.domain'};
 2866:     }
 2867:     my %can_assign = (
 2868:                           krb4 => 1,
 2869:                           krb5 => 1,
 2870:                           int  => 1,
 2871:                           loc  => 1,
 2872:                      );
 2873:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2874:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2875:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2876:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2877:             my $context;
 2878:             if ($env{'request.role'} =~ /^au/) {
 2879:                 $context = 'author';
 2880:             } elsif ($env{'request.role'} =~ /^dc/) {
 2881:                 $context = 'domain';
 2882:             } elsif ($env{'request.course.id'}) {
 2883:                 $context = 'course';
 2884:             }
 2885:             if ($context) {
 2886:                 if (ref($authhash->{$context}) eq 'HASH') {
 2887:                    %can_assign = %{$authhash->{$context}}; 
 2888:                 }
 2889:             }
 2890:         }
 2891:     }
 2892:     my $authnum = 0;
 2893:     foreach my $key (keys(%can_assign)) {
 2894:         if ($can_assign{$key}) {
 2895:             $authnum ++;
 2896:         }
 2897:     }
 2898:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2899:         $authnum --;
 2900:     }
 2901:     return ($authnum,%can_assign);
 2902: }
 2903: 
 2904: ###############################################################
 2905: ##    Get Kerberos Defaults for Domain                 ##
 2906: ###############################################################
 2907: ##
 2908: ## Returns default kerberos version and an associated argument
 2909: ## as listed in file domain.tab. If not listed, provides
 2910: ## appropriate default domain and kerberos version.
 2911: ##
 2912: #-------------------------------------------
 2913: 
 2914: =pod
 2915: 
 2916: =item * &get_kerberos_defaults()
 2917: 
 2918: get_kerberos_defaults($target_domain) returns the default kerberos
 2919: version and domain. If not found, it defaults to version 4 and the 
 2920: domain of the server.
 2921: 
 2922: =over 4
 2923: 
 2924: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2925: 
 2926: =back
 2927: 
 2928: =back
 2929: 
 2930: =cut
 2931: 
 2932: #-------------------------------------------
 2933: sub get_kerberos_defaults {
 2934:     my $domain=shift;
 2935:     my ($krbdef,$krbdefdom);
 2936:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2937:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2938:         $krbdef = $domdefaults{'auth_def'};
 2939:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2940:     } else {
 2941:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2942:         my $krbdefdom=$1;
 2943:         $krbdefdom=~tr/a-z/A-Z/;
 2944:         $krbdef = "krb4";
 2945:     }
 2946:     return ($krbdef,$krbdefdom);
 2947: }
 2948: 
 2949: 
 2950: ###############################################################
 2951: ##                Thesaurus Functions                        ##
 2952: ###############################################################
 2953: 
 2954: =pod
 2955: 
 2956: =head1 Thesaurus Functions
 2957: 
 2958: =over 4
 2959: 
 2960: =item * &initialize_keywords()
 2961: 
 2962: Initializes the package variable %Keywords if it is empty.  Uses the
 2963: package variable $thesaurus_db_file.
 2964: 
 2965: =cut
 2966: 
 2967: ###################################################
 2968: 
 2969: sub initialize_keywords {
 2970:     return 1 if (scalar keys(%Keywords));
 2971:     # If we are here, %Keywords is empty, so fill it up
 2972:     #   Make sure the file we need exists...
 2973:     if (! -e $thesaurus_db_file) {
 2974:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2975:                                  " failed because it does not exist");
 2976:         return 0;
 2977:     }
 2978:     #   Set up the hash as a database
 2979:     my %thesaurus_db;
 2980:     if (! tie(%thesaurus_db,'GDBM_File',
 2981:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2982:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2983:                                  $thesaurus_db_file);
 2984:         return 0;
 2985:     } 
 2986:     #  Get the average number of appearances of a word.
 2987:     my $avecount = $thesaurus_db{'average.count'};
 2988:     #  Put keywords (those that appear > average) into %Keywords
 2989:     while (my ($word,$data)=each (%thesaurus_db)) {
 2990:         my ($count,undef) = split /:/,$data;
 2991:         $Keywords{$word}++ if ($count > $avecount);
 2992:     }
 2993:     untie %thesaurus_db;
 2994:     # Remove special values from %Keywords.
 2995:     foreach my $value ('total.count','average.count') {
 2996:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2997:   }
 2998:     return 1;
 2999: }
 3000: 
 3001: ###################################################
 3002: 
 3003: =pod
 3004: 
 3005: =item * &keyword($word)
 3006: 
 3007: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3008: than the average number of times in the thesaurus database.  Calls 
 3009: &initialize_keywords
 3010: 
 3011: =cut
 3012: 
 3013: ###################################################
 3014: 
 3015: sub keyword {
 3016:     return if (!&initialize_keywords());
 3017:     my $word=lc(shift());
 3018:     $word=~s/\W//g;
 3019:     return exists($Keywords{$word});
 3020: }
 3021: 
 3022: ###############################################################
 3023: 
 3024: =pod 
 3025: 
 3026: =item * &get_related_words()
 3027: 
 3028: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3029: an array of words.  If the keyword is not in the thesaurus, an empty array
 3030: will be returned.  The order of the words returned is determined by the
 3031: database which holds them.
 3032: 
 3033: Uses global $thesaurus_db_file.
 3034: 
 3035: 
 3036: =cut
 3037: 
 3038: ###############################################################
 3039: sub get_related_words {
 3040:     my $keyword = shift;
 3041:     my %thesaurus_db;
 3042:     if (! -e $thesaurus_db_file) {
 3043:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3044:                                  "failed because the file does not exist");
 3045:         return ();
 3046:     }
 3047:     if (! tie(%thesaurus_db,'GDBM_File',
 3048:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3049:         return ();
 3050:     } 
 3051:     my @Words=();
 3052:     my $count=0;
 3053:     if (exists($thesaurus_db{$keyword})) {
 3054: 	# The first element is the number of times
 3055: 	# the word appears.  We do not need it now.
 3056: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3057: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3058: 	my $threshold=$mostfrequentcount/10;
 3059:         foreach my $possibleword (@RelatedWords) {
 3060:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3061:             if ($wordcount>$threshold) {
 3062: 		push(@Words,$word);
 3063:                 $count++;
 3064:                 if ($count>10) { last; }
 3065: 	    }
 3066:         }
 3067:     }
 3068:     untie %thesaurus_db;
 3069:     return @Words;
 3070: }
 3071: ###############################################################
 3072: #
 3073: #  Spell checking
 3074: #
 3075: 
 3076: =pod
 3077: 
 3078: =back
 3079: 
 3080: =head1 Spell checking
 3081: 
 3082: =over 4
 3083: 
 3084: =item * &check_spelling($wordlist $language)
 3085: 
 3086: Takes a string containing words and feeds it to an external
 3087: spellcheck program via a pipeline. Returns a string containing
 3088: them mis-spelled words.
 3089: 
 3090: Parameters:
 3091: 
 3092: =over 4
 3093: 
 3094: =item - $wordlist
 3095: 
 3096: String that will be fed into the spellcheck program.
 3097: 
 3098: =item - $language
 3099: 
 3100: Language string that specifies the language for which the spell
 3101: check will be performed.
 3102: 
 3103: =back
 3104: 
 3105: =back
 3106: 
 3107: Note: This sub assumes that aspell is installed.
 3108: 
 3109: 
 3110: =cut
 3111: 
 3112: 
 3113: sub check_spelling {
 3114:     my ($wordlist, $language) = @_;
 3115:     my @misspellings;
 3116:     
 3117:     # Generate the speller and set the langauge.
 3118:     # if explicitly selected:
 3119: 
 3120:     my $speller = Text::Aspell->new;
 3121:     if ($language) {
 3122: 	$speller->set_option('lang', $language);
 3123:     }
 3124: 
 3125:     # Turn the word list into an array of words by splittingon whitespace
 3126: 
 3127:     my @words = split(/\s+/, $wordlist);
 3128: 
 3129:     foreach my $word (@words) {
 3130: 	if(! $speller->check($word)) {
 3131: 	    push(@misspellings, $word);
 3132: 	}
 3133:     }
 3134:     return join(' ', @misspellings);
 3135:     
 3136: }
 3137: 
 3138: # -------------------------------------------------------------- Plaintext name
 3139: =pod
 3140: 
 3141: =head1 User Name Functions
 3142: 
 3143: =over 4
 3144: 
 3145: =item * &plainname($uname,$udom,$first)
 3146: 
 3147: Takes a users logon name and returns it as a string in
 3148: "first middle last generation" form 
 3149: if $first is set to 'lastname' then it returns it as
 3150: 'lastname generation, firstname middlename' if their is a lastname
 3151: 
 3152: =cut
 3153: 
 3154: 
 3155: ###############################################################
 3156: sub plainname {
 3157:     my ($uname,$udom,$first)=@_;
 3158:     return if (!defined($uname) || !defined($udom));
 3159:     my %names=&getnames($uname,$udom);
 3160:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3161: 					  $names{'middlename'},
 3162: 					  $names{'lastname'},
 3163: 					  $names{'generation'},$first);
 3164:     $name=~s/^\s+//;
 3165:     $name=~s/\s+$//;
 3166:     $name=~s/\s+/ /g;
 3167:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3168:     return $name;
 3169: }
 3170: 
 3171: # -------------------------------------------------------------------- Nickname
 3172: =pod
 3173: 
 3174: =item * &nickname($uname,$udom)
 3175: 
 3176: Gets a users name and returns it as a string as
 3177: 
 3178: "&quot;nickname&quot;"
 3179: 
 3180: if the user has a nickname or
 3181: 
 3182: "first middle last generation"
 3183: 
 3184: if the user does not
 3185: 
 3186: =cut
 3187: 
 3188: sub nickname {
 3189:     my ($uname,$udom)=@_;
 3190:     return if (!defined($uname) || !defined($udom));
 3191:     my %names=&getnames($uname,$udom);
 3192:     my $name=$names{'nickname'};
 3193:     if ($name) {
 3194:        $name='&quot;'.$name.'&quot;'; 
 3195:     } else {
 3196:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3197: 	     $names{'lastname'}.' '.$names{'generation'};
 3198:        $name=~s/\s+$//;
 3199:        $name=~s/\s+/ /g;
 3200:     }
 3201:     return $name;
 3202: }
 3203: 
 3204: sub getnames {
 3205:     my ($uname,$udom)=@_;
 3206:     return if (!defined($uname) || !defined($udom));
 3207:     if ($udom eq 'public' && $uname eq 'public') {
 3208: 	return ('lastname' => &mt('Public'));
 3209:     }
 3210:     my $id=$uname.':'.$udom;
 3211:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3212:     if ($cached) {
 3213: 	return %{$names};
 3214:     } else {
 3215: 	my %loadnames=&Apache::lonnet::get('environment',
 3216:                     ['firstname','middlename','lastname','generation','nickname'],
 3217: 					 $udom,$uname);
 3218: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3219: 	return %loadnames;
 3220:     }
 3221: }
 3222: 
 3223: # -------------------------------------------------------------------- getemails
 3224: 
 3225: =pod
 3226: 
 3227: =item * &getemails($uname,$udom)
 3228: 
 3229: Gets a user's email information and returns it as a hash with keys:
 3230: notification, critnotification, permanentemail
 3231: 
 3232: For notification and critnotification, values are comma-separated lists 
 3233: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3234:  
 3235: 
 3236: =cut
 3237: 
 3238: 
 3239: sub getemails {
 3240:     my ($uname,$udom)=@_;
 3241:     if ($udom eq 'public' && $uname eq 'public') {
 3242: 	return;
 3243:     }
 3244:     if (!$udom) { $udom=$env{'user.domain'}; }
 3245:     if (!$uname) { $uname=$env{'user.name'}; }
 3246:     my $id=$uname.':'.$udom;
 3247:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3248:     if ($cached) {
 3249: 	return %{$names};
 3250:     } else {
 3251: 	my %loadnames=&Apache::lonnet::get('environment',
 3252:                     			   ['notification','critnotification',
 3253: 					    'permanentemail'],
 3254: 					   $udom,$uname);
 3255: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3256: 	return %loadnames;
 3257:     }
 3258: }
 3259: 
 3260: sub flush_email_cache {
 3261:     my ($uname,$udom)=@_;
 3262:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3263:     if (!$uname) { $uname=$env{'user.name'};   }
 3264:     return if ($udom eq 'public' && $uname eq 'public');
 3265:     my $id=$uname.':'.$udom;
 3266:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3267: }
 3268: 
 3269: # -------------------------------------------------------------------- getlangs
 3270: 
 3271: =pod
 3272: 
 3273: =item * &getlangs($uname,$udom)
 3274: 
 3275: Gets a user's language preference and returns it as a hash with key:
 3276: language.
 3277: 
 3278: =cut
 3279: 
 3280: 
 3281: sub getlangs {
 3282:     my ($uname,$udom) = @_;
 3283:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3284:     if (!$uname) { $uname=$env{'user.name'};   }
 3285:     my $id=$uname.':'.$udom;
 3286:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3287:     if ($cached) {
 3288:         return %{$langs};
 3289:     } else {
 3290:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3291:                                            $udom,$uname);
 3292:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3293:         return %loadlangs;
 3294:     }
 3295: }
 3296: 
 3297: sub flush_langs_cache {
 3298:     my ($uname,$udom)=@_;
 3299:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3300:     if (!$uname) { $uname=$env{'user.name'};   }
 3301:     return if ($udom eq 'public' && $uname eq 'public');
 3302:     my $id=$uname.':'.$udom;
 3303:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3304: }
 3305: 
 3306: # ------------------------------------------------------------------ Screenname
 3307: 
 3308: =pod
 3309: 
 3310: =item * &screenname($uname,$udom)
 3311: 
 3312: Gets a users screenname and returns it as a string
 3313: 
 3314: =cut
 3315: 
 3316: sub screenname {
 3317:     my ($uname,$udom)=@_;
 3318:     if ($uname eq $env{'user.name'} &&
 3319: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3320:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3321:     return $names{'screenname'};
 3322: }
 3323: 
 3324: 
 3325: # ------------------------------------------------------------- Confirm Wrapper
 3326: =pod
 3327: 
 3328: =item * &confirmwrapper($message)
 3329: 
 3330: Wrap messages about completion of operation in box
 3331: 
 3332: =cut
 3333: 
 3334: sub confirmwrapper {
 3335:     my ($message)=@_;
 3336:     if ($message) {
 3337:         return "\n".'<div class="LC_confirm_box">'."\n"
 3338:                .$message."\n"
 3339:                .'</div>'."\n";
 3340:     } else {
 3341:         return $message;
 3342:     }
 3343: }
 3344: 
 3345: # ------------------------------------------------------------- Message Wrapper
 3346: 
 3347: sub messagewrapper {
 3348:     my ($link,$username,$domain,$subject,$text)=@_;
 3349:     return 
 3350:         '<a href="/adm/email?compose=individual&amp;'.
 3351:         'recname='.$username.'&amp;recdom='.$domain.
 3352: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3353:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3354: }
 3355: 
 3356: # --------------------------------------------------------------- Notes Wrapper
 3357: 
 3358: sub noteswrapper {
 3359:     my ($link,$un,$do)=@_;
 3360:     return 
 3361: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3362: }
 3363: 
 3364: # ------------------------------------------------------------- Aboutme Wrapper
 3365: 
 3366: sub aboutmewrapper {
 3367:     my ($link,$username,$domain,$target,$class)=@_;
 3368:     if (!defined($username)  && !defined($domain)) {
 3369:         return;
 3370:     }
 3371:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3372: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3373: }
 3374: 
 3375: # ------------------------------------------------------------ Syllabus Wrapper
 3376: 
 3377: sub syllabuswrapper {
 3378:     my ($linktext,$coursedir,$domain)=@_;
 3379:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3380: }
 3381: 
 3382: # -----------------------------------------------------------------------------
 3383: 
 3384: sub track_student_link {
 3385:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3386:     my $link ="/adm/trackstudent?";
 3387:     my $title = 'View recent activity';
 3388:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3389:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3390:         $link .= "selected_student=$sname:$sdom";
 3391:         $title .= ' of this student';
 3392:     } 
 3393:     if (defined($target) && $target !~ /^\s*$/) {
 3394:         $target = qq{target="$target"};
 3395:     } else {
 3396:         $target = '';
 3397:     }
 3398:     if ($start) { $link.='&amp;start='.$start; }
 3399:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3400:     $title = &mt($title);
 3401:     $linktext = &mt($linktext);
 3402:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3403: 	&help_open_topic('View_recent_activity');
 3404: }
 3405: 
 3406: sub slot_reservations_link {
 3407:     my ($linktext,$sname,$sdom,$target) = @_;
 3408:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3409:     my $title = 'View slot reservation history';
 3410:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3411:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3412:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3413:         $title .= ' of this student';
 3414:     }
 3415:     if (defined($target) && $target !~ /^\s*$/) {
 3416:         $target = qq{target="$target"};
 3417:     } else {
 3418:         $target = '';
 3419:     }
 3420:     $title = &mt($title);
 3421:     $linktext = &mt($linktext);
 3422:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3423: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3424: 
 3425: }
 3426: 
 3427: # ===================================================== Display a student photo
 3428: 
 3429: 
 3430: sub student_image_tag {
 3431:     my ($domain,$user)=@_;
 3432:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3433:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3434: 	return '<img src="'.$imgsrc.'" align="right" />';
 3435:     } else {
 3436: 	return '';
 3437:     }
 3438: }
 3439: 
 3440: =pod
 3441: 
 3442: =back
 3443: 
 3444: =head1 Access .tab File Data
 3445: 
 3446: =over 4
 3447: 
 3448: =item * &languageids() 
 3449: 
 3450: returns list of all language ids
 3451: 
 3452: =cut
 3453: 
 3454: sub languageids {
 3455:     return sort(keys(%language));
 3456: }
 3457: 
 3458: =pod
 3459: 
 3460: =item * &languagedescription() 
 3461: 
 3462: returns description of a specified language id
 3463: 
 3464: =cut
 3465: 
 3466: sub languagedescription {
 3467:     my $code=shift;
 3468:     return  ($supported_language{$code}?'* ':'').
 3469:             $language{$code}.
 3470: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3471: }
 3472: 
 3473: =pod
 3474: 
 3475: =item * &plainlanguagedescription
 3476: 
 3477: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3478: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3479: 
 3480: =cut
 3481: 
 3482: sub plainlanguagedescription {
 3483:     my $code=shift;
 3484:     return $language{$code};
 3485: }
 3486: 
 3487: =pod
 3488: 
 3489: =item * &supportedlanguagecode
 3490: 
 3491: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3492: code.
 3493: 
 3494: =cut
 3495: 
 3496: sub supportedlanguagecode {
 3497:     my $code=shift;
 3498:     return $supported_language{$code};
 3499: }
 3500: 
 3501: =pod
 3502: 
 3503: =item * &latexlanguage()
 3504: 
 3505: Given a language key code returns the correspondnig language to use
 3506: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3507: is no supported hyphenation for the language code.
 3508: 
 3509: =cut
 3510: 
 3511: sub latexlanguage {
 3512:     my $code = shift;
 3513:     return $latex_language{$code};
 3514: }
 3515: 
 3516: =pod
 3517: 
 3518: =item * &latexhyphenation()
 3519: 
 3520: Same as above but what's supplied is the language as it might be stored
 3521: in the metadata.
 3522: 
 3523: =cut
 3524: 
 3525: sub latexhyphenation {
 3526:     my $key = shift;
 3527:     return $latex_language_bykey{$key};
 3528: }
 3529: 
 3530: =pod
 3531: 
 3532: =item * &copyrightids() 
 3533: 
 3534: returns list of all copyrights
 3535: 
 3536: =cut
 3537: 
 3538: sub copyrightids {
 3539:     return sort(keys(%cprtag));
 3540: }
 3541: 
 3542: =pod
 3543: 
 3544: =item * &copyrightdescription() 
 3545: 
 3546: returns description of a specified copyright id
 3547: 
 3548: =cut
 3549: 
 3550: sub copyrightdescription {
 3551:     return &mt($cprtag{shift(@_)});
 3552: }
 3553: 
 3554: =pod
 3555: 
 3556: =item * &source_copyrightids() 
 3557: 
 3558: returns list of all source copyrights
 3559: 
 3560: =cut
 3561: 
 3562: sub source_copyrightids {
 3563:     return sort(keys(%scprtag));
 3564: }
 3565: 
 3566: =pod
 3567: 
 3568: =item * &source_copyrightdescription() 
 3569: 
 3570: returns description of a specified source copyright id
 3571: 
 3572: =cut
 3573: 
 3574: sub source_copyrightdescription {
 3575:     return &mt($scprtag{shift(@_)});
 3576: }
 3577: 
 3578: =pod
 3579: 
 3580: =item * &filecategories() 
 3581: 
 3582: returns list of all file categories
 3583: 
 3584: =cut
 3585: 
 3586: sub filecategories {
 3587:     return sort(keys(%category_extensions));
 3588: }
 3589: 
 3590: =pod
 3591: 
 3592: =item * &filecategorytypes() 
 3593: 
 3594: returns list of file types belonging to a given file
 3595: category
 3596: 
 3597: =cut
 3598: 
 3599: sub filecategorytypes {
 3600:     my ($cat) = @_;
 3601:     return @{$category_extensions{lc($cat)}};
 3602: }
 3603: 
 3604: =pod
 3605: 
 3606: =item * &fileembstyle() 
 3607: 
 3608: returns embedding style for a specified file type
 3609: 
 3610: =cut
 3611: 
 3612: sub fileembstyle {
 3613:     return $fe{lc(shift(@_))};
 3614: }
 3615: 
 3616: sub filemimetype {
 3617:     return $fm{lc(shift(@_))};
 3618: }
 3619: 
 3620: 
 3621: sub filecategoryselect {
 3622:     my ($name,$value)=@_;
 3623:     return &select_form($value,$name,
 3624:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3625: }
 3626: 
 3627: =pod
 3628: 
 3629: =item * &filedescription() 
 3630: 
 3631: returns description for a specified file type
 3632: 
 3633: =cut
 3634: 
 3635: sub filedescription {
 3636:     my $file_description = $fd{lc(shift())};
 3637:     $file_description =~ s:([\[\]]):~$1:g;
 3638:     return &mt($file_description);
 3639: }
 3640: 
 3641: =pod
 3642: 
 3643: =item * &filedescriptionex() 
 3644: 
 3645: returns description for a specified file type with
 3646: extra formatting
 3647: 
 3648: =cut
 3649: 
 3650: sub filedescriptionex {
 3651:     my $ex=shift;
 3652:     my $file_description = $fd{lc($ex)};
 3653:     $file_description =~ s:([\[\]]):~$1:g;
 3654:     return '.'.$ex.' '.&mt($file_description);
 3655: }
 3656: 
 3657: # End of .tab access
 3658: =pod
 3659: 
 3660: =back
 3661: 
 3662: =cut
 3663: 
 3664: # ------------------------------------------------------------------ File Types
 3665: sub fileextensions {
 3666:     return sort(keys(%fe));
 3667: }
 3668: 
 3669: # ----------------------------------------------------------- Display Languages
 3670: # returns a hash with all desired display languages
 3671: #
 3672: 
 3673: sub display_languages {
 3674:     my %languages=();
 3675:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3676: 	$languages{$lang}=1;
 3677:     }
 3678:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3679:     if ($env{'form.displaylanguage'}) {
 3680: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3681: 	    $languages{$lang}=1;
 3682:         }
 3683:     }
 3684:     return %languages;
 3685: }
 3686: 
 3687: sub languages {
 3688:     my ($possible_langs) = @_;
 3689:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3690:     if (!ref($possible_langs)) {
 3691: 	if( wantarray ) {
 3692: 	    return @preferred_langs;
 3693: 	} else {
 3694: 	    return $preferred_langs[0];
 3695: 	}
 3696:     }
 3697:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3698:     my @preferred_possibilities;
 3699:     foreach my $preferred_lang (@preferred_langs) {
 3700: 	if (exists($possibilities{$preferred_lang})) {
 3701: 	    push(@preferred_possibilities, $preferred_lang);
 3702: 	}
 3703:     }
 3704:     if( wantarray ) {
 3705: 	return @preferred_possibilities;
 3706:     }
 3707:     return $preferred_possibilities[0];
 3708: }
 3709: 
 3710: sub user_lang {
 3711:     my ($touname,$toudom,$fromcid) = @_;
 3712:     my @userlangs;
 3713:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3714:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3715:                     $env{'course.'.$fromcid.'.languages'}));
 3716:     } else {
 3717:         my %langhash = &getlangs($touname,$toudom);
 3718:         if ($langhash{'languages'} ne '') {
 3719:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3720:         } else {
 3721:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3722:             if ($domdefs{'lang_def'} ne '') {
 3723:                 @userlangs = ($domdefs{'lang_def'});
 3724:             }
 3725:         }
 3726:     }
 3727:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3728:     my $user_lh = Apache::localize->get_handle(@languages);
 3729:     return $user_lh;
 3730: }
 3731: 
 3732: 
 3733: ###############################################################
 3734: ##               Student Answer Attempts                     ##
 3735: ###############################################################
 3736: 
 3737: =pod
 3738: 
 3739: =head1 Alternate Problem Views
 3740: 
 3741: =over 4
 3742: 
 3743: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3744:     $getattempt, $regexp, $gradesub)
 3745: 
 3746: Return string with previous attempt on problem. Arguments:
 3747: 
 3748: =over 4
 3749: 
 3750: =item * $symb: Problem, including path
 3751: 
 3752: =item * $username: username of the desired student
 3753: 
 3754: =item * $domain: domain of the desired student
 3755: 
 3756: =item * $course: Course ID
 3757: 
 3758: =item * $getattempt: Leave blank for all attempts, otherwise put
 3759:     something
 3760: 
 3761: =item * $regexp: if string matches this regexp, the string will be
 3762:     sent to $gradesub
 3763: 
 3764: =item * $gradesub: routine that processes the string if it matches $regexp
 3765: 
 3766: =back
 3767: 
 3768: The output string is a table containing all desired attempts, if any.
 3769: 
 3770: =cut
 3771: 
 3772: sub get_previous_attempt {
 3773:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3774:   my $prevattempts='';
 3775:   no strict 'refs';
 3776:   if ($symb) {
 3777:     my (%returnhash)=
 3778:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3779:     if ($returnhash{'version'}) {
 3780:       my %lasthash=();
 3781:       my $version;
 3782:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3783:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3784: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3785:         }
 3786:       }
 3787:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3788:       $prevattempts.='<th>'.&mt('History').'</th>';
 3789:       my (%typeparts,%lasthidden);
 3790:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3791:       foreach my $key (sort(keys(%lasthash))) {
 3792: 	my ($ign,@parts) = split(/\./,$key);
 3793: 	if ($#parts > 0) {
 3794: 	  my $data=$parts[-1];
 3795:           next if ($data eq 'foilorder');
 3796: 	  pop(@parts);
 3797:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3798:           if ($data eq 'type') {
 3799:               unless ($showsurv) {
 3800:                   my $id = join(',',@parts);
 3801:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3802:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3803:                       $lasthidden{$ign.'.'.$id} = 1;
 3804:                   }
 3805:               }
 3806:           } 
 3807: 	} else {
 3808: 	  if ($#parts == 0) {
 3809: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3810: 	  } else {
 3811: 	    $prevattempts.='<th>'.$ign.'</th>';
 3812: 	  }
 3813: 	}
 3814:       }
 3815:       $prevattempts.=&end_data_table_header_row();
 3816:       if ($getattempt eq '') {
 3817: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3818:             my @hidden;
 3819:             if (%typeparts) {
 3820:                 foreach my $id (keys(%typeparts)) {
 3821:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3822:                         push(@hidden,$id);
 3823:                     }
 3824:                 }
 3825:             }
 3826:             $prevattempts.=&start_data_table_row().
 3827:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3828:             if (@hidden) {
 3829:                 foreach my $key (sort(keys(%lasthash))) {
 3830:                     next if ($key =~ /\.foilorder$/);
 3831:                     my $hide;
 3832:                     foreach my $id (@hidden) {
 3833:                         if ($key =~ /^\Q$id\E/) {
 3834:                             $hide = 1;
 3835:                             last;
 3836:                         }
 3837:                     }
 3838:                     if ($hide) {
 3839:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3840:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3841:                             my $value = &format_previous_attempt_value($key,
 3842:                                              $returnhash{$version.':'.$key});
 3843:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3844:                         } else {
 3845:                             $prevattempts.='<td>&nbsp;</td>';
 3846:                         }
 3847:                     } else {
 3848:                         if ($key =~ /\./) {
 3849:                             my $value = &format_previous_attempt_value($key,
 3850:                                               $returnhash{$version.':'.$key});
 3851:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3852:                         } else {
 3853:                             $prevattempts.='<td>&nbsp;</td>';
 3854:                         }
 3855:                     }
 3856:                 }
 3857:             } else {
 3858: 	        foreach my $key (sort(keys(%lasthash))) {
 3859:                     next if ($key =~ /\.foilorder$/);
 3860: 		    my $value = &format_previous_attempt_value($key,
 3861: 			            $returnhash{$version.':'.$key});
 3862: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3863: 	        }
 3864:             }
 3865: 	    $prevattempts.=&end_data_table_row();
 3866: 	 }
 3867:       }
 3868:       my @currhidden = keys(%lasthidden);
 3869:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3870:       foreach my $key (sort(keys(%lasthash))) {
 3871:           next if ($key =~ /\.foilorder$/);
 3872:           if (%typeparts) {
 3873:               my $hidden;
 3874:               foreach my $id (@currhidden) {
 3875:                   if ($key =~ /^\Q$id\E/) {
 3876:                       $hidden = 1;
 3877:                       last;
 3878:                   }
 3879:               }
 3880:               if ($hidden) {
 3881:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3882:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3883:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3884:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3885:                           $value = &$gradesub($value);
 3886:                       }
 3887:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3888:                   } else {
 3889:                       $prevattempts.='<td>&nbsp;</td>';
 3890:                   }
 3891:               } else {
 3892:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3893:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3894:                       $value = &$gradesub($value);
 3895:                   }
 3896:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3897:               }
 3898:           } else {
 3899: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3900: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3901:                   $value = &$gradesub($value);
 3902:               }
 3903: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3904:           }
 3905:       }
 3906:       $prevattempts.= &end_data_table_row().&end_data_table();
 3907:     } else {
 3908:       $prevattempts=
 3909: 	  &start_data_table().&start_data_table_row().
 3910: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3911: 	  &end_data_table_row().&end_data_table();
 3912:     }
 3913:   } else {
 3914:     $prevattempts=
 3915: 	  &start_data_table().&start_data_table_row().
 3916: 	  '<td>'.&mt('No data.').'</td>'.
 3917: 	  &end_data_table_row().&end_data_table();
 3918:   }
 3919: }
 3920: 
 3921: sub format_previous_attempt_value {
 3922:     my ($key,$value) = @_;
 3923:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3924: 	$value = &Apache::lonlocal::locallocaltime($value);
 3925:     } elsif (ref($value) eq 'ARRAY') {
 3926: 	$value = '('.join(', ', @{ $value }).')';
 3927:     } elsif ($key =~ /answerstring$/) {
 3928:         my %answers = &Apache::lonnet::str2hash($value);
 3929:         my @anskeys = sort(keys(%answers));
 3930:         if (@anskeys == 1) {
 3931:             my $answer = $answers{$anskeys[0]};
 3932:             if ($answer =~ m{\0}) {
 3933:                 $answer =~ s{\0}{,}g;
 3934:             }
 3935:             my $tag_internal_answer_name = 'INTERNAL';
 3936:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3937:                 $value = $answer; 
 3938:             } else {
 3939:                 $value = $anskeys[0].'='.$answer;
 3940:             }
 3941:         } else {
 3942:             foreach my $ans (@anskeys) {
 3943:                 my $answer = $answers{$ans};
 3944:                 if ($answer =~ m{\0}) {
 3945:                     $answer =~ s{\0}{,}g;
 3946:                 }
 3947:                 $value .=  $ans.'='.$answer.'<br />';;
 3948:             } 
 3949:         }
 3950:     } else {
 3951: 	$value = &unescape($value);
 3952:     }
 3953:     return $value;
 3954: }
 3955: 
 3956: 
 3957: sub relative_to_absolute {
 3958:     my ($url,$output)=@_;
 3959:     my $parser=HTML::TokeParser->new(\$output);
 3960:     my $token;
 3961:     my $thisdir=$url;
 3962:     my @rlinks=();
 3963:     while ($token=$parser->get_token) {
 3964: 	if ($token->[0] eq 'S') {
 3965: 	    if ($token->[1] eq 'a') {
 3966: 		if ($token->[2]->{'href'}) {
 3967: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3968: 		}
 3969: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3970: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3971: 	    } elsif ($token->[1] eq 'base') {
 3972: 		$thisdir=$token->[2]->{'href'};
 3973: 	    }
 3974: 	}
 3975:     }
 3976:     $thisdir=~s-/[^/]*$--;
 3977:     foreach my $link (@rlinks) {
 3978: 	unless (($link=~/^https?\:\/\//i) ||
 3979: 		($link=~/^\//) ||
 3980: 		($link=~/^javascript:/i) ||
 3981: 		($link=~/^mailto:/i) ||
 3982: 		($link=~/^\#/)) {
 3983: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3984: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3985: 	}
 3986:     }
 3987: # -------------------------------------------------- Deal with Applet codebases
 3988:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3989:     return $output;
 3990: }
 3991: 
 3992: =pod
 3993: 
 3994: =item * &get_student_view()
 3995: 
 3996: show a snapshot of what student was looking at
 3997: 
 3998: =cut
 3999: 
 4000: sub get_student_view {
 4001:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4002:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4003:   my (%form);
 4004:   my @elements=('symb','courseid','domain','username');
 4005:   foreach my $element (@elements) {
 4006:       $form{'grade_'.$element}=eval '$'.$element #'
 4007:   }
 4008:   if (defined($moreenv)) {
 4009:       %form=(%form,%{$moreenv});
 4010:   }
 4011:   if (defined($target)) { $form{'grade_target'} = $target; }
 4012:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4013:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4014:   $userview=~s/\<body[^\>]*\>//gi;
 4015:   $userview=~s/\<\/body\>//gi;
 4016:   $userview=~s/\<html\>//gi;
 4017:   $userview=~s/\<\/html\>//gi;
 4018:   $userview=~s/\<head\>//gi;
 4019:   $userview=~s/\<\/head\>//gi;
 4020:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4021:   $userview=&relative_to_absolute($feedurl,$userview);
 4022:   if (wantarray) {
 4023:      return ($userview,$response);
 4024:   } else {
 4025:      return $userview;
 4026:   }
 4027: }
 4028: 
 4029: sub get_student_view_with_retries {
 4030:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4031: 
 4032:     my $ok = 0;                 # True if we got a good response.
 4033:     my $content;
 4034:     my $response;
 4035: 
 4036:     # Try to get the student_view done. within the retries count:
 4037:     
 4038:     do {
 4039:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4040:          $ok      = $response->is_success;
 4041:          if (!$ok) {
 4042:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4043:          }
 4044:          $retries--;
 4045:     } while (!$ok && ($retries > 0));
 4046:     
 4047:     if (!$ok) {
 4048:        $content = '';          # On error return an empty content.
 4049:     }
 4050:     if (wantarray) {
 4051:        return ($content, $response);
 4052:     } else {
 4053:        return $content;
 4054:     }
 4055: }
 4056: 
 4057: =pod
 4058: 
 4059: =item * &get_student_answers() 
 4060: 
 4061: show a snapshot of how student was answering problem
 4062: 
 4063: =cut
 4064: 
 4065: sub get_student_answers {
 4066:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4067:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4068:   my (%moreenv);
 4069:   my @elements=('symb','courseid','domain','username');
 4070:   foreach my $element (@elements) {
 4071:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4072:   }
 4073:   $moreenv{'grade_target'}='answer';
 4074:   %moreenv=(%form,%moreenv);
 4075:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4076:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4077:   return $userview;
 4078: }
 4079: 
 4080: =pod
 4081: 
 4082: =item * &submlink()
 4083: 
 4084: Inputs: $text $uname $udom $symb $target
 4085: 
 4086: Returns: A link to grades.pm such as to see the SUBM view of a student
 4087: 
 4088: =cut
 4089: 
 4090: ###############################################
 4091: sub submlink {
 4092:     my ($text,$uname,$udom,$symb,$target)=@_;
 4093:     if (!($uname && $udom)) {
 4094: 	(my $cursymb, my $courseid,$udom,$uname)=
 4095: 	    &Apache::lonnet::whichuser($symb);
 4096: 	if (!$symb) { $symb=$cursymb; }
 4097:     }
 4098:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4099:     $symb=&escape($symb);
 4100:     if ($target) { $target=" target=\"$target\""; }
 4101:     return
 4102:         '<a href="/adm/grades?command=submission'.
 4103:         '&amp;symb='.$symb.
 4104:         '&amp;student='.$uname.
 4105:         '&amp;userdom='.$udom.'"'.
 4106:         $target.'>'.$text.'</a>';
 4107: }
 4108: ##############################################
 4109: 
 4110: =pod
 4111: 
 4112: =item * &pgrdlink()
 4113: 
 4114: Inputs: $text $uname $udom $symb $target
 4115: 
 4116: Returns: A link to grades.pm such as to see the PGRD view of a student
 4117: 
 4118: =cut
 4119: 
 4120: ###############################################
 4121: sub pgrdlink {
 4122:     my $link=&submlink(@_);
 4123:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4124:     return $link;
 4125: }
 4126: ##############################################
 4127: 
 4128: =pod
 4129: 
 4130: =item * &pprmlink()
 4131: 
 4132: Inputs: $text $uname $udom $symb $target
 4133: 
 4134: Returns: A link to parmset.pm such as to see the PPRM view of a
 4135: student and a specific resource
 4136: 
 4137: =cut
 4138: 
 4139: ###############################################
 4140: sub pprmlink {
 4141:     my ($text,$uname,$udom,$symb,$target)=@_;
 4142:     if (!($uname && $udom)) {
 4143: 	(my $cursymb, my $courseid,$udom,$uname)=
 4144: 	    &Apache::lonnet::whichuser($symb);
 4145: 	if (!$symb) { $symb=$cursymb; }
 4146:     }
 4147:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4148:     $symb=&escape($symb);
 4149:     if ($target) { $target="target=\"$target\""; }
 4150:     return '<a href="/adm/parmset?command=set&amp;'.
 4151: 	'symb='.$symb.'&amp;uname='.$uname.
 4152: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4153: }
 4154: ##############################################
 4155: 
 4156: =pod
 4157: 
 4158: =back
 4159: 
 4160: =cut
 4161: 
 4162: ###############################################
 4163: 
 4164: 
 4165: sub timehash {
 4166:     my ($thistime) = @_;
 4167:     my $timezone = &Apache::lonlocal::gettimezone();
 4168:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4169:                      ->set_time_zone($timezone);
 4170:     my $wday = $dt->day_of_week();
 4171:     if ($wday == 7) { $wday = 0; }
 4172:     return ( 'second' => $dt->second(),
 4173:              'minute' => $dt->minute(),
 4174:              'hour'   => $dt->hour(),
 4175:              'day'     => $dt->day_of_month(),
 4176:              'month'   => $dt->month(),
 4177:              'year'    => $dt->year(),
 4178:              'weekday' => $wday,
 4179:              'dayyear' => $dt->day_of_year(),
 4180:              'dlsav'   => $dt->is_dst() );
 4181: }
 4182: 
 4183: sub utc_string {
 4184:     my ($date)=@_;
 4185:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4186: }
 4187: 
 4188: sub maketime {
 4189:     my %th=@_;
 4190:     my ($epoch_time,$timezone,$dt);
 4191:     $timezone = &Apache::lonlocal::gettimezone();
 4192:     eval {
 4193:         $dt = DateTime->new( year   => $th{'year'},
 4194:                              month  => $th{'month'},
 4195:                              day    => $th{'day'},
 4196:                              hour   => $th{'hour'},
 4197:                              minute => $th{'minute'},
 4198:                              second => $th{'second'},
 4199:                              time_zone => $timezone,
 4200:                          );
 4201:     };
 4202:     if (!$@) {
 4203:         $epoch_time = $dt->epoch;
 4204:         if ($epoch_time) {
 4205:             return $epoch_time;
 4206:         }
 4207:     }
 4208:     return POSIX::mktime(
 4209:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4210:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4211: }
 4212: 
 4213: #########################################
 4214: 
 4215: sub findallcourses {
 4216:     my ($roles,$uname,$udom) = @_;
 4217:     my %roles;
 4218:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4219:     my %courses;
 4220:     my $now=time;
 4221:     if (!defined($uname)) {
 4222:         $uname = $env{'user.name'};
 4223:     }
 4224:     if (!defined($udom)) {
 4225:         $udom = $env{'user.domain'};
 4226:     }
 4227:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4228:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4229:         if (!%roles) {
 4230:             %roles = (
 4231:                        cc => 1,
 4232:                        co => 1,
 4233:                        in => 1,
 4234:                        ep => 1,
 4235:                        ta => 1,
 4236:                        cr => 1,
 4237:                        st => 1,
 4238:              );
 4239:         }
 4240:         foreach my $entry (keys(%roleshash)) {
 4241:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4242:             if ($trole =~ /^cr/) { 
 4243:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4244:             } else {
 4245:                 next if (!exists($roles{$trole}));
 4246:             }
 4247:             if ($tend) {
 4248:                 next if ($tend < $now);
 4249:             }
 4250:             if ($tstart) {
 4251:                 next if ($tstart > $now);
 4252:             }
 4253:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4254:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4255:             my $value = $trole.'/'.$cdom.'/';
 4256:             if ($secpart eq '') {
 4257:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4258:                 $sec = 'none';
 4259:                 $value .= $cnum.'/';
 4260:             } else {
 4261:                 $cnum = $cnumpart;
 4262:                 ($sec,$role) = split(/_/,$secpart);
 4263:                 $value .= $cnum.'/'.$sec;
 4264:             }
 4265:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4266:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4267:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4268:                 }
 4269:             } else {
 4270:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4271:             }
 4272:         }
 4273:     } else {
 4274:         foreach my $key (keys(%env)) {
 4275: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4276:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4277: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4278: 	        next if ($role eq 'ca' || $role eq 'aa');
 4279: 	        next if (%roles && !exists($roles{$role}));
 4280: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4281:                 my $active=1;
 4282:                 if ($starttime) {
 4283: 		    if ($now<$starttime) { $active=0; }
 4284:                 }
 4285:                 if ($endtime) {
 4286:                     if ($now>$endtime) { $active=0; }
 4287:                 }
 4288:                 if ($active) {
 4289:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4290:                     if ($sec eq '') {
 4291:                         $sec = 'none';
 4292:                     } else {
 4293:                         $value .= $sec;
 4294:                     }
 4295:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4296:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4297:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4298:                         }
 4299:                     } else {
 4300:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4301:                     }
 4302:                 }
 4303:             }
 4304:         }
 4305:     }
 4306:     return %courses;
 4307: }
 4308: 
 4309: ###############################################
 4310: 
 4311: sub blockcheck {
 4312:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4313: 
 4314:     if (!defined($udom)) {
 4315:         $udom = $env{'user.domain'};
 4316:     }
 4317:     if (!defined($uname)) {
 4318:         $uname = $env{'user.name'};
 4319:     }
 4320: 
 4321:     # If uname and udom are for a course, check for blocks in the course.
 4322: 
 4323:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4324:         my ($startblock,$endblock,$triggerblock) = 
 4325:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4326:         return ($startblock,$endblock,$triggerblock);
 4327:     }
 4328: 
 4329:     my $startblock = 0;
 4330:     my $endblock = 0;
 4331:     my $triggerblock = '';
 4332:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4333: 
 4334:     # If uname is for a user, and activity is course-specific, i.e.,
 4335:     # boards, chat or groups, check for blocking in current course only.
 4336: 
 4337:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4338:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4339:         foreach my $key (keys(%live_courses)) {
 4340:             if ($key ne $env{'request.course.id'}) {
 4341:                 delete($live_courses{$key});
 4342:             }
 4343:         }
 4344:     }
 4345: 
 4346:     my $otheruser = 0;
 4347:     my %own_courses;
 4348:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4349:         # Resource belongs to user other than current user.
 4350:         $otheruser = 1;
 4351:         # Gather courses for current user
 4352:         %own_courses = 
 4353:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4354:     }
 4355: 
 4356:     # Gather active course roles - course coordinator, instructor, 
 4357:     # exam proctor, ta, student, or custom role.
 4358: 
 4359:     foreach my $course (keys(%live_courses)) {
 4360:         my ($cdom,$cnum);
 4361:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4362:             $cdom = $env{'course.'.$course.'.domain'};
 4363:             $cnum = $env{'course.'.$course.'.num'};
 4364:         } else {
 4365:             ($cdom,$cnum) = split(/_/,$course); 
 4366:         }
 4367:         my $no_ownblock = 0;
 4368:         my $no_userblock = 0;
 4369:         if ($otheruser && $activity ne 'com') {
 4370:             # Check if current user has 'evb' priv for this
 4371:             if (defined($own_courses{$course})) {
 4372:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4373:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4374:                     if ($sec ne 'none') {
 4375:                         $checkrole .= '/'.$sec;
 4376:                     }
 4377:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4378:                         $no_ownblock = 1;
 4379:                         last;
 4380:                     }
 4381:                 }
 4382:             }
 4383:             # if they have 'evb' priv and are currently not playing student
 4384:             next if (($no_ownblock) &&
 4385:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4386:         }
 4387:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4388:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4389:             if ($sec ne 'none') {
 4390:                 $checkrole .= '/'.$sec;
 4391:             }
 4392:             if ($otheruser) {
 4393:                 # Resource belongs to user other than current user.
 4394:                 # Assemble privs for that user, and check for 'evb' priv.
 4395:                 my (%allroles,%userroles);
 4396:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4397:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4398:                         my ($trole,$tdom,$tnum,$tsec);
 4399:                         if ($entry =~ /^cr/) {
 4400:                             ($trole,$tdom,$tnum,$tsec) = 
 4401:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4402:                         } else {
 4403:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4404:                         }
 4405:                         my ($spec,$area,$trest);
 4406:                         $area = '/'.$tdom.'/'.$tnum;
 4407:                         $trest = $tnum;
 4408:                         if ($tsec ne '') {
 4409:                             $area .= '/'.$tsec;
 4410:                             $trest .= '/'.$tsec;
 4411:                         }
 4412:                         $spec = $trole.'.'.$area;
 4413:                         if ($trole =~ /^cr/) {
 4414:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4415:                                                               $tdom,$spec,$trest,$area);
 4416:                         } else {
 4417:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4418:                                                                 $tdom,$spec,$trest,$area);
 4419:                         }
 4420:                     }
 4421:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4422:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4423:                         if ($1) {
 4424:                             $no_userblock = 1;
 4425:                             last;
 4426:                         }
 4427:                     }
 4428:                 }
 4429:             } else {
 4430:                 # Resource belongs to current user
 4431:                 # Check for 'evb' priv via lonnet::allowed().
 4432:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4433:                     $no_ownblock = 1;
 4434:                     last;
 4435:                 }
 4436:             }
 4437:         }
 4438:         # if they have the evb priv and are currently not playing student
 4439:         next if (($no_ownblock) &&
 4440:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4441:         next if ($no_userblock);
 4442: 
 4443:         # Retrieve blocking times and identity of locker for course
 4444:         # of specified user, unless user has 'evb' privilege.
 4445:         
 4446:         my ($start,$end,$trigger) = 
 4447:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4448:         if (($start != 0) && 
 4449:             (($startblock == 0) || ($startblock > $start))) {
 4450:             $startblock = $start;
 4451:             if ($trigger ne '') {
 4452:                 $triggerblock = $trigger;
 4453:             }
 4454:         }
 4455:         if (($end != 0)  &&
 4456:             (($endblock == 0) || ($endblock < $end))) {
 4457:             $endblock = $end;
 4458:             if ($trigger ne '') {
 4459:                 $triggerblock = $trigger;
 4460:             }
 4461:         }
 4462:     }
 4463:     return ($startblock,$endblock,$triggerblock);
 4464: }
 4465: 
 4466: sub get_blocks {
 4467:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4468:     my $startblock = 0;
 4469:     my $endblock = 0;
 4470:     my $triggerblock = '';
 4471:     my $course = $cdom.'_'.$cnum;
 4472:     $setters->{$course} = {};
 4473:     $setters->{$course}{'staff'} = [];
 4474:     $setters->{$course}{'times'} = [];
 4475:     $setters->{$course}{'triggers'} = [];
 4476:     my (@blockers,%triggered);
 4477:     my $now = time;
 4478:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4479:     if ($activity eq 'docs') {
 4480:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4481:         foreach my $block (@blockers) {
 4482:             if ($block =~ /^firstaccess____(.+)$/) {
 4483:                 my $item = $1;
 4484:                 my $type = 'map';
 4485:                 my $timersymb = $item;
 4486:                 if ($item eq 'course') {
 4487:                     $type = 'course';
 4488:                 } elsif ($item =~ /___\d+___/) {
 4489:                     $type = 'resource';
 4490:                 } else {
 4491:                     $timersymb = &Apache::lonnet::symbread($item);
 4492:                 }
 4493:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4494:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4495:                 $triggered{$block} = {
 4496:                                        start => $start,
 4497:                                        end   => $end,
 4498:                                        type  => $type,
 4499:                                      };
 4500:             }
 4501:         }
 4502:     } else {
 4503:         foreach my $block (keys(%commblocks)) {
 4504:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4505:                 my ($start,$end) = ($1,$2);
 4506:                 if ($start <= time && $end >= time) {
 4507:                     if (ref($commblocks{$block}) eq 'HASH') {
 4508:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4509:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4510:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4511:                                     push(@blockers,$block);
 4512:                                 }
 4513:                             }
 4514:                         }
 4515:                     }
 4516:                 }
 4517:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4518:                 my $item = $1;
 4519:                 my $timersymb = $item; 
 4520:                 my $type = 'map';
 4521:                 if ($item eq 'course') {
 4522:                     $type = 'course';
 4523:                 } elsif ($item =~ /___\d+___/) {
 4524:                     $type = 'resource';
 4525:                 } else {
 4526:                     $timersymb = &Apache::lonnet::symbread($item);
 4527:                 }
 4528:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4529:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4530:                 if ($start && $end) {
 4531:                     if (($start <= time) && ($end >= time)) {
 4532:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4533:                             push(@blockers,$block);
 4534:                             $triggered{$block} = {
 4535:                                                    start => $start,
 4536:                                                    end   => $end,
 4537:                                                    type  => $type,
 4538:                                                  };
 4539:                         }
 4540:                     }
 4541:                 }
 4542:             }
 4543:         }
 4544:     }
 4545:     foreach my $blocker (@blockers) {
 4546:         my ($staff_name,$staff_dom,$title,$blocks) =
 4547:             &parse_block_record($commblocks{$blocker});
 4548:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4549:         my ($start,$end,$triggertype);
 4550:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4551:             ($start,$end) = ($1,$2);
 4552:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4553:             $start = $triggered{$blocker}{'start'};
 4554:             $end = $triggered{$blocker}{'end'};
 4555:             $triggertype = $triggered{$blocker}{'type'};
 4556:         }
 4557:         if ($start) {
 4558:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4559:             if ($triggertype) {
 4560:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4561:             } else {
 4562:                 push(@{$$setters{$course}{'triggers'}},0);
 4563:             }
 4564:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4565:                 $startblock = $start;
 4566:                 if ($triggertype) {
 4567:                     $triggerblock = $blocker;
 4568:                 }
 4569:             }
 4570:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4571:                $endblock = $end;
 4572:                if ($triggertype) {
 4573:                    $triggerblock = $blocker;
 4574:                }
 4575:             }
 4576:         }
 4577:     }
 4578:     return ($startblock,$endblock,$triggerblock);
 4579: }
 4580: 
 4581: sub parse_block_record {
 4582:     my ($record) = @_;
 4583:     my ($setuname,$setudom,$title,$blocks);
 4584:     if (ref($record) eq 'HASH') {
 4585:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4586:         $title = &unescape($record->{'event'});
 4587:         $blocks = $record->{'blocks'};
 4588:     } else {
 4589:         my @data = split(/:/,$record,3);
 4590:         if (scalar(@data) eq 2) {
 4591:             $title = $data[1];
 4592:             ($setuname,$setudom) = split(/@/,$data[0]);
 4593:         } else {
 4594:             ($setuname,$setudom,$title) = @data;
 4595:         }
 4596:         $blocks = { 'com' => 'on' };
 4597:     }
 4598:     return ($setuname,$setudom,$title,$blocks);
 4599: }
 4600: 
 4601: sub blocking_status {
 4602:     my ($activity,$uname,$udom,$url) = @_;
 4603:     my %setters;
 4604: 
 4605: # check for active blocking
 4606:     my ($startblock,$endblock,$triggerblock) = 
 4607:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4608:     my $blocked = 0;
 4609:     if ($startblock && $endblock) {
 4610:         $blocked = 1;
 4611:     }
 4612: 
 4613: # caller just wants to know whether a block is active
 4614:     if (!wantarray) { return $blocked; }
 4615: 
 4616: # build a link to a popup window containing the details
 4617:     my $querystring  = "?activity=$activity";
 4618: # $uname and $udom decide whose portfolio the user is trying to look at
 4619:     if ($activity eq 'port') {
 4620:         $querystring .= "&amp;udom=$udom"      if $udom;
 4621:         $querystring .= "&amp;uname=$uname"    if $uname;
 4622:     } elsif ($activity eq 'docs') {
 4623:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4624:     }
 4625: 
 4626:     my $output .= <<'END_MYBLOCK';
 4627: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4628:     var options = "width=" + w + ",height=" + h + ",";
 4629:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4630:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4631:     var newWin = window.open(url, wdwName, options);
 4632:     newWin.focus();
 4633: }
 4634: END_MYBLOCK
 4635: 
 4636:     $output = Apache::lonhtmlcommon::scripttag($output);
 4637:   
 4638:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4639:     my $text = &mt('Communication Blocked');
 4640:     if ($activity eq 'docs') {
 4641:         $text = &mt('Content Access Blocked');
 4642:     } elsif ($activity eq 'printout') {
 4643:         $text = &mt('Printing Blocked');
 4644:     }
 4645:     $output .= <<"END_BLOCK";
 4646: <div class='LC_comblock'>
 4647:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4648:   title='$text'>
 4649:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4650:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4651:   title='$text'>$text</a>
 4652: </div>
 4653: 
 4654: END_BLOCK
 4655: 
 4656:     return ($blocked, $output);
 4657: }
 4658: 
 4659: ###############################################
 4660: 
 4661: sub check_ip_acc {
 4662:     my ($acc)=@_;
 4663:     &Apache::lonxml::debug("acc is $acc");
 4664:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4665:         return 1;
 4666:     }
 4667:     my $allowed=0;
 4668:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4669: 
 4670:     my $name;
 4671:     foreach my $pattern (split(',',$acc)) {
 4672:         $pattern =~ s/^\s*//;
 4673:         $pattern =~ s/\s*$//;
 4674:         if ($pattern =~ /\*$/) {
 4675:             #35.8.*
 4676:             $pattern=~s/\*//;
 4677:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4678:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4679:             #35.8.3.[34-56]
 4680:             my $low=$2;
 4681:             my $high=$3;
 4682:             $pattern=$1;
 4683:             if ($ip =~ /^\Q$pattern\E/) {
 4684:                 my $last=(split(/\./,$ip))[3];
 4685:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4686:             }
 4687:         } elsif ($pattern =~ /^\*/) {
 4688:             #*.msu.edu
 4689:             $pattern=~s/\*//;
 4690:             if (!defined($name)) {
 4691:                 use Socket;
 4692:                 my $netaddr=inet_aton($ip);
 4693:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4694:             }
 4695:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4696:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4697:             #127.0.0.1
 4698:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4699:         } else {
 4700:             #some.name.com
 4701:             if (!defined($name)) {
 4702:                 use Socket;
 4703:                 my $netaddr=inet_aton($ip);
 4704:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4705:             }
 4706:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4707:         }
 4708:         if ($allowed) { last; }
 4709:     }
 4710:     return $allowed;
 4711: }
 4712: 
 4713: ###############################################
 4714: 
 4715: =pod
 4716: 
 4717: =head1 Domain Template Functions
 4718: 
 4719: =over 4
 4720: 
 4721: =item * &determinedomain()
 4722: 
 4723: Inputs: $domain (usually will be undef)
 4724: 
 4725: Returns: Determines which domain should be used for designs
 4726: 
 4727: =cut
 4728: 
 4729: ###############################################
 4730: sub determinedomain {
 4731:     my $domain=shift;
 4732:     if (! $domain) {
 4733:         # Determine domain if we have not been given one
 4734:         $domain = &Apache::lonnet::default_login_domain();
 4735:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4736:         if ($env{'request.role.domain'}) { 
 4737:             $domain=$env{'request.role.domain'}; 
 4738:         }
 4739:     }
 4740:     return $domain;
 4741: }
 4742: ###############################################
 4743: 
 4744: sub devalidate_domconfig_cache {
 4745:     my ($udom)=@_;
 4746:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4747: }
 4748: 
 4749: # ---------------------- Get domain configuration for a domain
 4750: sub get_domainconf {
 4751:     my ($udom) = @_;
 4752:     my $cachetime=1800;
 4753:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4754:     if (defined($cached)) { return %{$result}; }
 4755: 
 4756:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4757: 					     ['login','rolecolors','autoenroll'],$udom);
 4758:     my (%designhash,%legacy);
 4759:     if (keys(%domconfig) > 0) {
 4760:         if (ref($domconfig{'login'}) eq 'HASH') {
 4761:             if (keys(%{$domconfig{'login'}})) {
 4762:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4763:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4764:                         if ($key eq 'loginvia') {
 4765:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4766:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4767:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4768:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4769:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4770:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4771:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4772: 
 4773:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4774:                                             } else {
 4775:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4776:                                             }
 4777:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4778:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4779:                                             }
 4780:                                         }
 4781:                                     }
 4782:                                 }
 4783:                             }
 4784:                         } else {
 4785:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4786:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4787:                                     $domconfig{'login'}{$key}{$img};
 4788:                             }
 4789:                         }
 4790:                     } else {
 4791:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4792:                     }
 4793:                 }
 4794:             } else {
 4795:                 $legacy{'login'} = 1;
 4796:             }
 4797:         } else {
 4798:             $legacy{'login'} = 1;
 4799:         }
 4800:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4801:             if (keys(%{$domconfig{'rolecolors'}})) {
 4802:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4803:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4804:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4805:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4806:                         }
 4807:                     }
 4808:                 }
 4809:             } else {
 4810:                 $legacy{'rolecolors'} = 1;
 4811:             }
 4812:         } else {
 4813:             $legacy{'rolecolors'} = 1;
 4814:         }
 4815:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4816:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4817:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4818:             }
 4819:         }
 4820:         if (keys(%legacy) > 0) {
 4821:             my %legacyhash = &get_legacy_domconf($udom);
 4822:             foreach my $item (keys(%legacyhash)) {
 4823:                 if ($item =~ /^\Q$udom\E\.login/) {
 4824:                     if ($legacy{'login'}) { 
 4825:                         $designhash{$item} = $legacyhash{$item};
 4826:                     }
 4827:                 } else {
 4828:                     if ($legacy{'rolecolors'}) {
 4829:                         $designhash{$item} = $legacyhash{$item};
 4830:                     }
 4831:                 }
 4832:             }
 4833:         }
 4834:     } else {
 4835:         %designhash = &get_legacy_domconf($udom); 
 4836:     }
 4837:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4838: 				  $cachetime);
 4839:     return %designhash;
 4840: }
 4841: 
 4842: sub get_legacy_domconf {
 4843:     my ($udom) = @_;
 4844:     my %legacyhash;
 4845:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4846:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4847:     if (-e $designfile) {
 4848:         if ( open (my $fh,"<$designfile") ) {
 4849:             while (my $line = <$fh>) {
 4850:                 next if ($line =~ /^\#/);
 4851:                 chomp($line);
 4852:                 my ($key,$val)=(split(/\=/,$line));
 4853:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4854:             }
 4855:             close($fh);
 4856:         }
 4857:     }
 4858:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4859:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4860:     }
 4861:     return %legacyhash;
 4862: }
 4863: 
 4864: =pod
 4865: 
 4866: =item * &domainlogo()
 4867: 
 4868: Inputs: $domain (usually will be undef)
 4869: 
 4870: Returns: A link to a domain logo, if the domain logo exists.
 4871: If the domain logo does not exist, a description of the domain.
 4872: 
 4873: =cut
 4874: 
 4875: ###############################################
 4876: sub domainlogo {
 4877:     my $domain = &determinedomain(shift);
 4878:     my %designhash = &get_domainconf($domain);    
 4879:     # See if there is a logo
 4880:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4881:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4882:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4883: 	    if ($imgsrc =~ m{^/res/}) {
 4884: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4885: 		&Apache::lonnet::repcopy($local_name);
 4886: 	    }
 4887: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4888:         } 
 4889:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4890:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4891:         return &Apache::lonnet::domain($domain,'description');
 4892:     } else {
 4893:         return '';
 4894:     }
 4895: }
 4896: ##############################################
 4897: 
 4898: =pod
 4899: 
 4900: =item * &designparm()
 4901: 
 4902: Inputs: $which parameter; $domain (usually will be undef)
 4903: 
 4904: Returns: value of designparamter $which
 4905: 
 4906: =cut
 4907: 
 4908: 
 4909: ##############################################
 4910: sub designparm {
 4911:     my ($which,$domain)=@_;
 4912:     if (exists($env{'environment.color.'.$which})) {
 4913:         return $env{'environment.color.'.$which};
 4914:     }
 4915:     $domain=&determinedomain($domain);
 4916:     my %domdesign;
 4917:     unless ($domain eq 'public') {
 4918:         %domdesign = &get_domainconf($domain);
 4919:     }
 4920:     my $output;
 4921:     if ($domdesign{$domain.'.'.$which} ne '') {
 4922:         $output = $domdesign{$domain.'.'.$which};
 4923:     } else {
 4924:         $output = $defaultdesign{$which};
 4925:     }
 4926:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4927:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4928:         if ($output =~ m{^/(adm|res)/}) {
 4929:             if ($output =~ m{^/res/}) {
 4930:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4931:                 &Apache::lonnet::repcopy($local_name);
 4932:             }
 4933:             $output = &lonhttpdurl($output);
 4934:         }
 4935:     }
 4936:     return $output;
 4937: }
 4938: 
 4939: ##############################################
 4940: =pod
 4941: 
 4942: =item * &authorspace()
 4943: 
 4944: Inputs: $url (usually will be undef).
 4945: 
 4946: Returns: Path to Authoring Space containing the resource or 
 4947:          directory being viewed (or for which action is being taken). 
 4948:          If $url is provided, and begins /priv/<domain>/<uname>
 4949:          the path will be that portion of the $context argument.
 4950:          Otherwise the path will be for the author space of the current
 4951:          user when the current role is author, or for that of the 
 4952:          co-author/assistant co-author space when the current role 
 4953:          is co-author or assistant co-author.
 4954: 
 4955: =cut
 4956: 
 4957: sub authorspace {
 4958:     my ($url) = @_;
 4959:     if ($url ne '') {
 4960:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4961:            return $1;
 4962:         }
 4963:     }
 4964:     my $caname = '';
 4965:     my $cadom = '';
 4966:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4967:         ($cadom,$caname) =
 4968:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4969:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4970:         $caname = $env{'user.name'};
 4971:         $cadom = $env{'user.domain'};
 4972:     }
 4973:     if (($caname ne '') && ($cadom ne '')) {
 4974:         return "/priv/$cadom/$caname/";
 4975:     }
 4976:     return;
 4977: }
 4978: 
 4979: ##############################################
 4980: =pod
 4981: 
 4982: =item * &head_subbox()
 4983: 
 4984: Inputs: $content (contains HTML code with page functions, etc.)
 4985: 
 4986: Returns: HTML div with $content
 4987:          To be included in page header
 4988: 
 4989: =cut
 4990: 
 4991: sub head_subbox {
 4992:     my ($content)=@_;
 4993:     my $output =
 4994:         '<div class="LC_head_subbox">'
 4995:        .$content
 4996:        .'</div>'
 4997: }
 4998: 
 4999: ##############################################
 5000: =pod
 5001: 
 5002: =item * &CSTR_pageheader()
 5003: 
 5004: Input: (optional) filename from which breadcrumb trail is built.
 5005:        In most cases no input as needed, as $env{'request.filename'}
 5006:        is appropriate for use in building the breadcrumb trail.
 5007: 
 5008: Returns: HTML div with CSTR path and recent box
 5009:          To be included on Authoring Space pages
 5010: 
 5011: =cut
 5012: 
 5013: sub CSTR_pageheader {
 5014:     my ($trailfile) = @_;
 5015:     if ($trailfile eq '') {
 5016:         $trailfile = $env{'request.filename'};
 5017:     }
 5018: 
 5019: # this is for resources; directories have customtitle, and crumbs
 5020: # and select recent are created in lonpubdir.pm
 5021: 
 5022:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5023:     my ($udom,$uname,$thisdisfn)=
 5024:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5025:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5026:     $formaction =~ s{/+}{/}g;
 5027: 
 5028:     my $parentpath = '';
 5029:     my $lastitem = '';
 5030:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5031:         $parentpath = $1;
 5032:         $lastitem = $2;
 5033:     } else {
 5034:         $lastitem = $thisdisfn;
 5035:     }
 5036: 
 5037:     my $output =
 5038:          '<div>'
 5039:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5040:         .'<b>'.&mt('Authoring Space:').'</b> '
 5041:         .'<form name="dirs" method="post" action="'.$formaction
 5042:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5043:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5044: 
 5045:     if ($lastitem) {
 5046:         $output .=
 5047:              '<span class="LC_filename">'
 5048:             .$lastitem
 5049:             .'</span>';
 5050:     }
 5051:     $output .=
 5052:          '<br />'
 5053:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5054:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5055:         .'</form>'
 5056:         .&Apache::lonmenu::constspaceform()
 5057:         .'</div>';
 5058: 
 5059:     return $output;
 5060: }
 5061: 
 5062: ###############################################
 5063: ###############################################
 5064: 
 5065: =pod
 5066: 
 5067: =back
 5068: 
 5069: =head1 HTML Helpers
 5070: 
 5071: =over 4
 5072: 
 5073: =item * &bodytag()
 5074: 
 5075: Returns a uniform header for LON-CAPA web pages.
 5076: 
 5077: Inputs: 
 5078: 
 5079: =over 4
 5080: 
 5081: =item * $title, A title to be displayed on the page.
 5082: 
 5083: =item * $function, the current role (can be undef).
 5084: 
 5085: =item * $addentries, extra parameters for the <body> tag.
 5086: 
 5087: =item * $bodyonly, if defined, only return the <body> tag.
 5088: 
 5089: =item * $domain, if defined, force a given domain.
 5090: 
 5091: =item * $forcereg, if page should register as content page (relevant for 
 5092:             text interface only)
 5093: 
 5094: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5095:                      navigational links
 5096: 
 5097: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5098: 
 5099: =item * $args, optional argument valid values are
 5100:             no_auto_mt_title -> prevents &mt()ing the title arg
 5101:             inherit_jsmath -> when creating popup window in a page,
 5102:                               should it have jsmath forced on by the
 5103:                               current page
 5104: 
 5105: =item * $advtoolsref, optional argument, ref to an array containing
 5106:             inlineremote items to be added in "Functions" menu below
 5107:             breadcrumbs.
 5108: 
 5109: =back
 5110: 
 5111: Returns: A uniform header for LON-CAPA web pages.  
 5112: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5113: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5114: other decorations will be returned.
 5115: 
 5116: =cut
 5117: 
 5118: sub bodytag {
 5119:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5120:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5121: 
 5122:     my $public;
 5123:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5124:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5125:         $public = 1;
 5126:     }
 5127:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5128:     my $httphost = $args->{'use_absolute'};
 5129: 
 5130:     $function = &get_users_function() if (!$function);
 5131:     my $img =    &designparm($function.'.img',$domain);
 5132:     my $font =   &designparm($function.'.font',$domain);
 5133:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5134: 
 5135:     my %design = ( 'style'   => 'margin-top: 0',
 5136: 		   'bgcolor' => $pgbg,
 5137: 		   'text'    => $font,
 5138:                    'alink'   => &designparm($function.'.alink',$domain),
 5139: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5140: 		   'link'    => &designparm($function.'.link',$domain),);
 5141:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5142: 
 5143:  # role and realm
 5144:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5145:     if ($role  eq 'ca') {
 5146:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5147:         $realm = &plainname($rname,$rdom);
 5148:     } 
 5149: # realm
 5150:     if ($env{'request.course.id'}) {
 5151:         if ($env{'request.role'} !~ /^cr/) {
 5152:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5153:         }
 5154:         if ($env{'request.course.sec'}) {
 5155:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5156:         }   
 5157: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5158:     } else {
 5159:         $role = &Apache::lonnet::plaintext($role);
 5160:     }
 5161: 
 5162:     if (!$realm) { $realm='&nbsp;'; }
 5163: 
 5164:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5165: 
 5166: # construct main body tag
 5167:     my $bodytag = "<body $extra_body_attr>".
 5168: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5169: 
 5170:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5171: 
 5172:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5173:         return $bodytag;
 5174:     }
 5175: 
 5176:     if ($public) {
 5177: 	undef($role);
 5178:     }
 5179:     
 5180:     my $titleinfo = '<h1>'.$title.'</h1>';
 5181:     #
 5182:     # Extra info if you are the DC
 5183:     my $dc_info = '';
 5184:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5185:                         $env{'course.'.$env{'request.course.id'}.
 5186:                                  '.domain'}.'/'})) {
 5187:         my $cid = $env{'request.course.id'};
 5188:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5189:         $dc_info =~ s/\s+$//;
 5190:     }
 5191: 
 5192:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5193: 
 5194:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5195: 
 5196:         #    if ($env{'request.state'} eq 'construct') {
 5197:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5198:         #    }
 5199: 
 5200:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5201:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5202: 
 5203:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5204: 
 5205:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5206:              if ($dc_info) {
 5207:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5208:              }
 5209:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5210:                 <em>$realm</em> $dc_info</div>|;
 5211:             return $bodytag;
 5212:         }
 5213: 
 5214:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5215:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5216:         }
 5217: 
 5218:         $bodytag .= $right;
 5219: 
 5220:         if ($dc_info) {
 5221:             $dc_info = &dc_courseid_toggle($dc_info);
 5222:         }
 5223:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5224: 
 5225:         #don't show menus for public users
 5226:         if (!$public){
 5227:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5228:             $bodytag .= Apache::lonmenu::serverform();
 5229:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5230:             if ($env{'request.state'} eq 'construct') {
 5231:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5232:                                 $args->{'bread_crumbs'});
 5233:             } elsif ($forcereg) {
 5234:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5235:                                                             $args->{'group'});
 5236:             } else {
 5237:                 $bodytag .= 
 5238:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5239:                                                         $forcereg,$args->{'group'},
 5240:                                                         $args->{'bread_crumbs'},
 5241:                                                         $advtoolsref);
 5242:             }
 5243:         }else{
 5244:             # this is to seperate menu from content when there's no secondary
 5245:             # menu. Especially needed for public accessible ressources.
 5246:             $bodytag .= '<hr style="clear:both" />';
 5247:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5248:         }
 5249: 
 5250:         return $bodytag;
 5251: }
 5252: 
 5253: sub dc_courseid_toggle {
 5254:     my ($dc_info) = @_;
 5255:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5256:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5257:            &mt('(More ...)').'</a></span>'.
 5258:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5259: }
 5260: 
 5261: sub make_attr_string {
 5262:     my ($register,$attr_ref) = @_;
 5263: 
 5264:     if ($attr_ref && !ref($attr_ref)) {
 5265: 	die("addentries Must be a hash ref ".
 5266: 	    join(':',caller(1))." ".
 5267: 	    join(':',caller(0))." ");
 5268:     }
 5269: 
 5270:     if ($register) {
 5271: 	my ($on_load,$on_unload);
 5272: 	foreach my $key (keys(%{$attr_ref})) {
 5273: 	    if      (lc($key) eq 'onload') {
 5274: 		$on_load.=$attr_ref->{$key}.';';
 5275: 		delete($attr_ref->{$key});
 5276: 
 5277: 	    } elsif (lc($key) eq 'onunload') {
 5278: 		$on_unload.=$attr_ref->{$key}.';';
 5279: 		delete($attr_ref->{$key});
 5280: 	    }
 5281: 	}
 5282: 	$attr_ref->{'onload'}  = $on_load;
 5283: 	$attr_ref->{'onunload'}= $on_unload;
 5284:     }
 5285: 
 5286:     my $attr_string;
 5287:     foreach my $attr (sort(keys(%$attr_ref))) {
 5288: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5289:     }
 5290:     return $attr_string;
 5291: }
 5292: 
 5293: 
 5294: ###############################################
 5295: ###############################################
 5296: 
 5297: =pod
 5298: 
 5299: =item * &endbodytag()
 5300: 
 5301: Returns a uniform footer for LON-CAPA web pages.
 5302: 
 5303: Inputs: 1 - optional reference to an args hash
 5304: If in the hash, key for noredirectlink has a value which evaluates to true,
 5305: a 'Continue' link is not displayed if the page contains an
 5306: internal redirect in the <head></head> section,
 5307: i.e., $env{'internal.head.redirect'} exists   
 5308: 
 5309: =cut
 5310: 
 5311: sub endbodytag {
 5312:     my ($args) = @_;
 5313:     my $endbodytag;
 5314:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5315:         $endbodytag='</body>';
 5316:     }
 5317:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5318:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5319:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5320: 	    $endbodytag=
 5321: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5322: 	        &mt('Continue').'</a>'.
 5323: 	        $endbodytag;
 5324:         }
 5325:     }
 5326:     return $endbodytag;
 5327: }
 5328: 
 5329: =pod
 5330: 
 5331: =item * &standard_css()
 5332: 
 5333: Returns a style sheet
 5334: 
 5335: Inputs: (all optional)
 5336:             domain         -> force to color decorate a page for a specific
 5337:                                domain
 5338:             function       -> force usage of a specific rolish color scheme
 5339:             bgcolor        -> override the default page bgcolor
 5340: 
 5341: =cut
 5342: 
 5343: sub standard_css {
 5344:     my ($function,$domain,$bgcolor) = @_;
 5345:     $function  = &get_users_function() if (!$function);
 5346:     my $img    = &designparm($function.'.img',   $domain);
 5347:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5348:     my $font   = &designparm($function.'.font',  $domain);
 5349:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5350: #second colour for later usage
 5351:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5352:     my $pgbg_or_bgcolor =
 5353: 	         $bgcolor ||
 5354: 	         &designparm($function.'.pgbg',  $domain);
 5355:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5356:     my $alink  = &designparm($function.'.alink', $domain);
 5357:     my $vlink  = &designparm($function.'.vlink', $domain);
 5358:     my $link   = &designparm($function.'.link',  $domain);
 5359: 
 5360:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5361:     my $mono                 = 'monospace';
 5362:     my $data_table_head      = $sidebg;
 5363:     my $data_table_light     = '#FAFAFA';
 5364:     my $data_table_dark      = '#E0E0E0';
 5365:     my $data_table_darker    = '#CCCCCC';
 5366:     my $data_table_highlight = '#FFFF00';
 5367:     my $mail_new             = '#FFBB77';
 5368:     my $mail_new_hover       = '#DD9955';
 5369:     my $mail_read            = '#BBBB77';
 5370:     my $mail_read_hover      = '#999944';
 5371:     my $mail_replied         = '#AAAA88';
 5372:     my $mail_replied_hover   = '#888855';
 5373:     my $mail_other           = '#99BBBB';
 5374:     my $mail_other_hover     = '#669999';
 5375:     my $table_header         = '#DDDDDD';
 5376:     my $feedback_link_bg     = '#BBBBBB';
 5377:     my $lg_border_color      = '#C8C8C8';
 5378:     my $button_hover         = '#BF2317';
 5379: 
 5380:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5381:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5382:                                              : '0 3px 0 4px';
 5383: 
 5384: 
 5385:     return <<END;
 5386: 
 5387: /* needed for iframe to allow 100% height in FF */
 5388: body, html { 
 5389:     margin: 0;
 5390:     padding: 0 0.5%;
 5391:     height: 99%; /* to avoid scrollbars */
 5392: }
 5393: 
 5394: body {
 5395:   font-family: $sans;
 5396:   line-height:130%;
 5397:   font-size:0.83em;
 5398:   color:$font;
 5399: }
 5400: 
 5401: a:focus,
 5402: a:focus img {
 5403:   color: red;
 5404: }
 5405: 
 5406: form, .inline {
 5407:   display: inline;
 5408: }
 5409: 
 5410: .LC_right {
 5411:   text-align:right;
 5412: }
 5413: 
 5414: .LC_middle {
 5415:   vertical-align:middle;
 5416: }
 5417: 
 5418: .LC_floatleft {
 5419:   float: left;
 5420: }
 5421: 
 5422: .LC_floatright {
 5423:   float: right;
 5424: }
 5425: 
 5426: .LC_400Box {
 5427:   width:400px;
 5428: }
 5429: 
 5430: .LC_iframecontainer {
 5431:     width: 98%;
 5432:     margin: 0;
 5433:     position: fixed;
 5434:     top: 8.5em;
 5435:     bottom: 0;
 5436: }
 5437: 
 5438: .LC_iframecontainer iframe{
 5439:     border: none;
 5440:     width: 100%;
 5441:     height: 100%;
 5442: }
 5443: 
 5444: .LC_filename {
 5445:   font-family: $mono;
 5446:   white-space:pre;
 5447:   font-size: 120%;
 5448: }
 5449: 
 5450: .LC_fileicon {
 5451:   border: none;
 5452:   height: 1.3em;
 5453:   vertical-align: text-bottom;
 5454:   margin-right: 0.3em;
 5455:   text-decoration:none;
 5456: }
 5457: 
 5458: .LC_setting {
 5459:   text-decoration:underline;
 5460: }
 5461: 
 5462: .LC_error {
 5463:   color: red;
 5464: }
 5465: 
 5466: .LC_warning {
 5467:   color: darkorange;
 5468: }
 5469: 
 5470: .LC_diff_removed {
 5471:   color: red;
 5472: }
 5473: 
 5474: .LC_info,
 5475: .LC_success,
 5476: .LC_diff_added {
 5477:   color: green;
 5478: }
 5479: 
 5480: div.LC_confirm_box {
 5481:   background-color: #FAFAFA;
 5482:   border: 1px solid $lg_border_color;
 5483:   margin-right: 0;
 5484:   padding: 5px;
 5485: }
 5486: 
 5487: div.LC_confirm_box .LC_error img,
 5488: div.LC_confirm_box .LC_success img {
 5489:   vertical-align: middle;
 5490: }
 5491: 
 5492: .LC_icon {
 5493:   border: none;
 5494:   vertical-align: middle;
 5495: }
 5496: 
 5497: .LC_docs_spacer {
 5498:   width: 25px;
 5499:   height: 1px;
 5500:   border: none;
 5501: }
 5502: 
 5503: .LC_internal_info {
 5504:   color: #999999;
 5505: }
 5506: 
 5507: .LC_discussion {
 5508:   background: $data_table_dark;
 5509:   border: 1px solid black;
 5510:   margin: 2px;
 5511: }
 5512: 
 5513: .LC_disc_action_left {
 5514:   background: $sidebg;
 5515:   text-align: left;
 5516:   padding: 4px;
 5517:   margin: 2px;
 5518: }
 5519: 
 5520: .LC_disc_action_right {
 5521:   background: $sidebg;
 5522:   text-align: right;
 5523:   padding: 4px;
 5524:   margin: 2px;
 5525: }
 5526: 
 5527: .LC_disc_new_item {
 5528:   background: white;
 5529:   border: 2px solid red;
 5530:   margin: 4px;
 5531:   padding: 4px;
 5532: }
 5533: 
 5534: .LC_disc_old_item {
 5535:   background: white;
 5536:   margin: 4px;
 5537:   padding: 4px;
 5538: }
 5539: 
 5540: table.LC_pastsubmission {
 5541:   border: 1px solid black;
 5542:   margin: 2px;
 5543: }
 5544: 
 5545: table#LC_menubuttons {
 5546:   width: 100%;
 5547:   background: $pgbg;
 5548:   border: 2px;
 5549:   border-collapse: separate;
 5550:   padding: 0;
 5551: }
 5552: 
 5553: table#LC_title_bar a {
 5554:   color: $fontmenu;
 5555: }
 5556: 
 5557: table#LC_title_bar {
 5558:   clear: both;
 5559:   display: none;
 5560: }
 5561: 
 5562: table#LC_title_bar,
 5563: table.LC_breadcrumbs, /* obsolete? */
 5564: table#LC_title_bar.LC_with_remote {
 5565:   width: 100%;
 5566:   border-color: $pgbg;
 5567:   border-style: solid;
 5568:   border-width: $border;
 5569:   background: $pgbg;
 5570:   color: $fontmenu;
 5571:   border-collapse: collapse;
 5572:   padding: 0;
 5573:   margin: 0;
 5574: }
 5575: 
 5576: ul.LC_breadcrumb_tools_outerlist {
 5577:     margin: 0;
 5578:     padding: 0;
 5579:     position: relative;
 5580:     list-style: none;
 5581: }
 5582: ul.LC_breadcrumb_tools_outerlist li {
 5583:     display: inline;
 5584: }
 5585: 
 5586: .LC_breadcrumb_tools_navigation {
 5587:     padding: 0;
 5588:     margin: 0;
 5589:     float: left;
 5590: }
 5591: .LC_breadcrumb_tools_tools {
 5592:     padding: 0;
 5593:     margin: 0;
 5594:     float: right;
 5595: }
 5596: 
 5597: table#LC_title_bar td {
 5598:   background: $tabbg;
 5599: }
 5600: 
 5601: table#LC_menubuttons img {
 5602:   border: none;
 5603: }
 5604: 
 5605: .LC_breadcrumbs_component {
 5606:   float: right;
 5607:   margin: 0 1em;
 5608: }
 5609: .LC_breadcrumbs_component img {
 5610:   vertical-align: middle;
 5611: }
 5612: 
 5613: td.LC_table_cell_checkbox {
 5614:   text-align: center;
 5615: }
 5616: 
 5617: .LC_fontsize_small {
 5618:   font-size: 70%;
 5619: }
 5620: 
 5621: #LC_breadcrumbs {
 5622:   clear:both;
 5623:   background: $sidebg;
 5624:   border-bottom: 1px solid $lg_border_color;
 5625:   line-height: 2.5em;
 5626:   overflow: hidden;
 5627:   margin: 0;
 5628:   padding: 0;
 5629:   text-align: left;
 5630: }
 5631: 
 5632: .LC_head_subbox, .LC_actionbox {
 5633:   clear:both;
 5634:   background: #F8F8F8; /* $sidebg; */
 5635:   border: 1px solid $sidebg;
 5636:   margin: 0 0 10px 0;
 5637:   padding: 3px;
 5638:   text-align: left;
 5639: }
 5640: 
 5641: .LC_fontsize_medium {
 5642:   font-size: 85%;
 5643: }
 5644: 
 5645: .LC_fontsize_large {
 5646:   font-size: 120%;
 5647: }
 5648: 
 5649: .LC_menubuttons_inline_text {
 5650:   color: $font;
 5651:   font-size: 90%;
 5652:   padding-left:3px;
 5653: }
 5654: 
 5655: .LC_menubuttons_inline_text img{
 5656:   vertical-align: middle;
 5657: }
 5658: 
 5659: li.LC_menubuttons_inline_text img {
 5660:   cursor:pointer;
 5661:   text-decoration: none;
 5662: }
 5663: 
 5664: .LC_menubuttons_link {
 5665:   text-decoration: none;
 5666: }
 5667: 
 5668: .LC_menubuttons_category {
 5669:   color: $font;
 5670:   background: $pgbg;
 5671:   font-size: larger;
 5672:   font-weight: bold;
 5673: }
 5674: 
 5675: td.LC_menubuttons_text {
 5676:   color: $font;
 5677: }
 5678: 
 5679: .LC_current_location {
 5680:   background: $tabbg;
 5681: }
 5682: 
 5683: table.LC_data_table {
 5684:   border: 1px solid #000000;
 5685:   border-collapse: separate;
 5686:   border-spacing: 1px;
 5687:   background: $pgbg;
 5688: }
 5689: 
 5690: .LC_data_table_dense {
 5691:   font-size: small;
 5692: }
 5693: 
 5694: table.LC_nested_outer {
 5695:   border: 1px solid #000000;
 5696:   border-collapse: collapse;
 5697:   border-spacing: 0;
 5698:   width: 100%;
 5699: }
 5700: 
 5701: table.LC_innerpickbox,
 5702: table.LC_nested {
 5703:   border: none;
 5704:   border-collapse: collapse;
 5705:   border-spacing: 0;
 5706:   width: 100%;
 5707: }
 5708: 
 5709: table.LC_data_table tr th,
 5710: table.LC_calendar tr th,
 5711: table.LC_prior_tries tr th,
 5712: table.LC_innerpickbox tr th {
 5713:   font-weight: bold;
 5714:   background-color: $data_table_head;
 5715:   color:$fontmenu;
 5716:   font-size:90%;
 5717: }
 5718: 
 5719: table.LC_innerpickbox tr th,
 5720: table.LC_innerpickbox tr td {
 5721:   vertical-align: top;
 5722: }
 5723: 
 5724: table.LC_data_table tr.LC_info_row > td {
 5725:   background-color: #CCCCCC;
 5726:   font-weight: bold;
 5727:   text-align: left;
 5728: }
 5729: 
 5730: table.LC_data_table tr.LC_odd_row > td {
 5731:   background-color: $data_table_light;
 5732:   padding: 2px;
 5733:   vertical-align: top;
 5734: }
 5735: 
 5736: table.LC_pick_box tr > td.LC_odd_row {
 5737:   background-color: $data_table_light;
 5738:   vertical-align: top;
 5739: }
 5740: 
 5741: table.LC_data_table tr.LC_even_row > td {
 5742:   background-color: $data_table_dark;
 5743:   padding: 2px;
 5744:   vertical-align: top;
 5745: }
 5746: 
 5747: table.LC_pick_box tr > td.LC_even_row {
 5748:   background-color: $data_table_dark;
 5749:   vertical-align: top;
 5750: }
 5751: 
 5752: table.LC_data_table tr.LC_data_table_highlight td {
 5753:   background-color: $data_table_darker;
 5754: }
 5755: 
 5756: table.LC_data_table tr td.LC_leftcol_header {
 5757:   background-color: $data_table_head;
 5758:   font-weight: bold;
 5759: }
 5760: 
 5761: table.LC_data_table tr.LC_empty_row td,
 5762: table.LC_nested tr.LC_empty_row td {
 5763:   font-weight: bold;
 5764:   font-style: italic;
 5765:   text-align: center;
 5766:   padding: 8px;
 5767: }
 5768: 
 5769: table.LC_data_table tr.LC_empty_row td,
 5770: table.LC_data_table tr.LC_footer_row td {
 5771:   background-color: $sidebg;
 5772: }
 5773: 
 5774: table.LC_nested tr.LC_empty_row td {
 5775:   background-color: #FFFFFF;
 5776: }
 5777: 
 5778: table.LC_caption {
 5779: }
 5780: 
 5781: table.LC_nested tr.LC_empty_row td {
 5782:   padding: 4ex
 5783: }
 5784: 
 5785: table.LC_nested_outer tr th {
 5786:   font-weight: bold;
 5787:   color:$fontmenu;
 5788:   background-color: $data_table_head;
 5789:   font-size: small;
 5790:   border-bottom: 1px solid #000000;
 5791: }
 5792: 
 5793: table.LC_nested_outer tr td.LC_subheader {
 5794:   background-color: $data_table_head;
 5795:   font-weight: bold;
 5796:   font-size: small;
 5797:   border-bottom: 1px solid #000000;
 5798:   text-align: right;
 5799: }
 5800: 
 5801: table.LC_nested tr.LC_info_row td {
 5802:   background-color: #CCCCCC;
 5803:   font-weight: bold;
 5804:   font-size: small;
 5805:   text-align: center;
 5806: }
 5807: 
 5808: table.LC_nested tr.LC_info_row td.LC_left_item,
 5809: table.LC_nested_outer tr th.LC_left_item {
 5810:   text-align: left;
 5811: }
 5812: 
 5813: table.LC_nested td {
 5814:   background-color: #FFFFFF;
 5815:   font-size: small;
 5816: }
 5817: 
 5818: table.LC_nested_outer tr th.LC_right_item,
 5819: table.LC_nested tr.LC_info_row td.LC_right_item,
 5820: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5821: table.LC_nested tr td.LC_right_item {
 5822:   text-align: right;
 5823: }
 5824: 
 5825: table.LC_nested tr.LC_odd_row td {
 5826:   background-color: #EEEEEE;
 5827: }
 5828: 
 5829: table.LC_createuser {
 5830: }
 5831: 
 5832: table.LC_createuser tr.LC_section_row td {
 5833:   font-size: small;
 5834: }
 5835: 
 5836: table.LC_createuser tr.LC_info_row td  {
 5837:   background-color: #CCCCCC;
 5838:   font-weight: bold;
 5839:   text-align: center;
 5840: }
 5841: 
 5842: table.LC_calendar {
 5843:   border: 1px solid #000000;
 5844:   border-collapse: collapse;
 5845:   width: 98%;
 5846: }
 5847: 
 5848: table.LC_calendar_pickdate {
 5849:   font-size: xx-small;
 5850: }
 5851: 
 5852: table.LC_calendar tr td {
 5853:   border: 1px solid #000000;
 5854:   vertical-align: top;
 5855:   width: 14%;
 5856: }
 5857: 
 5858: table.LC_calendar tr td.LC_calendar_day_empty {
 5859:   background-color: $data_table_dark;
 5860: }
 5861: 
 5862: table.LC_calendar tr td.LC_calendar_day_current {
 5863:   background-color: $data_table_highlight;
 5864: }
 5865: 
 5866: table.LC_data_table tr td.LC_mail_new {
 5867:   background-color: $mail_new;
 5868: }
 5869: 
 5870: table.LC_data_table tr.LC_mail_new:hover {
 5871:   background-color: $mail_new_hover;
 5872: }
 5873: 
 5874: table.LC_data_table tr td.LC_mail_read {
 5875:   background-color: $mail_read;
 5876: }
 5877: 
 5878: /*
 5879: table.LC_data_table tr.LC_mail_read:hover {
 5880:   background-color: $mail_read_hover;
 5881: }
 5882: */
 5883: 
 5884: table.LC_data_table tr td.LC_mail_replied {
 5885:   background-color: $mail_replied;
 5886: }
 5887: 
 5888: /*
 5889: table.LC_data_table tr.LC_mail_replied:hover {
 5890:   background-color: $mail_replied_hover;
 5891: }
 5892: */
 5893: 
 5894: table.LC_data_table tr td.LC_mail_other {
 5895:   background-color: $mail_other;
 5896: }
 5897: 
 5898: /*
 5899: table.LC_data_table tr.LC_mail_other:hover {
 5900:   background-color: $mail_other_hover;
 5901: }
 5902: */
 5903: 
 5904: table.LC_data_table tr > td.LC_browser_file,
 5905: table.LC_data_table tr > td.LC_browser_file_published {
 5906:   background: #AAEE77;
 5907: }
 5908: 
 5909: table.LC_data_table tr > td.LC_browser_file_locked,
 5910: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5911:   background: #FFAA99;
 5912: }
 5913: 
 5914: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5915:   background: #888888;
 5916: }
 5917: 
 5918: table.LC_data_table tr > td.LC_browser_file_modified,
 5919: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5920:   background: #F8F866;
 5921: }
 5922: 
 5923: table.LC_data_table tr.LC_browser_folder > td {
 5924:   background: #E0E8FF;
 5925: }
 5926: 
 5927: table.LC_data_table tr > td.LC_roles_is {
 5928:   /* background: #77FF77; */
 5929: }
 5930: 
 5931: table.LC_data_table tr > td.LC_roles_future {
 5932:   border-right: 8px solid #FFFF77;
 5933: }
 5934: 
 5935: table.LC_data_table tr > td.LC_roles_will {
 5936:   border-right: 8px solid #FFAA77;
 5937: }
 5938: 
 5939: table.LC_data_table tr > td.LC_roles_expired {
 5940:   border-right: 8px solid #FF7777;
 5941: }
 5942: 
 5943: table.LC_data_table tr > td.LC_roles_will_not {
 5944:   border-right: 8px solid #AAFF77;
 5945: }
 5946: 
 5947: table.LC_data_table tr > td.LC_roles_selected {
 5948:   border-right: 8px solid #11CC55;
 5949: }
 5950: 
 5951: span.LC_current_location {
 5952:   font-size:larger;
 5953:   background: $pgbg;
 5954: }
 5955: 
 5956: span.LC_current_nav_location {
 5957:   font-weight:bold;
 5958:   background: $sidebg;
 5959: }
 5960: 
 5961: span.LC_parm_menu_item {
 5962:   font-size: larger;
 5963: }
 5964: 
 5965: span.LC_parm_scope_all {
 5966:   color: red;
 5967: }
 5968: 
 5969: span.LC_parm_scope_folder {
 5970:   color: green;
 5971: }
 5972: 
 5973: span.LC_parm_scope_resource {
 5974:   color: orange;
 5975: }
 5976: 
 5977: span.LC_parm_part {
 5978:   color: blue;
 5979: }
 5980: 
 5981: span.LC_parm_folder,
 5982: span.LC_parm_symb {
 5983:   font-size: x-small;
 5984:   font-family: $mono;
 5985:   color: #AAAAAA;
 5986: }
 5987: 
 5988: ul.LC_parm_parmlist li {
 5989:   display: inline-block;
 5990:   padding: 0.3em 0.8em;
 5991:   vertical-align: top;
 5992:   width: 150px;
 5993:   border-top:1px solid $lg_border_color;
 5994: }
 5995: 
 5996: td.LC_parm_overview_level_menu,
 5997: td.LC_parm_overview_map_menu,
 5998: td.LC_parm_overview_parm_selectors,
 5999: td.LC_parm_overview_restrictions  {
 6000:   border: 1px solid black;
 6001:   border-collapse: collapse;
 6002: }
 6003: 
 6004: table.LC_parm_overview_restrictions td {
 6005:   border-width: 1px 4px 1px 4px;
 6006:   border-style: solid;
 6007:   border-color: $pgbg;
 6008:   text-align: center;
 6009: }
 6010: 
 6011: table.LC_parm_overview_restrictions th {
 6012:   background: $tabbg;
 6013:   border-width: 1px 4px 1px 4px;
 6014:   border-style: solid;
 6015:   border-color: $pgbg;
 6016: }
 6017: 
 6018: table#LC_helpmenu {
 6019:   border: none;
 6020:   height: 55px;
 6021:   border-spacing: 0;
 6022: }
 6023: 
 6024: table#LC_helpmenu fieldset legend {
 6025:   font-size: larger;
 6026: }
 6027: 
 6028: table#LC_helpmenu_links {
 6029:   width: 100%;
 6030:   border: 1px solid black;
 6031:   background: $pgbg;
 6032:   padding: 0;
 6033:   border-spacing: 1px;
 6034: }
 6035: 
 6036: table#LC_helpmenu_links tr td {
 6037:   padding: 1px;
 6038:   background: $tabbg;
 6039:   text-align: center;
 6040:   font-weight: bold;
 6041: }
 6042: 
 6043: table#LC_helpmenu_links a:link,
 6044: table#LC_helpmenu_links a:visited,
 6045: table#LC_helpmenu_links a:active {
 6046:   text-decoration: none;
 6047:   color: $font;
 6048: }
 6049: 
 6050: table#LC_helpmenu_links a:hover {
 6051:   text-decoration: underline;
 6052:   color: $vlink;
 6053: }
 6054: 
 6055: .LC_chrt_popup_exists {
 6056:   border: 1px solid #339933;
 6057:   margin: -1px;
 6058: }
 6059: 
 6060: .LC_chrt_popup_up {
 6061:   border: 1px solid yellow;
 6062:   margin: -1px;
 6063: }
 6064: 
 6065: .LC_chrt_popup {
 6066:   border: 1px solid #8888FF;
 6067:   background: #CCCCFF;
 6068: }
 6069: 
 6070: table.LC_pick_box {
 6071:   border-collapse: separate;
 6072:   background: white;
 6073:   border: 1px solid black;
 6074:   border-spacing: 1px;
 6075: }
 6076: 
 6077: table.LC_pick_box td.LC_pick_box_title {
 6078:   background: $sidebg;
 6079:   font-weight: bold;
 6080:   text-align: left;
 6081:   vertical-align: top;
 6082:   width: 184px;
 6083:   padding: 8px;
 6084: }
 6085: 
 6086: table.LC_pick_box td.LC_pick_box_value {
 6087:   text-align: left;
 6088:   padding: 8px;
 6089: }
 6090: 
 6091: table.LC_pick_box td.LC_pick_box_select {
 6092:   text-align: left;
 6093:   padding: 8px;
 6094: }
 6095: 
 6096: table.LC_pick_box td.LC_pick_box_separator {
 6097:   padding: 0;
 6098:   height: 1px;
 6099:   background: black;
 6100: }
 6101: 
 6102: table.LC_pick_box td.LC_pick_box_submit {
 6103:   text-align: right;
 6104: }
 6105: 
 6106: table.LC_pick_box td.LC_evenrow_value {
 6107:   text-align: left;
 6108:   padding: 8px;
 6109:   background-color: $data_table_light;
 6110: }
 6111: 
 6112: table.LC_pick_box td.LC_oddrow_value {
 6113:   text-align: left;
 6114:   padding: 8px;
 6115:   background-color: $data_table_light;
 6116: }
 6117: 
 6118: span.LC_helpform_receipt_cat {
 6119:   font-weight: bold;
 6120: }
 6121: 
 6122: table.LC_group_priv_box {
 6123:   background: white;
 6124:   border: 1px solid black;
 6125:   border-spacing: 1px;
 6126: }
 6127: 
 6128: table.LC_group_priv_box td.LC_pick_box_title {
 6129:   background: $tabbg;
 6130:   font-weight: bold;
 6131:   text-align: right;
 6132:   width: 184px;
 6133: }
 6134: 
 6135: table.LC_group_priv_box td.LC_groups_fixed {
 6136:   background: $data_table_light;
 6137:   text-align: center;
 6138: }
 6139: 
 6140: table.LC_group_priv_box td.LC_groups_optional {
 6141:   background: $data_table_dark;
 6142:   text-align: center;
 6143: }
 6144: 
 6145: table.LC_group_priv_box td.LC_groups_functionality {
 6146:   background: $data_table_darker;
 6147:   text-align: center;
 6148:   font-weight: bold;
 6149: }
 6150: 
 6151: table.LC_group_priv td {
 6152:   text-align: left;
 6153:   padding: 0;
 6154: }
 6155: 
 6156: .LC_navbuttons {
 6157:   margin: 2ex 0ex 2ex 0ex;
 6158: }
 6159: 
 6160: .LC_topic_bar {
 6161:   font-weight: bold;
 6162:   background: $tabbg;
 6163:   margin: 1em 0em 1em 2em;
 6164:   padding: 3px;
 6165:   font-size: 1.2em;
 6166: }
 6167: 
 6168: .LC_topic_bar span {
 6169:   left: 0.5em;
 6170:   position: absolute;
 6171:   vertical-align: middle;
 6172:   font-size: 1.2em;
 6173: }
 6174: 
 6175: table.LC_course_group_status {
 6176:   margin: 20px;
 6177: }
 6178: 
 6179: table.LC_status_selector td {
 6180:   vertical-align: top;
 6181:   text-align: center;
 6182:   padding: 4px;
 6183: }
 6184: 
 6185: div.LC_feedback_link {
 6186:   clear: both;
 6187:   background: $sidebg;
 6188:   width: 100%;
 6189:   padding-bottom: 10px;
 6190:   border: 1px $tabbg solid;
 6191:   height: 22px;
 6192:   line-height: 22px;
 6193:   padding-top: 5px;
 6194: }
 6195: 
 6196: div.LC_feedback_link img {
 6197:   height: 22px;
 6198:   vertical-align:middle;
 6199: }
 6200: 
 6201: div.LC_feedback_link a {
 6202:   text-decoration: none;
 6203: }
 6204: 
 6205: div.LC_comblock {
 6206:   display:inline;
 6207:   color:$font;
 6208:   font-size:90%;
 6209: }
 6210: 
 6211: div.LC_feedback_link div.LC_comblock {
 6212:   padding-left:5px;
 6213: }
 6214: 
 6215: div.LC_feedback_link div.LC_comblock a {
 6216:   color:$font;
 6217: }
 6218: 
 6219: span.LC_feedback_link {
 6220:   /* background: $feedback_link_bg; */
 6221:   font-size: larger;
 6222: }
 6223: 
 6224: span.LC_message_link {
 6225:   /* background: $feedback_link_bg; */
 6226:   font-size: larger;
 6227:   position: absolute;
 6228:   right: 1em;
 6229: }
 6230: 
 6231: table.LC_prior_tries {
 6232:   border: 1px solid #000000;
 6233:   border-collapse: separate;
 6234:   border-spacing: 1px;
 6235: }
 6236: 
 6237: table.LC_prior_tries td {
 6238:   padding: 2px;
 6239: }
 6240: 
 6241: .LC_answer_correct {
 6242:   background: lightgreen;
 6243:   color: darkgreen;
 6244:   padding: 6px;
 6245: }
 6246: 
 6247: .LC_answer_charged_try {
 6248:   background: #FFAAAA;
 6249:   color: darkred;
 6250:   padding: 6px;
 6251: }
 6252: 
 6253: .LC_answer_not_charged_try,
 6254: .LC_answer_no_grade,
 6255: .LC_answer_late {
 6256:   background: lightyellow;
 6257:   color: black;
 6258:   padding: 6px;
 6259: }
 6260: 
 6261: .LC_answer_previous {
 6262:   background: lightblue;
 6263:   color: darkblue;
 6264:   padding: 6px;
 6265: }
 6266: 
 6267: .LC_answer_no_message {
 6268:   background: #FFFFFF;
 6269:   color: black;
 6270:   padding: 6px;
 6271: }
 6272: 
 6273: .LC_answer_unknown {
 6274:   background: orange;
 6275:   color: black;
 6276:   padding: 6px;
 6277: }
 6278: 
 6279: span.LC_prior_numerical,
 6280: span.LC_prior_string,
 6281: span.LC_prior_custom,
 6282: span.LC_prior_reaction,
 6283: span.LC_prior_math {
 6284:   font-family: $mono;
 6285:   white-space: pre;
 6286: }
 6287: 
 6288: span.LC_prior_string {
 6289:   font-family: $mono;
 6290:   white-space: pre;
 6291: }
 6292: 
 6293: table.LC_prior_option {
 6294:   width: 100%;
 6295:   border-collapse: collapse;
 6296: }
 6297: 
 6298: table.LC_prior_rank,
 6299: table.LC_prior_match {
 6300:   border-collapse: collapse;
 6301: }
 6302: 
 6303: table.LC_prior_option tr td,
 6304: table.LC_prior_rank tr td,
 6305: table.LC_prior_match tr td {
 6306:   border: 1px solid #000000;
 6307: }
 6308: 
 6309: .LC_nobreak {
 6310:   white-space: nowrap;
 6311: }
 6312: 
 6313: span.LC_cusr_emph {
 6314:   font-style: italic;
 6315: }
 6316: 
 6317: span.LC_cusr_subheading {
 6318:   font-weight: normal;
 6319:   font-size: 85%;
 6320: }
 6321: 
 6322: div.LC_docs_entry_move {
 6323:   border: 1px solid #BBBBBB;
 6324:   background: #DDDDDD;
 6325:   width: 22px;
 6326:   padding: 1px;
 6327:   margin: 0;
 6328: }
 6329: 
 6330: table.LC_data_table tr > td.LC_docs_entry_commands,
 6331: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6332:   font-size: x-small;
 6333: }
 6334: 
 6335: .LC_docs_entry_parameter {
 6336:   white-space: nowrap;
 6337: }
 6338: 
 6339: .LC_docs_copy {
 6340:   color: #000099;
 6341: }
 6342: 
 6343: .LC_docs_cut {
 6344:   color: #550044;
 6345: }
 6346: 
 6347: .LC_docs_rename {
 6348:   color: #009900;
 6349: }
 6350: 
 6351: .LC_docs_remove {
 6352:   color: #990000;
 6353: }
 6354: 
 6355: .LC_docs_reinit_warn,
 6356: .LC_docs_ext_edit {
 6357:   font-size: x-small;
 6358: }
 6359: 
 6360: table.LC_docs_adddocs td,
 6361: table.LC_docs_adddocs th {
 6362:   border: 1px solid #BBBBBB;
 6363:   padding: 4px;
 6364:   background: #DDDDDD;
 6365: }
 6366: 
 6367: table.LC_sty_begin {
 6368:   background: #BBFFBB;
 6369: }
 6370: 
 6371: table.LC_sty_end {
 6372:   background: #FFBBBB;
 6373: }
 6374: 
 6375: table.LC_double_column {
 6376:   border-width: 0;
 6377:   border-collapse: collapse;
 6378:   width: 100%;
 6379:   padding: 2px;
 6380: }
 6381: 
 6382: table.LC_double_column tr td.LC_left_col {
 6383:   top: 2px;
 6384:   left: 2px;
 6385:   width: 47%;
 6386:   vertical-align: top;
 6387: }
 6388: 
 6389: table.LC_double_column tr td.LC_right_col {
 6390:   top: 2px;
 6391:   right: 2px;
 6392:   width: 47%;
 6393:   vertical-align: top;
 6394: }
 6395: 
 6396: div.LC_left_float {
 6397:   float: left;
 6398:   padding-right: 5%;
 6399:   padding-bottom: 4px;
 6400: }
 6401: 
 6402: div.LC_clear_float_header {
 6403:   padding-bottom: 2px;
 6404: }
 6405: 
 6406: div.LC_clear_float_footer {
 6407:   padding-top: 10px;
 6408:   clear: both;
 6409: }
 6410: 
 6411: div.LC_grade_show_user {
 6412: /*  border-left: 5px solid $sidebg; */
 6413:   border-top: 5px solid #000000;
 6414:   margin: 50px 0 0 0;
 6415:   padding: 15px 0 5px 10px;
 6416: }
 6417: 
 6418: div.LC_grade_show_user_odd_row {
 6419: /*  border-left: 5px solid #000000; */
 6420: }
 6421: 
 6422: div.LC_grade_show_user div.LC_Box {
 6423:   margin-right: 50px;
 6424: }
 6425: 
 6426: div.LC_grade_submissions,
 6427: div.LC_grade_message_center,
 6428: div.LC_grade_info_links {
 6429:   margin: 5px;
 6430:   width: 99%;
 6431:   background: #FFFFFF;
 6432: }
 6433: 
 6434: div.LC_grade_submissions_header,
 6435: div.LC_grade_message_center_header {
 6436:   font-weight: bold;
 6437:   font-size: large;
 6438: }
 6439: 
 6440: div.LC_grade_submissions_body,
 6441: div.LC_grade_message_center_body {
 6442:   border: 1px solid black;
 6443:   width: 99%;
 6444:   background: #FFFFFF;
 6445: }
 6446: 
 6447: table.LC_scantron_action {
 6448:   width: 100%;
 6449: }
 6450: 
 6451: table.LC_scantron_action tr th {
 6452:   font-weight:bold;
 6453:   font-style:normal;
 6454: }
 6455: 
 6456: .LC_edit_problem_header,
 6457: div.LC_edit_problem_footer {
 6458:   font-weight: normal;
 6459:   font-size:  medium;
 6460:   margin: 2px;
 6461:   background-color: $sidebg;
 6462: }
 6463: 
 6464: div.LC_edit_problem_header,
 6465: div.LC_edit_problem_header div,
 6466: div.LC_edit_problem_footer,
 6467: div.LC_edit_problem_footer div,
 6468: div.LC_edit_problem_editxml_header,
 6469: div.LC_edit_problem_editxml_header div {
 6470:   margin-top: 5px;
 6471: }
 6472: 
 6473: div.LC_edit_problem_header_title {
 6474:   font-weight: bold;
 6475:   font-size: larger;
 6476:   background: $tabbg;
 6477:   padding: 3px;
 6478:   margin: 0 0 5px 0;
 6479: }
 6480: 
 6481: table.LC_edit_problem_header_title {
 6482:   width: 100%;
 6483:   background: $tabbg;
 6484: }
 6485: 
 6486: div.LC_edit_problem_discards {
 6487:   float: left;
 6488:   padding-bottom: 5px;
 6489: }
 6490: 
 6491: div.LC_edit_problem_saves {
 6492:   float: right;
 6493:   padding-bottom: 5px;
 6494: }
 6495: 
 6496: .LC_edit_opt {
 6497:   padding-left: 1em;
 6498:   white-space: nowrap;
 6499: }
 6500: 
 6501: .LC_edit_problem_latexhelper{
 6502:     text-align: right;
 6503: }
 6504: 
 6505: #LC_edit_problem_colorful div{
 6506:     margin-left: 40px;
 6507: }
 6508: 
 6509: img.stift {
 6510:   border-width: 0;
 6511:   vertical-align: middle;
 6512: }
 6513: 
 6514: table td.LC_mainmenu_col_fieldset {
 6515:   vertical-align: top;
 6516: }
 6517: 
 6518: div.LC_createcourse {
 6519:   margin: 10px 10px 10px 10px;
 6520: }
 6521: 
 6522: .LC_dccid {
 6523:   float: right;
 6524:   margin: 0.2em 0 0 0;
 6525:   padding: 0;
 6526:   font-size: 90%;
 6527:   display:none;
 6528: }
 6529: 
 6530: ol.LC_primary_menu a:hover,
 6531: ol#LC_MenuBreadcrumbs a:hover,
 6532: ol#LC_PathBreadcrumbs a:hover,
 6533: ul#LC_secondary_menu a:hover,
 6534: .LC_FormSectionClearButton input:hover
 6535: ul.LC_TabContent   li:hover a {
 6536:   color:$button_hover;
 6537:   text-decoration:none;
 6538: }
 6539: 
 6540: h1 {
 6541:   padding: 0;
 6542:   line-height:130%;
 6543: }
 6544: 
 6545: h2,
 6546: h3,
 6547: h4,
 6548: h5,
 6549: h6 {
 6550:   margin: 5px 0 5px 0;
 6551:   padding: 0;
 6552:   line-height:130%;
 6553: }
 6554: 
 6555: .LC_hcell {
 6556:   padding:3px 15px 3px 15px;
 6557:   margin: 0;
 6558:   background-color:$tabbg;
 6559:   color:$fontmenu;
 6560:   border-bottom:solid 1px $lg_border_color;
 6561: }
 6562: 
 6563: .LC_Box > .LC_hcell {
 6564:   margin: 0 -10px 10px -10px;
 6565: }
 6566: 
 6567: .LC_noBorder {
 6568:   border: 0;
 6569: }
 6570: 
 6571: .LC_FormSectionClearButton input {
 6572:   background-color:transparent;
 6573:   border: none;
 6574:   cursor:pointer;
 6575:   text-decoration:underline;
 6576: }
 6577: 
 6578: .LC_help_open_topic {
 6579:   color: #FFFFFF;
 6580:   background-color: #EEEEFF;
 6581:   margin: 1px;
 6582:   padding: 4px;
 6583:   border: 1px solid #000033;
 6584:   white-space: nowrap;
 6585:   /* vertical-align: middle; */
 6586: }
 6587: 
 6588: dl,
 6589: ul,
 6590: div,
 6591: fieldset {
 6592:   margin: 10px 10px 10px 0;
 6593:   /* overflow: hidden; */
 6594: }
 6595: 
 6596: fieldset > legend {
 6597:   font-weight: bold;
 6598:   padding: 0 5px 0 5px;
 6599: }
 6600: 
 6601: #LC_nav_bar {
 6602:   float: left;
 6603:   background-color: $pgbg_or_bgcolor;
 6604:   margin: 0 0 2px 0;
 6605: }
 6606: 
 6607: #LC_realm {
 6608:   margin: 0.2em 0 0 0;
 6609:   padding: 0;
 6610:   font-weight: bold;
 6611:   text-align: center;
 6612:   background-color: $pgbg_or_bgcolor;
 6613: }
 6614: 
 6615: #LC_nav_bar em {
 6616:   font-weight: bold;
 6617:   font-style: normal;
 6618: }
 6619: 
 6620: ol.LC_primary_menu {
 6621:   margin: 0;
 6622:   padding: 0;
 6623:   background-color: $pgbg_or_bgcolor;
 6624: }
 6625: 
 6626: ol#LC_PathBreadcrumbs {
 6627:   margin: 0;
 6628: }
 6629: 
 6630: ol.LC_primary_menu li {
 6631:   color: RGB(80, 80, 80);
 6632:   vertical-align: middle;
 6633:   text-align: left;
 6634:   list-style: none;
 6635:   float: left;
 6636: }
 6637: 
 6638: ol.LC_primary_menu li a {
 6639:   display: block;
 6640:   margin: 0;
 6641:   padding: 0 5px 0 10px;
 6642:   text-decoration: none;
 6643: }
 6644: 
 6645: ol.LC_primary_menu li ul {
 6646:   display: none;
 6647:   width: 10em;
 6648:   background-color: $data_table_light;
 6649: }
 6650: 
 6651: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6652:   display: block;
 6653:   position: absolute;
 6654:   margin: 0;
 6655:   padding: 0;
 6656:   z-index: 2;
 6657: }
 6658: 
 6659: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6660:   font-size: 90%;
 6661:   vertical-align: top;
 6662:   float: none;
 6663:   border-left: 1px solid black;
 6664:   border-right: 1px solid black;
 6665: }
 6666: 
 6667: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6668:   background-color:$data_table_light;
 6669: }
 6670: 
 6671: ol.LC_primary_menu li li a:hover {
 6672:    color:$button_hover;
 6673:    background-color:$data_table_dark;
 6674: }
 6675: 
 6676: ol.LC_primary_menu li img {
 6677:   vertical-align: bottom;
 6678:   height: 1.1em;
 6679:   margin: 0.2em 0 0 0;
 6680: }
 6681: 
 6682: ol.LC_primary_menu a {
 6683:   color: RGB(80, 80, 80);
 6684:   text-decoration: none;
 6685: }
 6686: 
 6687: ol.LC_primary_menu a.LC_new_message {
 6688:   font-weight:bold;
 6689:   color: darkred;
 6690: }
 6691: 
 6692: ol.LC_docs_parameters {
 6693:   margin-left: 0;
 6694:   padding: 0;
 6695:   list-style: none;
 6696: }
 6697: 
 6698: ol.LC_docs_parameters li {
 6699:   margin: 0;
 6700:   padding-right: 20px;
 6701:   display: inline;
 6702: }
 6703: 
 6704: ol.LC_docs_parameters li:before {
 6705:   content: "\\002022 \\0020";
 6706: }
 6707: 
 6708: li.LC_docs_parameters_title {
 6709:   font-weight: bold;
 6710: }
 6711: 
 6712: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6713:   content: "";
 6714: }
 6715: 
 6716: ul#LC_secondary_menu {
 6717:   clear: right;
 6718:   color: $fontmenu;
 6719:   background: $tabbg;
 6720:   list-style: none;
 6721:   padding: 0;
 6722:   margin: 0;
 6723:   width: 100%;
 6724:   text-align: left;
 6725:   float: left;
 6726: }
 6727: 
 6728: ul#LC_secondary_menu li {
 6729:   font-weight: bold;
 6730:   line-height: 1.8em;
 6731:   border-right: 1px solid black;
 6732:   float: left;
 6733: }
 6734: 
 6735: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6736:   background-color: $data_table_light;
 6737: }
 6738: 
 6739: ul#LC_secondary_menu li a {
 6740:   padding: 0 0.8em;
 6741: }
 6742: 
 6743: ul#LC_secondary_menu li ul {
 6744:   display: none;
 6745: }
 6746: 
 6747: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6748:   display: block;
 6749:   position: absolute;
 6750:   margin: 0;
 6751:   padding: 0;
 6752:   list-style:none;
 6753:   float: none;
 6754:   background-color: $data_table_light;
 6755:   z-index: 2;
 6756:   margin-left: -1px;
 6757: }
 6758: 
 6759: ul#LC_secondary_menu li ul li {
 6760:   font-size: 90%;
 6761:   vertical-align: top;
 6762:   border-left: 1px solid black;
 6763:   border-right: 1px solid black;
 6764:   background-color: $data_table_light;
 6765:   list-style:none;
 6766:   float: none;
 6767: }
 6768: 
 6769: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6770:   background-color: $data_table_dark;
 6771: }
 6772: 
 6773: ul.LC_TabContent {
 6774:   display:block;
 6775:   background: $sidebg;
 6776:   border-bottom: solid 1px $lg_border_color;
 6777:   list-style:none;
 6778:   margin: -1px -10px 0 -10px;
 6779:   padding: 0;
 6780: }
 6781: 
 6782: ul.LC_TabContent li,
 6783: ul.LC_TabContentBigger li {
 6784:   float:left;
 6785: }
 6786: 
 6787: ul#LC_secondary_menu li a {
 6788:   color: $fontmenu;
 6789:   text-decoration: none;
 6790: }
 6791: 
 6792: ul.LC_TabContent {
 6793:   min-height:20px;
 6794: }
 6795: 
 6796: ul.LC_TabContent li {
 6797:   vertical-align:middle;
 6798:   padding: 0 16px 0 10px;
 6799:   background-color:$tabbg;
 6800:   border-bottom:solid 1px $lg_border_color;
 6801:   border-left: solid 1px $font;
 6802: }
 6803: 
 6804: ul.LC_TabContent .right {
 6805:   float:right;
 6806: }
 6807: 
 6808: ul.LC_TabContent li a,
 6809: ul.LC_TabContent li {
 6810:   color:rgb(47,47,47);
 6811:   text-decoration:none;
 6812:   font-size:95%;
 6813:   font-weight:bold;
 6814:   min-height:20px;
 6815: }
 6816: 
 6817: ul.LC_TabContent li a:hover,
 6818: ul.LC_TabContent li a:focus {
 6819:   color: $button_hover;
 6820:   background:none;
 6821:   outline:none;
 6822: }
 6823: 
 6824: ul.LC_TabContent li:hover {
 6825:   color: $button_hover;
 6826:   cursor:pointer;
 6827: }
 6828: 
 6829: ul.LC_TabContent li.active {
 6830:   color: $font;
 6831:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6832:   border-bottom:solid 1px #FFFFFF;
 6833:   cursor: default;
 6834: }
 6835: 
 6836: ul.LC_TabContent li.active a {
 6837:   color:$font;
 6838:   background:#FFFFFF;
 6839:   outline: none;
 6840: }
 6841: 
 6842: ul.LC_TabContent li.goback {
 6843:   float: left;
 6844:   border-left: none;
 6845: }
 6846: 
 6847: #maincoursedoc {
 6848:   clear:both;
 6849: }
 6850: 
 6851: ul.LC_TabContentBigger {
 6852:   display:block;
 6853:   list-style:none;
 6854:   padding: 0;
 6855: }
 6856: 
 6857: ul.LC_TabContentBigger li {
 6858:   vertical-align:bottom;
 6859:   height: 30px;
 6860:   font-size:110%;
 6861:   font-weight:bold;
 6862:   color: #737373;
 6863: }
 6864: 
 6865: ul.LC_TabContentBigger li.active {
 6866:   position: relative;
 6867:   top: 1px;
 6868: }
 6869: 
 6870: ul.LC_TabContentBigger li a {
 6871:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6872:   height: 30px;
 6873:   line-height: 30px;
 6874:   text-align: center;
 6875:   display: block;
 6876:   text-decoration: none;
 6877:   outline: none;  
 6878: }
 6879: 
 6880: ul.LC_TabContentBigger li.active a {
 6881:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6882:   color:$font;
 6883: }
 6884: 
 6885: ul.LC_TabContentBigger li b {
 6886:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6887:   display: block;
 6888:   float: left;
 6889:   padding: 0 30px;
 6890:   border-bottom: 1px solid $lg_border_color;
 6891: }
 6892: 
 6893: ul.LC_TabContentBigger li:hover b {
 6894:   color:$button_hover;
 6895: }
 6896: 
 6897: ul.LC_TabContentBigger li.active b {
 6898:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6899:   color:$font;
 6900:   border: 0;
 6901: }
 6902: 
 6903: 
 6904: ul.LC_CourseBreadcrumbs {
 6905:   background: $sidebg;
 6906:   height: 2em;
 6907:   padding-left: 10px;
 6908:   margin: 0;
 6909:   list-style-position: inside;
 6910: }
 6911: 
 6912: ol#LC_MenuBreadcrumbs,
 6913: ol#LC_PathBreadcrumbs {
 6914:   padding-left: 10px;
 6915:   margin: 0;
 6916:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6917: }
 6918: 
 6919: ol#LC_MenuBreadcrumbs li,
 6920: ol#LC_PathBreadcrumbs li,
 6921: ul.LC_CourseBreadcrumbs li {
 6922:   display: inline;
 6923:   white-space: normal;  
 6924: }
 6925: 
 6926: ol#LC_MenuBreadcrumbs li a,
 6927: ul.LC_CourseBreadcrumbs li a {
 6928:   text-decoration: none;
 6929:   font-size:90%;
 6930: }
 6931: 
 6932: ol#LC_MenuBreadcrumbs h1 {
 6933:   display: inline;
 6934:   font-size: 90%;
 6935:   line-height: 2.5em;
 6936:   margin: 0;
 6937:   padding: 0;
 6938: }
 6939: 
 6940: ol#LC_PathBreadcrumbs li a {
 6941:   text-decoration:none;
 6942:   font-size:100%;
 6943:   font-weight:bold;
 6944: }
 6945: 
 6946: .LC_Box {
 6947:   border: solid 1px $lg_border_color;
 6948:   padding: 0 10px 10px 10px;
 6949: }
 6950: 
 6951: .LC_DocsBox {
 6952:   border: solid 1px $lg_border_color;
 6953:   padding: 0 0 10px 10px;
 6954: }
 6955: 
 6956: .LC_AboutMe_Image {
 6957:   float:left;
 6958:   margin-right:10px;
 6959: }
 6960: 
 6961: .LC_Clear_AboutMe_Image {
 6962:   clear:left;
 6963: }
 6964: 
 6965: dl.LC_ListStyleClean dt {
 6966:   padding-right: 5px;
 6967:   display: table-header-group;
 6968: }
 6969: 
 6970: dl.LC_ListStyleClean dd {
 6971:   display: table-row;
 6972: }
 6973: 
 6974: .LC_ListStyleClean,
 6975: .LC_ListStyleSimple,
 6976: .LC_ListStyleNormal,
 6977: .LC_ListStyleSpecial {
 6978:   /* display:block; */
 6979:   list-style-position: inside;
 6980:   list-style-type: none;
 6981:   overflow: hidden;
 6982:   padding: 0;
 6983: }
 6984: 
 6985: .LC_ListStyleSimple li,
 6986: .LC_ListStyleSimple dd,
 6987: .LC_ListStyleNormal li,
 6988: .LC_ListStyleNormal dd,
 6989: .LC_ListStyleSpecial li,
 6990: .LC_ListStyleSpecial dd {
 6991:   margin: 0;
 6992:   padding: 5px 5px 5px 10px;
 6993:   clear: both;
 6994: }
 6995: 
 6996: .LC_ListStyleClean li,
 6997: .LC_ListStyleClean dd {
 6998:   padding-top: 0;
 6999:   padding-bottom: 0;
 7000: }
 7001: 
 7002: .LC_ListStyleSimple dd,
 7003: .LC_ListStyleSimple li {
 7004:   border-bottom: solid 1px $lg_border_color;
 7005: }
 7006: 
 7007: .LC_ListStyleSpecial li,
 7008: .LC_ListStyleSpecial dd {
 7009:   list-style-type: none;
 7010:   background-color: RGB(220, 220, 220);
 7011:   margin-bottom: 4px;
 7012: }
 7013: 
 7014: table.LC_SimpleTable {
 7015:   margin:5px;
 7016:   border:solid 1px $lg_border_color;
 7017: }
 7018: 
 7019: table.LC_SimpleTable tr {
 7020:   padding: 0;
 7021:   border:solid 1px $lg_border_color;
 7022: }
 7023: 
 7024: table.LC_SimpleTable thead {
 7025:   background:rgb(220,220,220);
 7026: }
 7027: 
 7028: div.LC_columnSection {
 7029:   display: block;
 7030:   clear: both;
 7031:   overflow: hidden;
 7032:   margin: 0;
 7033: }
 7034: 
 7035: div.LC_columnSection>* {
 7036:   float: left;
 7037:   margin: 10px 20px 10px 0;
 7038:   overflow:hidden;
 7039: }
 7040: 
 7041: table em {
 7042:   font-weight: bold;
 7043:   font-style: normal;
 7044: }
 7045: 
 7046: table.LC_tableBrowseRes,
 7047: table.LC_tableOfContent {
 7048:   border:none;
 7049:   border-spacing: 1px;
 7050:   padding: 3px;
 7051:   background-color: #FFFFFF;
 7052:   font-size: 90%;
 7053: }
 7054: 
 7055: table.LC_tableOfContent {
 7056:   border-collapse: collapse;
 7057: }
 7058: 
 7059: table.LC_tableBrowseRes a,
 7060: table.LC_tableOfContent a {
 7061:   background-color: transparent;
 7062:   text-decoration: none;
 7063: }
 7064: 
 7065: table.LC_tableOfContent img {
 7066:   border: none;
 7067:   height: 1.3em;
 7068:   vertical-align: text-bottom;
 7069:   margin-right: 0.3em;
 7070: }
 7071: 
 7072: a#LC_content_toolbar_firsthomework {
 7073:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7074: }
 7075: 
 7076: a#LC_content_toolbar_everything {
 7077:   background-image:url(/res/adm/pages/show-all.gif);
 7078: }
 7079: 
 7080: a#LC_content_toolbar_uncompleted {
 7081:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7082: }
 7083: 
 7084: #LC_content_toolbar_clearbubbles {
 7085:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7086: }
 7087: 
 7088: a#LC_content_toolbar_changefolder {
 7089:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7090: }
 7091: 
 7092: a#LC_content_toolbar_changefolder_toggled {
 7093:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7094: }
 7095: 
 7096: a#LC_content_toolbar_edittoplevel {
 7097:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7098: }
 7099: 
 7100: ul#LC_toolbar li a:hover {
 7101:   background-position: bottom center;
 7102: }
 7103: 
 7104: ul#LC_toolbar {
 7105:   padding: 0;
 7106:   margin: 2px;
 7107:   list-style:none;
 7108:   position:relative;
 7109:   background-color:white;
 7110:   overflow: auto;
 7111: }
 7112: 
 7113: ul#LC_toolbar li {
 7114:   border:1px solid white;
 7115:   padding: 0;
 7116:   margin: 0;
 7117:   float: left;
 7118:   display:inline;
 7119:   vertical-align:middle;
 7120:   white-space: nowrap;
 7121: }
 7122: 
 7123: 
 7124: a.LC_toolbarItem {
 7125:   display:block;
 7126:   padding: 0;
 7127:   margin: 0;
 7128:   height: 32px;
 7129:   width: 32px;
 7130:   color:white;
 7131:   border: none;
 7132:   background-repeat:no-repeat;
 7133:   background-color:transparent;
 7134: }
 7135: 
 7136: ul.LC_funclist {
 7137:     margin: 0;
 7138:     padding: 0.5em 1em 0.5em 0;
 7139: }
 7140: 
 7141: ul.LC_funclist > li:first-child {
 7142:     font-weight:bold; 
 7143:     margin-left:0.8em;
 7144: }
 7145: 
 7146: ul.LC_funclist + ul.LC_funclist {
 7147:     /* 
 7148:        left border as a seperator if we have more than
 7149:        one list 
 7150:     */
 7151:     border-left: 1px solid $sidebg;
 7152:     /* 
 7153:        this hides the left border behind the border of the 
 7154:        outer box if element is wrapped to the next 'line' 
 7155:     */
 7156:     margin-left: -1px;
 7157: }
 7158: 
 7159: ul.LC_funclist li {
 7160:   display: inline;
 7161:   white-space: nowrap;
 7162:   margin: 0 0 0 25px;
 7163:   line-height: 150%;
 7164: }
 7165: 
 7166: .LC_hidden {
 7167:   display: none;
 7168: }
 7169: 
 7170: .LCmodal-overlay {
 7171: 		position:fixed;
 7172: 		top:0;
 7173: 		right:0;
 7174: 		bottom:0;
 7175: 		left:0;
 7176: 		height:100%;
 7177: 		width:100%;
 7178: 		margin:0;
 7179: 		padding:0;
 7180: 		background:#999;
 7181: 		opacity:.75;
 7182: 		filter: alpha(opacity=75);
 7183: 		-moz-opacity: 0.75;
 7184: 		z-index:101;
 7185: }
 7186: 
 7187: * html .LCmodal-overlay {   
 7188: 		position: absolute;
 7189: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7190: }
 7191: 
 7192: .LCmodal-window {
 7193: 		position:fixed;
 7194: 		top:50%;
 7195: 		left:50%;
 7196: 		margin:0;
 7197: 		padding:0;
 7198: 		z-index:102;
 7199: 	}
 7200: 
 7201: * html .LCmodal-window {
 7202: 		position:absolute;
 7203: }
 7204: 
 7205: .LCclose-window {
 7206: 		position:absolute;
 7207: 		width:32px;
 7208: 		height:32px;
 7209: 		right:8px;
 7210: 		top:8px;
 7211: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7212: 		text-indent:-99999px;
 7213: 		overflow:hidden;
 7214: 		cursor:pointer;
 7215: }
 7216: 
 7217: /*
 7218:   styles used by TTH when "Default set of options to pass to tth/m
 7219:   when converting TeX" in course settings has been set
 7220: 
 7221:   option passed: -t
 7222: 
 7223: */
 7224: 
 7225: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7226: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7227: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7228: td div.norm {line-height:normal;}
 7229: 
 7230: /*
 7231:   option passed -y3
 7232: */
 7233: 
 7234: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7235: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7236: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7237: 
 7238: END
 7239: }
 7240: 
 7241: =pod
 7242: 
 7243: =item * &headtag()
 7244: 
 7245: Returns a uniform footer for LON-CAPA web pages.
 7246: 
 7247: Inputs: $title - optional title for the head
 7248:         $head_extra - optional extra HTML to put inside the <head>
 7249:         $args - optional arguments
 7250:             force_register - if is true call registerurl so the remote is 
 7251:                              informed
 7252:             redirect       -> array ref of
 7253:                                    1- seconds before redirect occurs
 7254:                                    2- url to redirect to
 7255:                                    3- whether the side effect should occur
 7256:                            (side effect of setting 
 7257:                                $env{'internal.head.redirect'} to the url 
 7258:                                redirected too)
 7259:             domain         -> force to color decorate a page for a specific
 7260:                                domain
 7261:             function       -> force usage of a specific rolish color scheme
 7262:             bgcolor        -> override the default page bgcolor
 7263:             no_auto_mt_title
 7264:                            -> prevent &mt()ing the title arg
 7265: 
 7266: =cut
 7267: 
 7268: sub headtag {
 7269:     my ($title,$head_extra,$args) = @_;
 7270:     
 7271:     my $function = $args->{'function'} || &get_users_function();
 7272:     my $domain   = $args->{'domain'}   || &determinedomain();
 7273:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7274:     my $httphost = $args->{'use_absolute'};
 7275:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7276: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7277: 		   #time(),
 7278: 		   $env{'environment.color.timestamp'},
 7279: 		   $function,$domain,$bgcolor);
 7280: 
 7281:     $url = '/adm/css/'.&escape($url).'.css';
 7282: 
 7283:     my $result =
 7284: 	'<head>'.
 7285: 	&font_settings($args);
 7286: 
 7287:     my $inhibitprint = &print_suppression();
 7288: 
 7289:     if (!$args->{'frameset'}) {
 7290: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7291:     }
 7292:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7293:         $result .= Apache::lonxml::display_title();
 7294:     }
 7295:     if (!$args->{'no_nav_bar'} 
 7296: 	&& !$args->{'only_body'}
 7297: 	&& !$args->{'frameset'}) {
 7298: 	$result .= &help_menu_js($httphost);
 7299:         $result.=&modal_window();
 7300:         $result.=&togglebox_script();
 7301:         $result.=&wishlist_window();
 7302:         $result.=&LCprogressbarUpdate_script();
 7303:     } else {
 7304:         if ($args->{'add_modal'}) {
 7305:            $result.=&modal_window();
 7306:         }
 7307:         if ($args->{'add_wishlist'}) {
 7308:            $result.=&wishlist_window();
 7309:         }
 7310:         if ($args->{'add_togglebox'}) {
 7311:            $result.=&togglebox_script();
 7312:         }
 7313:         if ($args->{'add_progressbar'}) {
 7314:            $result.=&LCprogressbarUpdate_script();
 7315:         }
 7316:     }
 7317:     if (ref($args->{'redirect'})) {
 7318: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7319: 	$url = &Apache::lonenc::check_encrypt($url);
 7320: 	if (!$inhibit_continue) {
 7321: 	    $env{'internal.head.redirect'} = $url;
 7322: 	}
 7323: 	$result.=<<ADDMETA
 7324: <meta http-equiv="pragma" content="no-cache" />
 7325: <meta http-equiv="Refresh" content="$time; url=$url" />
 7326: ADDMETA
 7327:     }
 7328:     if (!defined($title)) {
 7329: 	$title = 'The LearningOnline Network with CAPA';
 7330:     }
 7331:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7332:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7333: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7334:         .$inhibitprint
 7335: 	.$head_extra;
 7336:     if ($env{'browser.mobile'}) {
 7337:         $result .= '
 7338: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7339: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7340:     }
 7341:     return $result.'</head>';
 7342: }
 7343: 
 7344: =pod
 7345: 
 7346: =item * &font_settings()
 7347: 
 7348: Returns neccessary <meta> to set the proper encoding
 7349: 
 7350: Inputs: optional reference to HASH -- $args passed to &headtag()
 7351: 
 7352: =cut
 7353: 
 7354: sub font_settings {
 7355:     my ($args) = @_;
 7356:     my $headerstring='';
 7357:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7358:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7359: 	$headerstring.=
 7360: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n";
 7361:     }
 7362:     return $headerstring;
 7363: }
 7364: 
 7365: =pod
 7366: 
 7367: =item * &print_suppression()
 7368: 
 7369: In course context returns css which causes the body to be blank when media="print",
 7370: if printout generation is unavailable for the current resource.
 7371: 
 7372: This could be because:
 7373: 
 7374: (a) printstartdate is in the future
 7375: 
 7376: (b) printenddate is in the past
 7377: 
 7378: (c) there is an active exam block with "printout"
 7379: functionality blocked
 7380: 
 7381: Users with pav, pfo or evb privileges are exempt.
 7382: 
 7383: Inputs: none
 7384: 
 7385: =cut
 7386: 
 7387: 
 7388: sub print_suppression {
 7389:     my $noprint;
 7390:     if ($env{'request.course.id'}) {
 7391:         my $scope = $env{'request.course.id'};
 7392:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7393:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7394:             return;
 7395:         }
 7396:         if ($env{'request.course.sec'} ne '') {
 7397:             $scope .= "/$env{'request.course.sec'}";
 7398:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7399:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7400:                 return;
 7401:             }
 7402:         }
 7403:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7404:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7405:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7406:         if ($blocked) {
 7407:             my $checkrole = "cm./$cdom/$cnum";
 7408:             if ($env{'request.course.sec'} ne '') {
 7409:                 $checkrole .= "/$env{'request.course.sec'}";
 7410:             }
 7411:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7412:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7413:                 $noprint = 1;
 7414:             }
 7415:         }
 7416:         unless ($noprint) {
 7417:             my $symb = &Apache::lonnet::symbread();
 7418:             if ($symb ne '') {
 7419:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7420:                 if (ref($navmap)) {
 7421:                     my $res = $navmap->getBySymb($symb);
 7422:                     if (ref($res)) {
 7423:                         if (!$res->resprintable()) {
 7424:                             $noprint = 1;
 7425:                         }
 7426:                     }
 7427:                 }
 7428:             }
 7429:         }
 7430:         if ($noprint) {
 7431:             return <<"ENDSTYLE";
 7432: <style type="text/css" media="print">
 7433:     body { display:none }
 7434: </style>
 7435: ENDSTYLE
 7436:         }
 7437:     }
 7438:     return;
 7439: }
 7440: 
 7441: =pod
 7442: 
 7443: =item * &xml_begin()
 7444: 
 7445: Returns the needed doctype and <html>
 7446: 
 7447: Inputs: none
 7448: 
 7449: =cut
 7450: 
 7451: sub xml_begin {
 7452:     my $output='';
 7453: 
 7454:     if ($env{'browser.mathml'}) {
 7455: 	$output='<?xml version="1.0"?>'
 7456:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7457: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7458:             
 7459: #	    .'<!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">] >'
 7460: 	    .'<!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">'
 7461:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7462: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7463:     } else {
 7464: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n"
 7465:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7466:     }
 7467:     return $output;
 7468: }
 7469: 
 7470: =pod
 7471: 
 7472: =item * &start_page()
 7473: 
 7474: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7475: 
 7476: Inputs:
 7477: 
 7478: =over 4
 7479: 
 7480: $title - optional title for the page
 7481: 
 7482: $head_extra - optional extra HTML to incude inside the <head>
 7483: 
 7484: $args - additional optional args supported are:
 7485: 
 7486: =over 8
 7487: 
 7488:              only_body      -> is true will set &bodytag() onlybodytag
 7489:                                     arg on
 7490:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7491:              add_entries    -> additional attributes to add to the  <body>
 7492:              domain         -> force to color decorate a page for a 
 7493:                                     specific domain
 7494:              function       -> force usage of a specific rolish color
 7495:                                     scheme
 7496:              redirect       -> see &headtag()
 7497:              bgcolor        -> override the default page bg color
 7498:              js_ready       -> return a string ready for being used in 
 7499:                                     a javascript writeln
 7500:              html_encode    -> return a string ready for being used in 
 7501:                                     a html attribute
 7502:              force_register -> if is true will turn on the &bodytag()
 7503:                                     $forcereg arg
 7504:              frameset       -> if true will start with a <frameset>
 7505:                                     rather than <body>
 7506:              skip_phases    -> hash ref of 
 7507:                                     head -> skip the <html><head> generation
 7508:                                     body -> skip all <body> generation
 7509:              no_auto_mt_title -> prevent &mt()ing the title arg
 7510:              inherit_jsmath -> when creating popup window in a page,
 7511:                                     should it have jsmath forced on by the
 7512:                                     current page
 7513:              bread_crumbs ->             Array containing breadcrumbs
 7514:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7515:              group          -> includes the current group, if page is for a 
 7516:                                specific group  
 7517: 
 7518: =back
 7519: 
 7520: =back
 7521: 
 7522: =cut
 7523: 
 7524: sub start_page {
 7525:     my ($title,$head_extra,$args) = @_;
 7526:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7527: 
 7528:     $env{'internal.start_page'}++;
 7529:     my ($result,@advtools);
 7530: 
 7531:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7532:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7533:     }
 7534:     
 7535:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7536: 	if ($args->{'frameset'}) {
 7537: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7538: 						$args->{'add_entries'});
 7539: 	    $result .= "\n<frameset $attr_string>\n";
 7540:         } else {
 7541:             $result .=
 7542:                 &bodytag($title, 
 7543:                          $args->{'function'},       $args->{'add_entries'},
 7544:                          $args->{'only_body'},      $args->{'domain'},
 7545:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7546:                          $args->{'bgcolor'},        $args,
 7547:                          \@advtools);
 7548:         }
 7549:     }
 7550: 
 7551:     if ($args->{'js_ready'}) {
 7552: 		$result = &js_ready($result);
 7553:     }
 7554:     if ($args->{'html_encode'}) {
 7555: 		$result = &html_encode($result);
 7556:     }
 7557: 
 7558:     # Preparation for new and consistent functionlist at top of screen
 7559:     # if ($args->{'functionlist'}) {
 7560:     #            $result .= &build_functionlist();
 7561:     #}
 7562: 
 7563:     # Don't add anything more if only_body wanted or in const space
 7564:     return $result if    $args->{'only_body'} 
 7565:                       || $env{'request.state'} eq 'construct';
 7566: 
 7567:     #Breadcrumbs
 7568:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7569: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7570: 		#if any br links exists, add them to the breadcrumbs
 7571: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7572: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7573: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7574: 			}
 7575: 		}
 7576:                 # if @advtools array contains items add then to the breadcrumbs
 7577:                 if (@advtools > 0) {
 7578:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7579:                 }
 7580: 
 7581: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7582: 		if(exists($args->{'bread_crumbs_component'})){
 7583: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7584: 		}else{
 7585: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7586: 		}
 7587:     }
 7588:     return $result;
 7589: }
 7590: 
 7591: sub end_page {
 7592:     my ($args) = @_;
 7593:     $env{'internal.end_page'}++;
 7594:     my $result;
 7595:     if ($args->{'discussion'}) {
 7596: 	my ($target,$parser);
 7597: 	if (ref($args->{'discussion'})) {
 7598: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7599: 				$args->{'discussion'}{'parser'});
 7600: 	}
 7601: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7602:     }
 7603:     if ($args->{'frameset'}) {
 7604: 	$result .= '</frameset>';
 7605:     } else {
 7606: 	$result .= &endbodytag($args);
 7607:     }
 7608:     unless ($args->{'notbody'}) {
 7609:         $result .= "\n</html>";
 7610:     }
 7611: 
 7612:     if ($args->{'js_ready'}) {
 7613: 	$result = &js_ready($result);
 7614:     }
 7615: 
 7616:     if ($args->{'html_encode'}) {
 7617: 	$result = &html_encode($result);
 7618:     }
 7619: 
 7620:     return $result;
 7621: }
 7622: 
 7623: sub wishlist_window {
 7624:     return(<<'ENDWISHLIST');
 7625: <script type="text/javascript">
 7626: // <![CDATA[
 7627: // <!-- BEGIN LON-CAPA Internal
 7628: function set_wishlistlink(title, path) {
 7629:     if (!title) {
 7630:         title = document.title;
 7631:         title = title.replace(/^LON-CAPA /,'');
 7632:     }
 7633:     if (!path) {
 7634:         path = location.pathname;
 7635:     }
 7636:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7637:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7638: }
 7639: // END LON-CAPA Internal -->
 7640: // ]]>
 7641: </script>
 7642: ENDWISHLIST
 7643: }
 7644: 
 7645: sub modal_window {
 7646:     return(<<'ENDMODAL');
 7647: <script type="text/javascript">
 7648: // <![CDATA[
 7649: // <!-- BEGIN LON-CAPA Internal
 7650: var modalWindow = {
 7651: 	parent:"body",
 7652: 	windowId:null,
 7653: 	content:null,
 7654: 	width:null,
 7655: 	height:null,
 7656: 	close:function()
 7657: 	{
 7658: 	        $(".LCmodal-window").remove();
 7659: 	        $(".LCmodal-overlay").remove();
 7660: 	},
 7661: 	open:function()
 7662: 	{
 7663: 		var modal = "";
 7664: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7665: 		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;\">";
 7666: 		modal += this.content;
 7667: 		modal += "</div>";	
 7668: 
 7669: 		$(this.parent).append(modal);
 7670: 
 7671: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7672: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7673: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7674: 	}
 7675: };
 7676: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7677: 	{
 7678: 		modalWindow.windowId = "myModal";
 7679: 		modalWindow.width = width;
 7680: 		modalWindow.height = height;
 7681: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
 7682: 		modalWindow.open();
 7683: 	};	
 7684: // END LON-CAPA Internal -->
 7685: // ]]>
 7686: </script>
 7687: ENDMODAL
 7688: }
 7689: 
 7690: sub modal_link {
 7691:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7692:     unless ($width) { $width=480; }
 7693:     unless ($height) { $height=400; }
 7694:     unless ($scrolling) { $scrolling='yes'; }
 7695:     unless ($transparency) { $transparency='true'; }
 7696: 
 7697:     my $target_attr;
 7698:     if (defined($target)) {
 7699:         $target_attr = 'target="'.$target.'"';
 7700:     }
 7701:     return <<"ENDLINK";
 7702: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7703:            $linktext</a>
 7704: ENDLINK
 7705: }
 7706: 
 7707: sub modal_adhoc_script {
 7708:     my ($funcname,$width,$height,$content)=@_;
 7709:     return (<<ENDADHOC);
 7710: <script type="text/javascript">
 7711: // <![CDATA[
 7712:         var $funcname = function()
 7713:         {
 7714:                 modalWindow.windowId = "myModal";
 7715:                 modalWindow.width = $width;
 7716:                 modalWindow.height = $height;
 7717:                 modalWindow.content = '$content';
 7718:                 modalWindow.open();
 7719:         };  
 7720: // ]]>
 7721: </script>
 7722: ENDADHOC
 7723: }
 7724: 
 7725: sub modal_adhoc_inner {
 7726:     my ($funcname,$width,$height,$content)=@_;
 7727:     my $innerwidth=$width-20;
 7728:     $content=&js_ready(
 7729:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7730:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7731:                  $content.
 7732:                  &end_scrollbox().
 7733:                  &end_page()
 7734:              );
 7735:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7736: }
 7737: 
 7738: sub modal_adhoc_window {
 7739:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7740:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7741:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7742: }
 7743: 
 7744: sub modal_adhoc_launch {
 7745:     my ($funcname,$width,$height,$content)=@_;
 7746:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7747: <script type="text/javascript">
 7748: // <![CDATA[
 7749: $funcname();
 7750: // ]]>
 7751: </script>
 7752: ENDLAUNCH
 7753: }
 7754: 
 7755: sub modal_adhoc_close {
 7756:     return (<<ENDCLOSE);
 7757: <script type="text/javascript">
 7758: // <![CDATA[
 7759: modalWindow.close();
 7760: // ]]>
 7761: </script>
 7762: ENDCLOSE
 7763: }
 7764: 
 7765: sub togglebox_script {
 7766:    return(<<ENDTOGGLE);
 7767: <script type="text/javascript"> 
 7768: // <![CDATA[
 7769: function LCtoggleDisplay(id,hidetext,showtext) {
 7770:    link = document.getElementById(id + "link").childNodes[0];
 7771:    with (document.getElementById(id).style) {
 7772:       if (display == "none" ) {
 7773:           display = "inline";
 7774:           link.nodeValue = hidetext;
 7775:         } else {
 7776:           display = "none";
 7777:           link.nodeValue = showtext;
 7778:        }
 7779:    }
 7780: }
 7781: // ]]>
 7782: </script>
 7783: ENDTOGGLE
 7784: }
 7785: 
 7786: sub start_togglebox {
 7787:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7788:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7789:     unless ($showtext) { $showtext=&mt('show'); }
 7790:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7791:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7792:     return &start_data_table().
 7793:            &start_data_table_header_row().
 7794:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7795:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7796:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7797:            &end_data_table_header_row().
 7798:            '<tr id="'.$id.'" style="display:none""><td>';
 7799: }
 7800: 
 7801: sub end_togglebox {
 7802:     return '</td></tr>'.&end_data_table();
 7803: }
 7804: 
 7805: sub LCprogressbar_script {
 7806:    my ($id)=@_;
 7807:    return(<<ENDPROGRESS);
 7808: <script type="text/javascript">
 7809: // <![CDATA[
 7810: \$('#progressbar$id').progressbar({
 7811:   value: 0,
 7812:   change: function(event, ui) {
 7813:     var newVal = \$(this).progressbar('option', 'value');
 7814:     \$('.pblabel', this).text(LCprogressTxt);
 7815:   }
 7816: });
 7817: // ]]>
 7818: </script>
 7819: ENDPROGRESS
 7820: }
 7821: 
 7822: sub LCprogressbarUpdate_script {
 7823:    return(<<ENDPROGRESSUPDATE);
 7824: <style type="text/css">
 7825: .ui-progressbar { position:relative; }
 7826: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7827: </style>
 7828: <script type="text/javascript">
 7829: // <![CDATA[
 7830: var LCprogressTxt='---';
 7831: 
 7832: function LCupdateProgress(percent,progresstext,id) {
 7833:    LCprogressTxt=progresstext;
 7834:    \$('#progressbar'+id).progressbar('value',percent);
 7835: }
 7836: // ]]>
 7837: </script>
 7838: ENDPROGRESSUPDATE
 7839: }
 7840: 
 7841: my $LClastpercent;
 7842: my $LCidcnt;
 7843: my $LCcurrentid;
 7844: 
 7845: sub LCprogressbar {
 7846:     my ($r)=(@_);
 7847:     $LClastpercent=0;
 7848:     $LCidcnt++;
 7849:     $LCcurrentid=$$.'_'.$LCidcnt;
 7850:     my $starting=&mt('Starting');
 7851:     my $content=(<<ENDPROGBAR);
 7852:   <div id="progressbar$LCcurrentid">
 7853:     <span class="pblabel">$starting</span>
 7854:   </div>
 7855: ENDPROGBAR
 7856:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7857: }
 7858: 
 7859: sub LCprogressbarUpdate {
 7860:     my ($r,$val,$text)=@_;
 7861:     unless ($val) { 
 7862:        if ($LClastpercent) {
 7863:            $val=$LClastpercent;
 7864:        } else {
 7865:            $val=0;
 7866:        }
 7867:     }
 7868:     if ($val<0) { $val=0; }
 7869:     if ($val>100) { $val=0; }
 7870:     $LClastpercent=$val;
 7871:     unless ($text) { $text=$val.'%'; }
 7872:     $text=&js_ready($text);
 7873:     &r_print($r,<<ENDUPDATE);
 7874: <script type="text/javascript">
 7875: // <![CDATA[
 7876: LCupdateProgress($val,'$text','$LCcurrentid');
 7877: // ]]>
 7878: </script>
 7879: ENDUPDATE
 7880: }
 7881: 
 7882: sub LCprogressbarClose {
 7883:     my ($r)=@_;
 7884:     $LClastpercent=0;
 7885:     &r_print($r,<<ENDCLOSE);
 7886: <script type="text/javascript">
 7887: // <![CDATA[
 7888: \$("#progressbar$LCcurrentid").hide('slow'); 
 7889: // ]]>
 7890: </script>
 7891: ENDCLOSE
 7892: }
 7893: 
 7894: sub r_print {
 7895:     my ($r,$to_print)=@_;
 7896:     if ($r) {
 7897:       $r->print($to_print);
 7898:       $r->rflush();
 7899:     } else {
 7900:       print($to_print);
 7901:     }
 7902: }
 7903: 
 7904: sub html_encode {
 7905:     my ($result) = @_;
 7906: 
 7907:     $result = &HTML::Entities::encode($result,'<>&"');
 7908:     
 7909:     return $result;
 7910: }
 7911: 
 7912: sub js_ready {
 7913:     my ($result) = @_;
 7914: 
 7915:     $result =~ s/[\n\r]/ /xmsg;
 7916:     $result =~ s/\\/\\\\/xmsg;
 7917:     $result =~ s/'/\\'/xmsg;
 7918:     $result =~ s{</}{<\\/}xmsg;
 7919:     
 7920:     return $result;
 7921: }
 7922: 
 7923: sub validate_page {
 7924:     if (  exists($env{'internal.start_page'})
 7925: 	  &&     $env{'internal.start_page'} > 1) {
 7926: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7927: 				 $env{'internal.start_page'}.' '.
 7928: 				 $ENV{'request.filename'});
 7929:     }
 7930:     if (  exists($env{'internal.end_page'})
 7931: 	  &&     $env{'internal.end_page'} > 1) {
 7932: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7933: 				 $env{'internal.end_page'}.' '.
 7934: 				 $env{'request.filename'});
 7935:     }
 7936:     if (     exists($env{'internal.start_page'})
 7937: 	&& ! exists($env{'internal.end_page'})) {
 7938: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7939: 				 $env{'request.filename'});
 7940:     }
 7941:     if (   ! exists($env{'internal.start_page'})
 7942: 	&&   exists($env{'internal.end_page'})) {
 7943: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7944: 				 $env{'request.filename'});
 7945:     }
 7946: }
 7947: 
 7948: 
 7949: sub start_scrollbox {
 7950:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 7951:     unless ($outerwidth) { $outerwidth='520px'; }
 7952:     unless ($width) { $width='500px'; }
 7953:     unless ($height) { $height='200px'; }
 7954:     my ($table_id,$div_id,$tdcol);
 7955:     if ($id ne '') {
 7956:         $table_id = ' id="table_'.$id.'"';
 7957:         $div_id = ' id="div_'.$id.'"';
 7958:     }
 7959:     if ($bgcolor ne '') {
 7960:         $tdcol = "background-color: $bgcolor;";
 7961:     }
 7962:     my $nicescroll_js;
 7963:     if ($env{'browser.mobile'}) {
 7964:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 7965:     }
 7966:     return <<"END";
 7967: $nicescroll_js
 7968: 
 7969: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 7970: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 7971: END
 7972: }
 7973: 
 7974: sub end_scrollbox {
 7975:     return '</div></td></tr></table>';
 7976: }
 7977: 
 7978: sub nicescroll_javascript {
 7979:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 7980:     my %options;
 7981:     if (ref($cursor) eq 'HASH') {
 7982:         %options = %{$cursor};
 7983:     }
 7984:     unless ($options{'railalign'} =~ /^left|right$/) {
 7985:         $options{'railalign'} = 'left';
 7986:     }
 7987:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7988:         my $function  = &get_users_function();
 7989:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 7990:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7991:             $options{'cursorcolor'} = '#00F';
 7992:         }
 7993:     }
 7994:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 7995:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 7996:             $options{'cursoropacity'}='1.0';
 7997:         }
 7998:     } else {
 7999:         $options{'cursoropacity'}='1.0';
 8000:     }
 8001:     if ($options{'cursorfixedheight'} eq 'none') {
 8002:         delete($options{'cursorfixedheight'});
 8003:     } else {
 8004:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8005:     }
 8006:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8007:         delete($options{'railoffset'});
 8008:     }
 8009:     my @niceoptions;
 8010:     while (my($key,$value) = each(%options)) {
 8011:         if ($value =~ /^\{.+\}$/) {
 8012:             push(@niceoptions,$key.':'.$value);
 8013:         } else {
 8014:             push(@niceoptions,$key.':"'.$value.'"');
 8015:         }
 8016:     }
 8017:     my $nicescroll_js = '
 8018: $(document).ready(
 8019:       function() {
 8020:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8021:       }
 8022: );
 8023: ';
 8024:     if ($framecheck) {
 8025:         $nicescroll_js .= '
 8026: function expand_div(caller) {
 8027:     if (top === self) {
 8028:         document.getElementById("'.$id.'").style.width = "auto";
 8029:         document.getElementById("'.$id.'").style.height = "auto";
 8030:     } else {
 8031:         try {
 8032:             if (parent.frames) {
 8033:                 if (parent.frames.length > 1) {
 8034:                     var framesrc = parent.frames[1].location.href;
 8035:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8036:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8037:                         document.getElementById("'.$id.'").style.width = "auto";
 8038:                         document.getElementById("'.$id.'").style.height = "auto";
 8039:                     }
 8040:                 }
 8041:             }
 8042:         } catch (e) {
 8043:             return;
 8044:         }
 8045:     }
 8046:     return;
 8047: }
 8048: ';
 8049:     }
 8050:     if ($needjsready) {
 8051:         $nicescroll_js = '
 8052: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8053:     } else {
 8054:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8055:     }
 8056:     return $nicescroll_js;
 8057: }
 8058: 
 8059: sub simple_error_page {
 8060:     my ($r,$title,$msg,$args) = @_;
 8061:     if (ref($args) eq 'HASH') {
 8062:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8063:     } else {
 8064:         $msg = &mt($msg);
 8065:     }
 8066: 
 8067:     my $page =
 8068: 	&Apache::loncommon::start_page($title).
 8069: 	'<p class="LC_error">'.$msg.'</p>'.
 8070: 	&Apache::loncommon::end_page();
 8071:     if (ref($r)) {
 8072: 	$r->print($page);
 8073: 	return;
 8074:     }
 8075:     return $page;
 8076: }
 8077: 
 8078: {
 8079:     my @row_count;
 8080: 
 8081:     sub start_data_table_count {
 8082:         unshift(@row_count, 0);
 8083:         return;
 8084:     }
 8085: 
 8086:     sub end_data_table_count {
 8087:         shift(@row_count);
 8088:         return;
 8089:     }
 8090: 
 8091:     sub start_data_table {
 8092: 	my ($add_class,$id) = @_;
 8093: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8094:         my $table_id;
 8095:         if (defined($id)) {
 8096:             $table_id = ' id="'.$id.'"';
 8097:         }
 8098: 	&start_data_table_count();
 8099: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8100:     }
 8101: 
 8102:     sub end_data_table {
 8103: 	&end_data_table_count();
 8104: 	return '</table>'."\n";;
 8105:     }
 8106: 
 8107:     sub start_data_table_row {
 8108: 	my ($add_class, $id) = @_;
 8109: 	$row_count[0]++;
 8110: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8111: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8112:         $id = (' id="'.$id.'"') unless ($id eq '');
 8113:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8114:     }
 8115:     
 8116:     sub continue_data_table_row {
 8117: 	my ($add_class, $id) = @_;
 8118: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8119: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8120:         $id = (' id="'.$id.'"') unless ($id eq '');
 8121:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8122:     }
 8123: 
 8124:     sub end_data_table_row {
 8125: 	return '</tr>'."\n";;
 8126:     }
 8127: 
 8128:     sub start_data_table_empty_row {
 8129: #	$row_count[0]++;
 8130: 	return  '<tr class="LC_empty_row" >'."\n";;
 8131:     }
 8132: 
 8133:     sub end_data_table_empty_row {
 8134: 	return '</tr>'."\n";;
 8135:     }
 8136: 
 8137:     sub start_data_table_header_row {
 8138: 	return  '<tr class="LC_header_row">'."\n";;
 8139:     }
 8140: 
 8141:     sub end_data_table_header_row {
 8142: 	return '</tr>'."\n";;
 8143:     }
 8144: 
 8145:     sub data_table_caption {
 8146:         my $caption = shift;
 8147:         return "<caption class=\"LC_caption\">$caption</caption>";
 8148:     }
 8149: }
 8150: 
 8151: =pod
 8152: 
 8153: =item * &inhibit_menu_check($arg)
 8154: 
 8155: Checks for a inhibitmenu state and generates output to preserve it
 8156: 
 8157: Inputs:         $arg - can be any of
 8158:                      - undef - in which case the return value is a string 
 8159:                                to add  into arguments list of a uri
 8160:                      - 'input' - in which case the return value is a HTML
 8161:                                  <form> <input> field of type hidden to
 8162:                                  preserve the value
 8163:                      - a url - in which case the return value is the url with
 8164:                                the neccesary cgi args added to preserve the
 8165:                                inhibitmenu state
 8166:                      - a ref to a url - no return value, but the string is
 8167:                                         updated to include the neccessary cgi
 8168:                                         args to preserve the inhibitmenu state
 8169: 
 8170: =cut
 8171: 
 8172: sub inhibit_menu_check {
 8173:     my ($arg) = @_;
 8174:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8175:     if ($arg eq 'input') {
 8176: 	if ($env{'form.inhibitmenu'}) {
 8177: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8178: 	} else {
 8179: 	    return
 8180: 	}
 8181:     }
 8182:     if ($env{'form.inhibitmenu'}) {
 8183: 	if (ref($arg)) {
 8184: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8185: 	} elsif ($arg eq '') {
 8186: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8187: 	} else {
 8188: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8189: 	}
 8190:     }
 8191:     if (!ref($arg)) {
 8192: 	return $arg;
 8193:     }
 8194: }
 8195: 
 8196: ###############################################
 8197: 
 8198: =pod
 8199: 
 8200: =back
 8201: 
 8202: =head1 User Information Routines
 8203: 
 8204: =over 4
 8205: 
 8206: =item * &get_users_function()
 8207: 
 8208: Used by &bodytag to determine the current users primary role.
 8209: Returns either 'student','coordinator','admin', or 'author'.
 8210: 
 8211: =cut
 8212: 
 8213: ###############################################
 8214: sub get_users_function {
 8215:     my $function = 'norole';
 8216:     if ($env{'request.role'}=~/^(st)/) {
 8217:         $function='student';
 8218:     }
 8219:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8220:         $function='coordinator';
 8221:     }
 8222:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8223:         $function='admin';
 8224:     }
 8225:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8226:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8227:         $function='author';
 8228:     }
 8229:     return $function;
 8230: }
 8231: 
 8232: ###############################################
 8233: 
 8234: =pod
 8235: 
 8236: =item * &show_course()
 8237: 
 8238: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8239: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8240: 
 8241: Inputs:
 8242: None
 8243: 
 8244: Outputs:
 8245: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8246: 
 8247: =cut
 8248: 
 8249: ###############################################
 8250: sub show_course {
 8251:     my $course = !$env{'user.adv'};
 8252:     if (!$env{'user.adv'}) {
 8253:         foreach my $env (keys(%env)) {
 8254:             next if ($env !~ m/^user\.priv\./);
 8255:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8256:                 $course = 0;
 8257:                 last;
 8258:             }
 8259:         }
 8260:     }
 8261:     return $course;
 8262: }
 8263: 
 8264: ###############################################
 8265: 
 8266: =pod
 8267: 
 8268: =item * &check_user_status()
 8269: 
 8270: Determines current status of supplied role for a
 8271: specific user. Roles can be active, previous or future.
 8272: 
 8273: Inputs: 
 8274: user's domain, user's username, course's domain,
 8275: course's number, optional section ID.
 8276: 
 8277: Outputs:
 8278: role status: active, previous or future. 
 8279: 
 8280: =cut
 8281: 
 8282: sub check_user_status {
 8283:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8284:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8285:     my @uroles = keys %userinfo;
 8286:     my $srchstr;
 8287:     my $active_chk = 'none';
 8288:     my $now = time;
 8289:     if (@uroles > 0) {
 8290:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8291:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8292:         } else {
 8293:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8294:         }
 8295:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8296:             my $role_end = 0;
 8297:             my $role_start = 0;
 8298:             $active_chk = 'active';
 8299:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8300:                 $role_end = $1;
 8301:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8302:                     $role_start = $1;
 8303:                 }
 8304:             }
 8305:             if ($role_start > 0) {
 8306:                 if ($now < $role_start) {
 8307:                     $active_chk = 'future';
 8308:                 }
 8309:             }
 8310:             if ($role_end > 0) {
 8311:                 if ($now > $role_end) {
 8312:                     $active_chk = 'previous';
 8313:                 }
 8314:             }
 8315:         }
 8316:     }
 8317:     return $active_chk;
 8318: }
 8319: 
 8320: ###############################################
 8321: 
 8322: =pod
 8323: 
 8324: =item * &get_sections()
 8325: 
 8326: Determines all the sections for a course including
 8327: sections with students and sections containing other roles.
 8328: Incoming parameters: 
 8329: 
 8330: 1. domain
 8331: 2. course number 
 8332: 3. reference to array containing roles for which sections should 
 8333: be gathered (optional).
 8334: 4. reference to array containing status types for which sections 
 8335: should be gathered (optional).
 8336: 
 8337: If the third argument is undefined, sections are gathered for any role. 
 8338: If the fourth argument is undefined, sections are gathered for any status.
 8339: Permissible values are 'active' or 'future' or 'previous'.
 8340:  
 8341: Returns section hash (keys are section IDs, values are
 8342: number of users in each section), subject to the
 8343: optional roles filter, optional status filter 
 8344: 
 8345: =cut
 8346: 
 8347: ###############################################
 8348: sub get_sections {
 8349:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8350:     if (!defined($cdom) || !defined($cnum)) {
 8351:         my $cid =  $env{'request.course.id'};
 8352: 
 8353: 	return if (!defined($cid));
 8354: 
 8355:         $cdom = $env{'course.'.$cid.'.domain'};
 8356:         $cnum = $env{'course.'.$cid.'.num'};
 8357:     }
 8358: 
 8359:     my %sectioncount;
 8360:     my $now = time;
 8361: 
 8362:     my $check_students = 1;
 8363:     my $only_students = 0;
 8364:     if (ref($possible_roles) eq 'ARRAY') {
 8365:         if (grep(/^st$/,@{$possible_roles})) {
 8366:             if (@{$possible_roles} == 1) {
 8367:                 $only_students = 1;
 8368:             }
 8369:         } else {
 8370:             $check_students = 0;
 8371:         }
 8372:     }
 8373: 
 8374:     if ($check_students) { 
 8375: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8376: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8377: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8378:         my $start_index = &Apache::loncoursedata::CL_START();
 8379:         my $end_index = &Apache::loncoursedata::CL_END();
 8380:         my $status;
 8381: 	while (my ($student,$data) = each(%$classlist)) {
 8382: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8383: 				                     $data->[$status_index],
 8384:                                                      $data->[$start_index],
 8385:                                                      $data->[$end_index]);
 8386:             if ($stu_status eq 'Active') {
 8387:                 $status = 'active';
 8388:             } elsif ($end < $now) {
 8389:                 $status = 'previous';
 8390:             } elsif ($start > $now) {
 8391:                 $status = 'future';
 8392:             } 
 8393: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8394:                 if ((!defined($possible_status)) || (($status ne '') && 
 8395:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8396: 		    $sectioncount{$section}++;
 8397:                 }
 8398: 	    }
 8399: 	}
 8400:     }
 8401:     if ($only_students) {
 8402:         return %sectioncount;
 8403:     }
 8404:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8405:     foreach my $user (sort(keys(%courseroles))) {
 8406: 	if ($user !~ /^(\w{2})/) { next; }
 8407: 	my ($role) = ($user =~ /^(\w{2})/);
 8408: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8409: 	my ($section,$status);
 8410: 	if ($role eq 'cr' &&
 8411: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8412: 	    $section=$1;
 8413: 	}
 8414: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8415: 	if (!defined($section) || $section eq '-1') { next; }
 8416:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8417:         if ($end == -1 && $start == -1) {
 8418:             next; #deleted role
 8419:         }
 8420:         if (!defined($possible_status)) { 
 8421:             $sectioncount{$section}++;
 8422:         } else {
 8423:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8424:                 $status = 'active';
 8425:             } elsif ($end < $now) {
 8426:                 $status = 'future';
 8427:             } elsif ($start > $now) {
 8428:                 $status = 'previous';
 8429:             }
 8430:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8431:                 $sectioncount{$section}++;
 8432:             }
 8433:         }
 8434:     }
 8435:     return %sectioncount;
 8436: }
 8437: 
 8438: ###############################################
 8439: 
 8440: =pod
 8441: 
 8442: =item * &get_course_users()
 8443: 
 8444: Retrieves usernames:domains for users in the specified course
 8445: with specific role(s), and access status. 
 8446: 
 8447: Incoming parameters:
 8448: 1. course domain
 8449: 2. course number
 8450: 3. access status: users must have - either active, 
 8451: previous, future, or all.
 8452: 4. reference to array of permissible roles
 8453: 5. reference to array of section restrictions (optional)
 8454: 6. reference to results object (hash of hashes).
 8455: 7. reference to optional userdata hash
 8456: 8. reference to optional statushash
 8457: 9. flag if privileged users (except those set to unhide in
 8458:    course settings) should be excluded    
 8459: Keys of top level results hash are roles.
 8460: Keys of inner hashes are username:domain, with 
 8461: values set to access type.
 8462: Optional userdata hash returns an array with arguments in the 
 8463: same order as loncoursedata::get_classlist() for student data.
 8464: 
 8465: Optional statushash returns
 8466: 
 8467: Entries for end, start, section and status are blank because
 8468: of the possibility of multiple values for non-student roles.
 8469: 
 8470: =cut
 8471: 
 8472: ###############################################
 8473: 
 8474: sub get_course_users {
 8475:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8476:     my %idx = ();
 8477:     my %seclists;
 8478: 
 8479:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8480:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8481:     $idx{end} = &Apache::loncoursedata::CL_END();
 8482:     $idx{start} = &Apache::loncoursedata::CL_START();
 8483:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8484:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8485:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8486:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8487: 
 8488:     if (grep(/^st$/,@{$roles})) {
 8489:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8490:         my $now = time;
 8491:         foreach my $student (keys(%{$classlist})) {
 8492:             my $match = 0;
 8493:             my $secmatch = 0;
 8494:             my $section = $$classlist{$student}[$idx{section}];
 8495:             my $status = $$classlist{$student}[$idx{status}];
 8496:             if ($section eq '') {
 8497:                 $section = 'none';
 8498:             }
 8499:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8500:                 if (grep(/^all$/,@{$sections})) {
 8501:                     $secmatch = 1;
 8502:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8503:                     if (grep(/^none$/,@{$sections})) {
 8504:                         $secmatch = 1;
 8505:                     }
 8506:                 } else {  
 8507: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8508: 		        $secmatch = 1;
 8509:                     }
 8510: 		}
 8511:                 if (!$secmatch) {
 8512:                     next;
 8513:                 }
 8514:             }
 8515:             if (defined($$types{'active'})) {
 8516:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8517:                     push(@{$$users{st}{$student}},'active');
 8518:                     $match = 1;
 8519:                 }
 8520:             }
 8521:             if (defined($$types{'previous'})) {
 8522:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8523:                     push(@{$$users{st}{$student}},'previous');
 8524:                     $match = 1;
 8525:                 }
 8526:             }
 8527:             if (defined($$types{'future'})) {
 8528:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8529:                     push(@{$$users{st}{$student}},'future');
 8530:                     $match = 1;
 8531:                 }
 8532:             }
 8533:             if ($match) {
 8534:                 push(@{$seclists{$student}},$section);
 8535:                 if (ref($userdata) eq 'HASH') {
 8536:                     $$userdata{$student} = $$classlist{$student};
 8537:                 }
 8538:                 if (ref($statushash) eq 'HASH') {
 8539:                     $statushash->{$student}{'st'}{$section} = $status;
 8540:                 }
 8541:             }
 8542:         }
 8543:     }
 8544:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8545:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8546:         my $now = time;
 8547:         my %displaystatus = ( previous => 'Expired',
 8548:                               active   => 'Active',
 8549:                               future   => 'Future',
 8550:                             );
 8551:         my (%nothide,@possdoms);
 8552:         if ($hidepriv) {
 8553:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8554:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8555:                 if ($user !~ /:/) {
 8556:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8557:                 } else {
 8558:                     $nothide{$user} = 1;
 8559:                 }
 8560:             }
 8561:             my @possdoms = ($cdom);
 8562:             if ($coursehash{'checkforpriv'}) {
 8563:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8564:             }
 8565:         }
 8566:         foreach my $person (sort(keys(%coursepersonnel))) {
 8567:             my $match = 0;
 8568:             my $secmatch = 0;
 8569:             my $status;
 8570:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8571:             $user =~ s/:$//;
 8572:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8573:             if ($end == -1 || $start == -1) {
 8574:                 next;
 8575:             }
 8576:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8577:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8578:                 my ($uname,$udom) = split(/:/,$user);
 8579:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8580:                     if (grep(/^all$/,@{$sections})) {
 8581:                         $secmatch = 1;
 8582:                     } elsif ($usec eq '') {
 8583:                         if (grep(/^none$/,@{$sections})) {
 8584:                             $secmatch = 1;
 8585:                         }
 8586:                     } else {
 8587:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8588:                             $secmatch = 1;
 8589:                         }
 8590:                     }
 8591:                     if (!$secmatch) {
 8592:                         next;
 8593:                     }
 8594:                 }
 8595:                 if ($usec eq '') {
 8596:                     $usec = 'none';
 8597:                 }
 8598:                 if ($uname ne '' && $udom ne '') {
 8599:                     if ($hidepriv) {
 8600:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8601:                             (!$nothide{$uname.':'.$udom})) {
 8602:                             next;
 8603:                         }
 8604:                     }
 8605:                     if ($end > 0 && $end < $now) {
 8606:                         $status = 'previous';
 8607:                     } elsif ($start > $now) {
 8608:                         $status = 'future';
 8609:                     } else {
 8610:                         $status = 'active';
 8611:                     }
 8612:                     foreach my $type (keys(%{$types})) { 
 8613:                         if ($status eq $type) {
 8614:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8615:                                 push(@{$$users{$role}{$user}},$type);
 8616:                             }
 8617:                             $match = 1;
 8618:                         }
 8619:                     }
 8620:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8621:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8622: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8623:                         }
 8624:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8625:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8626:                         }
 8627:                         if (ref($statushash) eq 'HASH') {
 8628:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8629:                         }
 8630:                     }
 8631:                 }
 8632:             }
 8633:         }
 8634:         if (grep(/^ow$/,@{$roles})) {
 8635:             if ((defined($cdom)) && (defined($cnum))) {
 8636:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8637:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8638:                     my $owner = $csettings{'internal.courseowner'};
 8639:                     next if ($owner eq '');
 8640:                     my ($ownername,$ownerdom);
 8641:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8642:                         $ownername = $1;
 8643:                         $ownerdom = $2;
 8644:                     } else {
 8645:                         $ownername = $owner;
 8646:                         $ownerdom = $cdom;
 8647:                         $owner = $ownername.':'.$ownerdom;
 8648:                     }
 8649:                     @{$$users{'ow'}{$owner}} = 'any';
 8650:                     if (defined($userdata) && 
 8651: 			!exists($$userdata{$owner})) {
 8652: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8653:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8654:                             push(@{$seclists{$owner}},'none');
 8655:                         }
 8656:                         if (ref($statushash) eq 'HASH') {
 8657:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8658:                         }
 8659: 		    }
 8660:                 }
 8661:             }
 8662:         }
 8663:         foreach my $user (keys(%seclists)) {
 8664:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8665:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8666:         }
 8667:     }
 8668:     return;
 8669: }
 8670: 
 8671: sub get_user_info {
 8672:     my ($udom,$uname,$idx,$userdata) = @_;
 8673:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8674: 	&plainname($uname,$udom,'lastname');
 8675:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8676:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8677:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8678:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8679:     return;
 8680: }
 8681: 
 8682: ###############################################
 8683: 
 8684: =pod
 8685: 
 8686: =item * &get_user_quota()
 8687: 
 8688: Retrieves quota assigned for storage of user files.
 8689: Default is to report quota for portfolio files.
 8690: 
 8691: Incoming parameters:
 8692: 1. user's username
 8693: 2. user's domain
 8694: 3. quota name - portfolio, author, or course
 8695:    (if no quota name provided, defaults to portfolio).
 8696: 4. crstype - official, unofficial or community, if quota name is
 8697:    course
 8698: 
 8699: Returns:
 8700: 1. Disk quota (in MB) assigned to student.
 8701: 2. (Optional) Type of setting: custom or default
 8702:    (individually assigned or default for user's 
 8703:    institutional status).
 8704: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8705:    or student - types as defined in localenroll::inst_usertypes 
 8706:    for user's domain, which determines default quota for user.
 8707: 4. (Optional) - Default quota which would apply to the user.
 8708: 
 8709: If a value has been stored in the user's environment, 
 8710: it will return that, otherwise it returns the maximal default
 8711: defined for the user's institutional status(es) in the domain.
 8712: 
 8713: =cut
 8714: 
 8715: ###############################################
 8716: 
 8717: 
 8718: sub get_user_quota {
 8719:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8720:     my ($quota,$quotatype,$settingstatus,$defquota);
 8721:     if (!defined($udom)) {
 8722:         $udom = $env{'user.domain'};
 8723:     }
 8724:     if (!defined($uname)) {
 8725:         $uname = $env{'user.name'};
 8726:     }
 8727:     if (($udom eq '' || $uname eq '') ||
 8728:         ($udom eq 'public') && ($uname eq 'public')) {
 8729:         $quota = 0;
 8730:         $quotatype = 'default';
 8731:         $defquota = 0; 
 8732:     } else {
 8733:         my $inststatus;
 8734:         if ($quotaname eq 'course') {
 8735:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8736:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8737:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8738:             } else {
 8739:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8740:                 $quota = $cenv{'internal.uploadquota'};
 8741:             }
 8742:         } else {
 8743:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8744:                 if ($quotaname eq 'author') {
 8745:                     $quota = $env{'environment.authorquota'};
 8746:                 } else {
 8747:                     $quota = $env{'environment.portfolioquota'};
 8748:                 }
 8749:                 $inststatus = $env{'environment.inststatus'};
 8750:             } else {
 8751:                 my %userenv = 
 8752:                     &Apache::lonnet::get('environment',['portfolioquota',
 8753:                                          'authorquota','inststatus'],$udom,$uname);
 8754:                 my ($tmp) = keys(%userenv);
 8755:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8756:                     if ($quotaname eq 'author') {
 8757:                         $quota = $userenv{'authorquota'};
 8758:                     } else {
 8759:                         $quota = $userenv{'portfolioquota'};
 8760:                     }
 8761:                     $inststatus = $userenv{'inststatus'};
 8762:                 } else {
 8763:                     undef(%userenv);
 8764:                 }
 8765:             }
 8766:         }
 8767:         if ($quota eq '' || wantarray) {
 8768:             if ($quotaname eq 'course') {
 8769:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8770:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || ($crstype eq 'community')) { 
 8771:                     $defquota = $domdefs{$crstype.'quota'};
 8772:                 }
 8773:                 if ($defquota eq '') {
 8774:                     $defquota = 500;
 8775:                 }
 8776:             } else {
 8777:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8778:             }
 8779:             if ($quota eq '') {
 8780:                 $quota = $defquota;
 8781:                 $quotatype = 'default';
 8782:             } else {
 8783:                 $quotatype = 'custom';
 8784:             }
 8785:         }
 8786:     }
 8787:     if (wantarray) {
 8788:         return ($quota,$quotatype,$settingstatus,$defquota);
 8789:     } else {
 8790:         return $quota;
 8791:     }
 8792: }
 8793: 
 8794: ###############################################
 8795: 
 8796: =pod
 8797: 
 8798: =item * &default_quota()
 8799: 
 8800: Retrieves default quota assigned for storage of user portfolio files,
 8801: given an (optional) user's institutional status.
 8802: 
 8803: Incoming parameters:
 8804: 
 8805: 1. domain
 8806: 2. (Optional) institutional status(es).  This is a : separated list of 
 8807:    status types (e.g., faculty, staff, student etc.)
 8808:    which apply to the user for whom the default is being retrieved.
 8809:    If the institutional status string in undefined, the domain
 8810:    default quota will be returned.
 8811: 3.  quota name - portfolio, author, or course
 8812:    (if no quota name provided, defaults to portfolio).
 8813: 
 8814: Returns:
 8815: 
 8816: 1. Default disk quota (in MB) for user portfolios in the domain.
 8817: 2. (Optional) institutional type which determined the value of the
 8818:    default quota.
 8819: 
 8820: If a value has been stored in the domain's configuration db,
 8821: it will return that, otherwise it returns 20 (for backwards 
 8822: compatibility with domains which have not set up a configuration
 8823: db file; the original statically defined portfolio quota was 20 MB). 
 8824: 
 8825: If the user's status includes multiple types (e.g., staff and student),
 8826: the largest default quota which applies to the user determines the
 8827: default quota returned.
 8828: 
 8829: =cut
 8830: 
 8831: ###############################################
 8832: 
 8833: 
 8834: sub default_quota {
 8835:     my ($udom,$inststatus,$quotaname) = @_;
 8836:     my ($defquota,$settingstatus);
 8837:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8838:                                             ['quotas'],$udom);
 8839:     my $key = 'defaultquota';
 8840:     if ($quotaname eq 'author') {
 8841:         $key = 'authorquota';
 8842:     }
 8843:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8844:         if ($inststatus ne '') {
 8845:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8846:             foreach my $item (@statuses) {
 8847:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8848:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 8849:                         if ($defquota eq '') {
 8850:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8851:                             $settingstatus = $item;
 8852:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 8853:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8854:                             $settingstatus = $item;
 8855:                         }
 8856:                     }
 8857:                 } elsif ($key eq 'defaultquota') {
 8858:                     if ($quotahash{'quotas'}{$item} ne '') {
 8859:                         if ($defquota eq '') {
 8860:                             $defquota = $quotahash{'quotas'}{$item};
 8861:                             $settingstatus = $item;
 8862:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8863:                             $defquota = $quotahash{'quotas'}{$item};
 8864:                             $settingstatus = $item;
 8865:                         }
 8866:                     }
 8867:                 }
 8868:             }
 8869:         }
 8870:         if ($defquota eq '') {
 8871:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8872:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 8873:             } elsif ($key eq 'defaultquota') {
 8874:                 $defquota = $quotahash{'quotas'}{'default'};
 8875:             }
 8876:             $settingstatus = 'default';
 8877:             if ($defquota eq '') {
 8878:                 if ($quotaname eq 'author') {
 8879:                     $defquota = 500;
 8880:                 }
 8881:             }
 8882:         }
 8883:     } else {
 8884:         $settingstatus = 'default';
 8885:         if ($quotaname eq 'author') {
 8886:             $defquota = 500;
 8887:         } else {
 8888:             $defquota = 20;
 8889:         }
 8890:     }
 8891:     if (wantarray) {
 8892:         return ($defquota,$settingstatus);
 8893:     } else {
 8894:         return $defquota;
 8895:     }
 8896: }
 8897: 
 8898: ###############################################
 8899: 
 8900: =pod
 8901: 
 8902: =item * &excess_filesize_warning()
 8903: 
 8904: Returns warning message if upload of file to authoring space, or copying
 8905: of existing file within authoring space will cause quota for the authoring
 8906: space to be exceeded.
 8907: 
 8908: Same, if upload of a file directly to a course/community via Course Editor
 8909: will cause quota for uploaded content for the course to be exceeded.
 8910: 
 8911: Inputs: 6
 8912: 1. username or coursenum
 8913: 2. domain
 8914: 3. context ('author' or 'course')
 8915: 4. filename of file for which action is being requested
 8916: 5. filesize (kB) of file
 8917: 6. action being taken: copy or upload.
 8918: 
 8919: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 8920:          otherwise return null.
 8921: 
 8922: =back
 8923: 
 8924: =cut
 8925: 
 8926: sub excess_filesize_warning {
 8927:     my ($uname,$udom,$context,$filename,$filesize,$action) = @_;
 8928:     my $current_disk_usage = 0;
 8929:     my $disk_quota = &get_user_quota($uname,$udom,$context); #expressed in MB
 8930:     if ($context eq 'author') {
 8931:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 8932:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 8933:     } else {
 8934:         foreach my $subdir ('docs','supplemental') {
 8935:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 8936:         }
 8937:     }
 8938:     $disk_quota = int($disk_quota * 1000);
 8939:     if (($current_disk_usage + $filesize) > $disk_quota) {
 8940:         return '<p><span class="LC_warning">'.
 8941:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 8942:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
 8943:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 8944:                             $disk_quota,$current_disk_usage).
 8945:                '</p>';
 8946:     }
 8947:     return;
 8948: }
 8949: 
 8950: ###############################################
 8951: 
 8952: 
 8953: 
 8954: 
 8955: sub get_secgrprole_info {
 8956:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8957:     my %sections_count = &get_sections($cdom,$cnum);
 8958:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8959:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8960:     my @groups = sort(keys(%curr_groups));
 8961:     my $allroles = [];
 8962:     my $rolehash;
 8963:     my $accesshash = {
 8964:                      active => 'Currently has access',
 8965:                      future => 'Will have future access',
 8966:                      previous => 'Previously had access',
 8967:                   };
 8968:     if ($needroles) {
 8969:         $rolehash = {'all' => 'all'};
 8970:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8971: 	if (&Apache::lonnet::error(%user_roles)) {
 8972: 	    undef(%user_roles);
 8973: 	}
 8974:         foreach my $item (keys(%user_roles)) {
 8975:             my ($role)=split(/\:/,$item,2);
 8976:             if ($role eq 'cr') { next; }
 8977:             if ($role =~ /^cr/) {
 8978:                 $$rolehash{$role} = (split('/',$role))[3];
 8979:             } else {
 8980:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8981:             }
 8982:         }
 8983:         foreach my $key (sort(keys(%{$rolehash}))) {
 8984:             push(@{$allroles},$key);
 8985:         }
 8986:         push (@{$allroles},'st');
 8987:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8988:     }
 8989:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8990: }
 8991: 
 8992: sub user_picker {
 8993:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8994:     my $currdom = $dom;
 8995:     my %curr_selected = (
 8996:                         srchin => 'dom',
 8997:                         srchby => 'lastname',
 8998:                       );
 8999:     my $srchterm;
 9000:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9001:         if ($srch->{'srchby'} ne '') {
 9002:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9003:         }
 9004:         if ($srch->{'srchin'} ne '') {
 9005:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9006:         }
 9007:         if ($srch->{'srchtype'} ne '') {
 9008:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9009:         }
 9010:         if ($srch->{'srchdomain'} ne '') {
 9011:             $currdom = $srch->{'srchdomain'};
 9012:         }
 9013:         $srchterm = $srch->{'srchterm'};
 9014:     }
 9015:     my %lt=&Apache::lonlocal::texthash(
 9016:                     'usr'       => 'Search criteria',
 9017:                     'doma'      => 'Domain/institution to search',
 9018:                     'uname'     => 'username',
 9019:                     'lastname'  => 'last name',
 9020:                     'lastfirst' => 'last name, first name',
 9021:                     'crs'       => 'in this course',
 9022:                     'dom'       => 'in selected LON-CAPA domain', 
 9023:                     'alc'       => 'all LON-CAPA',
 9024:                     'instd'     => 'in institutional directory for selected domain',
 9025:                     'exact'     => 'is',
 9026:                     'contains'  => 'contains',
 9027:                     'begins'    => 'begins with',
 9028:                     'youm'      => "You must include some text to search for.",
 9029:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9030:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9031:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9032:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9033:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9034:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9035:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9036:                                        );
 9037:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9038:     my $srchinsel = ' <select name="srchin">';
 9039: 
 9040:     my @srchins = ('crs','dom','alc','instd');
 9041: 
 9042:     foreach my $option (@srchins) {
 9043:         # FIXME 'alc' option unavailable until 
 9044:         #       loncreateuser::print_user_query_page()
 9045:         #       has been completed.
 9046:         next if ($option eq 'alc');
 9047:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9048:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9049:         if ($curr_selected{'srchin'} eq $option) {
 9050:             $srchinsel .= ' 
 9051:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9052:         } else {
 9053:             $srchinsel .= '
 9054:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9055:         }
 9056:     }
 9057:     $srchinsel .= "\n  </select>\n";
 9058: 
 9059:     my $srchbysel =  ' <select name="srchby">';
 9060:     foreach my $option ('lastname','lastfirst','uname') {
 9061:         if ($curr_selected{'srchby'} eq $option) {
 9062:             $srchbysel .= '
 9063:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9064:         } else {
 9065:             $srchbysel .= '
 9066:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9067:          }
 9068:     }
 9069:     $srchbysel .= "\n  </select>\n";
 9070: 
 9071:     my $srchtypesel = ' <select name="srchtype">';
 9072:     foreach my $option ('begins','contains','exact') {
 9073:         if ($curr_selected{'srchtype'} eq $option) {
 9074:             $srchtypesel .= '
 9075:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9076:         } else {
 9077:             $srchtypesel .= '
 9078:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9079:         }
 9080:     }
 9081:     $srchtypesel .= "\n  </select>\n";
 9082: 
 9083:     my ($newuserscript,$new_user_create);
 9084:     my $context_dom = $env{'request.role.domain'};
 9085:     if ($context eq 'requestcrs') {
 9086:         if ($env{'form.coursedom'} ne '') { 
 9087:             $context_dom = $env{'form.coursedom'};
 9088:         }
 9089:     }
 9090:     if ($forcenewuser) {
 9091:         if (ref($srch) eq 'HASH') {
 9092:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9093:                 if ($cancreate) {
 9094:                     $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>';
 9095:                 } else {
 9096:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9097:                     my %usertypetext = (
 9098:                         official   => 'institutional',
 9099:                         unofficial => 'non-institutional',
 9100:                     );
 9101:                     $new_user_create = '<p class="LC_warning">'
 9102:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9103:                                       .' '
 9104:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9105:                                           ,'<a href="'.$helplink.'">','</a>')
 9106:                                       .'</p><br />';
 9107:                 }
 9108:             }
 9109:         }
 9110: 
 9111:         $newuserscript = <<"ENDSCRIPT";
 9112: 
 9113: function setSearch(createnew,callingForm) {
 9114:     if (createnew == 1) {
 9115:         for (var i=0; i<callingForm.srchby.length; i++) {
 9116:             if (callingForm.srchby.options[i].value == 'uname') {
 9117:                 callingForm.srchby.selectedIndex = i;
 9118:             }
 9119:         }
 9120:         for (var i=0; i<callingForm.srchin.length; i++) {
 9121:             if ( callingForm.srchin.options[i].value == 'dom') {
 9122: 		callingForm.srchin.selectedIndex = i;
 9123:             }
 9124:         }
 9125:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9126:             if (callingForm.srchtype.options[i].value == 'exact') {
 9127:                 callingForm.srchtype.selectedIndex = i;
 9128:             }
 9129:         }
 9130:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9131:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9132:                 callingForm.srchdomain.selectedIndex = i;
 9133:             }
 9134:         }
 9135:     }
 9136: }
 9137: ENDSCRIPT
 9138: 
 9139:     }
 9140: 
 9141:     my $output = <<"END_BLOCK";
 9142: <script type="text/javascript">
 9143: // <![CDATA[
 9144: function validateEntry(callingForm) {
 9145: 
 9146:     var checkok = 1;
 9147:     var srchin;
 9148:     for (var i=0; i<callingForm.srchin.length; i++) {
 9149: 	if ( callingForm.srchin[i].checked ) {
 9150: 	    srchin = callingForm.srchin[i].value;
 9151: 	}
 9152:     }
 9153: 
 9154:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9155:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9156:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9157:     var srchterm =  callingForm.srchterm.value;
 9158:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9159:     var msg = "";
 9160: 
 9161:     if (srchterm == "") {
 9162:         checkok = 0;
 9163:         msg += "$lt{'youm'}\\n";
 9164:     }
 9165: 
 9166:     if (srchtype== 'begins') {
 9167:         if (srchterm.length < 2) {
 9168:             checkok = 0;
 9169:             msg += "$lt{'thte'}\\n";
 9170:         }
 9171:     }
 9172: 
 9173:     if (srchtype== 'contains') {
 9174:         if (srchterm.length < 3) {
 9175:             checkok = 0;
 9176:             msg += "$lt{'thet'}\\n";
 9177:         }
 9178:     }
 9179:     if (srchin == 'instd') {
 9180:         if (srchdomain == '') {
 9181:             checkok = 0;
 9182:             msg += "$lt{'yomc'}\\n";
 9183:         }
 9184:     }
 9185:     if (srchin == 'dom') {
 9186:         if (srchdomain == '') {
 9187:             checkok = 0;
 9188:             msg += "$lt{'ymcd'}\\n";
 9189:         }
 9190:     }
 9191:     if (srchby == 'lastfirst') {
 9192:         if (srchterm.indexOf(",") == -1) {
 9193:             checkok = 0;
 9194:             msg += "$lt{'whus'}\\n";
 9195:         }
 9196:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9197:             checkok = 0;
 9198:             msg += "$lt{'whse'}\\n";
 9199:         }
 9200:     }
 9201:     if (checkok == 0) {
 9202:         alert("$lt{'thfo'}\\n"+msg);
 9203:         return;
 9204:     }
 9205:     if (checkok == 1) {
 9206:         callingForm.submit();
 9207:     }
 9208: }
 9209: 
 9210: $newuserscript
 9211: 
 9212: // ]]>
 9213: </script>
 9214: 
 9215: $new_user_create
 9216: 
 9217: END_BLOCK
 9218: 
 9219:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9220:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9221:                $domform.
 9222:                &Apache::lonhtmlcommon::row_closure().
 9223:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9224:                $srchbysel.
 9225:                $srchtypesel. 
 9226:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9227:                $srchinsel.
 9228:                &Apache::lonhtmlcommon::row_closure(1). 
 9229:                &Apache::lonhtmlcommon::end_pick_box().
 9230:                '<br />';
 9231:     return $output;
 9232: }
 9233: 
 9234: sub user_rule_check {
 9235:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9236:     my $response;
 9237:     if (ref($usershash) eq 'HASH') {
 9238:         foreach my $user (keys(%{$usershash})) {
 9239:             my ($uname,$udom) = split(/:/,$user);
 9240:             next if ($udom eq '' || $uname eq '');
 9241:             my ($id,$newuser);
 9242:             if (ref($usershash->{$user}) eq 'HASH') {
 9243:                 $newuser = $usershash->{$user}->{'newuser'};
 9244:                 $id = $usershash->{$user}->{'id'};
 9245:             }
 9246:             my $inst_response;
 9247:             if (ref($checks) eq 'HASH') {
 9248:                 if (defined($checks->{'username'})) {
 9249:                     ($inst_response,%{$inst_results->{$user}}) = 
 9250:                         &Apache::lonnet::get_instuser($udom,$uname);
 9251:                 } elsif (defined($checks->{'id'})) {
 9252:                     ($inst_response,%{$inst_results->{$user}}) =
 9253:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9254:                 }
 9255:             } else {
 9256:                 ($inst_response,%{$inst_results->{$user}}) =
 9257:                     &Apache::lonnet::get_instuser($udom,$uname);
 9258:                 return;
 9259:             }
 9260:             if (!$got_rules->{$udom}) {
 9261:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9262:                                                   ['usercreation'],$udom);
 9263:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9264:                     foreach my $item ('username','id') {
 9265:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9266:                             $$curr_rules{$udom}{$item} = 
 9267:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9268:                         }
 9269:                     }
 9270:                 }
 9271:                 $got_rules->{$udom} = 1;  
 9272:             }
 9273:             foreach my $item (keys(%{$checks})) {
 9274:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9275:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9276:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9277:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9278:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9279:                                 if ($rule_check{$rule}) {
 9280:                                     $$rulematch{$user}{$item} = $rule;
 9281:                                     if ($inst_response eq 'ok') {
 9282:                                         if (ref($inst_results) eq 'HASH') {
 9283:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9284:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9285:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9286:                                                 }
 9287:                                             }
 9288:                                         }
 9289:                                     }
 9290:                                     last;
 9291:                                 }
 9292:                             }
 9293:                         }
 9294:                     }
 9295:                 }
 9296:             }
 9297:         }
 9298:     }
 9299:     return;
 9300: }
 9301: 
 9302: sub user_rule_formats {
 9303:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9304:     my %text = ( 
 9305:                  'username' => 'Usernames',
 9306:                  'id'       => 'IDs',
 9307:                );
 9308:     my $output;
 9309:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9310:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9311:         if (@{$ruleorder} > 0) {
 9312:             $output = '<br />'.
 9313:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9314:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9315:                       ' <ul>';
 9316:             foreach my $rule (@{$ruleorder}) {
 9317:                 if (ref($curr_rules) eq 'ARRAY') {
 9318:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9319:                         if (ref($rules->{$rule}) eq 'HASH') {
 9320:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9321:                                         $rules->{$rule}{'desc'}.'</li>';
 9322:                         }
 9323:                     }
 9324:                 }
 9325:             }
 9326:             $output .= '</ul>';
 9327:         }
 9328:     }
 9329:     return $output;
 9330: }
 9331: 
 9332: sub instrule_disallow_msg {
 9333:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9334:     my $response;
 9335:     my %text = (
 9336:                   item   => 'username',
 9337:                   items  => 'usernames',
 9338:                   match  => 'matches',
 9339:                   do     => 'does',
 9340:                   action => 'a username',
 9341:                   one    => 'one',
 9342:                );
 9343:     if ($count > 1) {
 9344:         $text{'item'} = 'usernames';
 9345:         $text{'match'} ='match';
 9346:         $text{'do'} = 'do';
 9347:         $text{'action'} = 'usernames',
 9348:         $text{'one'} = 'ones';
 9349:     }
 9350:     if ($checkitem eq 'id') {
 9351:         $text{'items'} = 'IDs';
 9352:         $text{'item'} = 'ID';
 9353:         $text{'action'} = 'an ID';
 9354:         if ($count > 1) {
 9355:             $text{'item'} = 'IDs';
 9356:             $text{'action'} = 'IDs';
 9357:         }
 9358:     }
 9359:     $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 />';
 9360:     if ($mode eq 'upload') {
 9361:         if ($checkitem eq 'username') {
 9362:             $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'}.");
 9363:         } elsif ($checkitem eq 'id') {
 9364:             $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.");
 9365:         }
 9366:     } elsif ($mode eq 'selfcreate') {
 9367:         if ($checkitem eq 'id') {
 9368:             $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.");
 9369:         }
 9370:     } else {
 9371:         if ($checkitem eq 'username') {
 9372:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9373:         } elsif ($checkitem eq 'id') {
 9374:             $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.");
 9375:         }
 9376:     }
 9377:     return $response;
 9378: }
 9379: 
 9380: sub personal_data_fieldtitles {
 9381:     my %fieldtitles = &Apache::lonlocal::texthash (
 9382:                         id => 'Student/Employee ID',
 9383:                         permanentemail => 'E-mail address',
 9384:                         lastname => 'Last Name',
 9385:                         firstname => 'First Name',
 9386:                         middlename => 'Middle Name',
 9387:                         generation => 'Generation',
 9388:                         gen => 'Generation',
 9389:                         inststatus => 'Affiliation',
 9390:                    );
 9391:     return %fieldtitles;
 9392: }
 9393: 
 9394: sub sorted_inst_types {
 9395:     my ($dom) = @_;
 9396:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9397:     my $othertitle = &mt('All users');
 9398:     if ($env{'request.course.id'}) {
 9399:         $othertitle  = &mt('Any users');
 9400:     }
 9401:     my @types;
 9402:     if (ref($order) eq 'ARRAY') {
 9403:         @types = @{$order};
 9404:     }
 9405:     if (@types == 0) {
 9406:         if (ref($usertypes) eq 'HASH') {
 9407:             @types = sort(keys(%{$usertypes}));
 9408:         }
 9409:     }
 9410:     if (keys(%{$usertypes}) > 0) {
 9411:         $othertitle = &mt('Other users');
 9412:     }
 9413:     return ($othertitle,$usertypes,\@types);
 9414: }
 9415: 
 9416: sub get_institutional_codes {
 9417:     my ($settings,$allcourses,$LC_code) = @_;
 9418: # Get complete list of course sections to update
 9419:     my @currsections = ();
 9420:     my @currxlists = ();
 9421:     my $coursecode = $$settings{'internal.coursecode'};
 9422: 
 9423:     if ($$settings{'internal.sectionnums'} ne '') {
 9424:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9425:     }
 9426: 
 9427:     if ($$settings{'internal.crosslistings'} ne '') {
 9428:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9429:     }
 9430: 
 9431:     if (@currxlists > 0) {
 9432:         foreach (@currxlists) {
 9433:             if (m/^([^:]+):(\w*)$/) {
 9434:                 unless (grep/^$1$/,@{$allcourses}) {
 9435:                     push @{$allcourses},$1;
 9436:                     $$LC_code{$1} = $2;
 9437:                 }
 9438:             }
 9439:         }
 9440:     }
 9441:  
 9442:     if (@currsections > 0) {
 9443:         foreach (@currsections) {
 9444:             if (m/^(\w+):(\w*)$/) {
 9445:                 my $sec = $coursecode.$1;
 9446:                 my $lc_sec = $2;
 9447:                 unless (grep/^$sec$/,@{$allcourses}) {
 9448:                     push @{$allcourses},$sec;
 9449:                     $$LC_code{$sec} = $lc_sec;
 9450:                 }
 9451:             }
 9452:         }
 9453:     }
 9454:     return;
 9455: }
 9456: 
 9457: sub get_standard_codeitems {
 9458:     return ('Year','Semester','Department','Number','Section');
 9459: }
 9460: 
 9461: =pod
 9462: 
 9463: =head1 Slot Helpers
 9464: 
 9465: =over 4
 9466: 
 9467: =item * sorted_slots()
 9468: 
 9469: Sorts an array of slot names in order of an optional sort key,
 9470: default sort is by slot start time (earliest first). 
 9471: 
 9472: Inputs:
 9473: 
 9474: =over 4
 9475: 
 9476: slotsarr  - Reference to array of unsorted slot names.
 9477: 
 9478: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9479: 
 9480: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9481: 
 9482: =back
 9483: 
 9484: Returns:
 9485: 
 9486: =over 4
 9487: 
 9488: sorted   - An array of slot names sorted by a specified sort key 
 9489:            (default sort key is start time of the slot).
 9490: 
 9491: =back
 9492: 
 9493: =cut
 9494: 
 9495: 
 9496: sub sorted_slots {
 9497:     my ($slotsarr,$slots,$sortkey) = @_;
 9498:     if ($sortkey eq '') {
 9499:         $sortkey = 'starttime';
 9500:     }
 9501:     my @sorted;
 9502:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9503:         @sorted =
 9504:             sort {
 9505:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9506:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9507:                      }
 9508:                      if (ref($slots->{$a})) { return -1;}
 9509:                      if (ref($slots->{$b})) { return 1;}
 9510:                      return 0;
 9511:                  } @{$slotsarr};
 9512:     }
 9513:     return @sorted;
 9514: }
 9515: 
 9516: =pod
 9517: 
 9518: =item * get_future_slots()
 9519: 
 9520: Inputs:
 9521: 
 9522: =over 4
 9523: 
 9524: cnum - course number
 9525: 
 9526: cdom - course domain
 9527: 
 9528: now - current UNIX time
 9529: 
 9530: symb - optional symb
 9531: 
 9532: =back
 9533: 
 9534: Returns:
 9535: 
 9536: =over 4
 9537: 
 9538: sorted_reservable - ref to array of student_schedulable slots currently 
 9539:                     reservable, ordered by end date of reservation period.
 9540: 
 9541: reservable_now - ref to hash of student_schedulable slots currently
 9542:                  reservable.
 9543: 
 9544:     Keys in inner hash are:
 9545:     (a) symb: either blank or symb to which slot use is restricted.
 9546:     (b) endreserve: end date of reservation period. 
 9547: 
 9548: sorted_future - ref to array of student_schedulable slots reservable in
 9549:                 the future, ordered by start date of reservation period.
 9550: 
 9551: future_reservable - ref to hash of student_schedulable slots reservable
 9552:                     in the future.
 9553: 
 9554:     Keys in inner hash are:
 9555:     (a) symb: either blank or symb to which slot use is restricted.
 9556:     (b) startreserve:  start date of reservation period.
 9557: 
 9558: =back
 9559: 
 9560: =cut
 9561: 
 9562: sub get_future_slots {
 9563:     my ($cnum,$cdom,$now,$symb) = @_;
 9564:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9565:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9566:     foreach my $slot (keys(%slots)) {
 9567:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9568:         if ($symb) {
 9569:             next if (($slots{$slot}->{'symb'} ne '') && 
 9570:                      ($slots{$slot}->{'symb'} ne $symb));
 9571:         }
 9572:         if (($slots{$slot}->{'starttime'} > $now) &&
 9573:             ($slots{$slot}->{'endtime'} > $now)) {
 9574:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9575:                 my $userallowed = 0;
 9576:                 if ($slots{$slot}->{'allowedsections'}) {
 9577:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9578:                     if (!defined($env{'request.role.sec'})
 9579:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9580:                         $userallowed=1;
 9581:                     } else {
 9582:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9583:                             $userallowed=1;
 9584:                         }
 9585:                     }
 9586:                     unless ($userallowed) {
 9587:                         if (defined($env{'request.course.groups'})) {
 9588:                             my @groups = split(/:/,$env{'request.course.groups'});
 9589:                             foreach my $group (@groups) {
 9590:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9591:                                     $userallowed=1;
 9592:                                     last;
 9593:                                 }
 9594:                             }
 9595:                         }
 9596:                     }
 9597:                 }
 9598:                 if ($slots{$slot}->{'allowedusers'}) {
 9599:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9600:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9601:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9602:                         $userallowed = 1;
 9603:                     }
 9604:                 }
 9605:                 next unless($userallowed);
 9606:             }
 9607:             my $startreserve = $slots{$slot}->{'startreserve'};
 9608:             my $endreserve = $slots{$slot}->{'endreserve'};
 9609:             my $symb = $slots{$slot}->{'symb'};
 9610:             if (($startreserve < $now) &&
 9611:                 (!$endreserve || $endreserve > $now)) {
 9612:                 my $lastres = $endreserve;
 9613:                 if (!$lastres) {
 9614:                     $lastres = $slots{$slot}->{'starttime'};
 9615:                 }
 9616:                 $reservable_now{$slot} = {
 9617:                                            symb       => $symb,
 9618:                                            endreserve => $lastres
 9619:                                          };
 9620:             } elsif (($startreserve > $now) &&
 9621:                      (!$endreserve || $endreserve > $startreserve)) {
 9622:                 $future_reservable{$slot} = {
 9623:                                               symb         => $symb,
 9624:                                               startreserve => $startreserve
 9625:                                             };
 9626:             }
 9627:         }
 9628:     }
 9629:     my @unsorted_reservable = keys(%reservable_now);
 9630:     if (@unsorted_reservable > 0) {
 9631:         @sorted_reservable = 
 9632:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9633:     }
 9634:     my @unsorted_future = keys(%future_reservable);
 9635:     if (@unsorted_future > 0) {
 9636:         @sorted_future =
 9637:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9638:     }
 9639:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9640: }
 9641: 
 9642: =pod
 9643: 
 9644: =back
 9645: 
 9646: =head1 HTTP Helpers
 9647: 
 9648: =over 4
 9649: 
 9650: =item * &get_unprocessed_cgi($query,$possible_names)
 9651: 
 9652: Modify the %env hash to contain unprocessed CGI form parameters held in
 9653: $query.  The parameters listed in $possible_names (an array reference),
 9654: will be set in $env{'form.name'} if they do not already exist.
 9655: 
 9656: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9657: $possible_names is an ref to an array of form element names.  As an example:
 9658: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9659: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9660: 
 9661: =cut
 9662: 
 9663: sub get_unprocessed_cgi {
 9664:   my ($query,$possible_names)= @_;
 9665:   # $Apache::lonxml::debug=1;
 9666:   foreach my $pair (split(/&/,$query)) {
 9667:     my ($name, $value) = split(/=/,$pair);
 9668:     $name = &unescape($name);
 9669:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9670:       $value =~ tr/+/ /;
 9671:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9672:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9673:     }
 9674:   }
 9675: }
 9676: 
 9677: =pod
 9678: 
 9679: =item * &cacheheader() 
 9680: 
 9681: returns cache-controlling header code
 9682: 
 9683: =cut
 9684: 
 9685: sub cacheheader {
 9686:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9687:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9688:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9689:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9690:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9691:     return $output;
 9692: }
 9693: 
 9694: =pod
 9695: 
 9696: =item * &no_cache($r) 
 9697: 
 9698: specifies header code to not have cache
 9699: 
 9700: =cut
 9701: 
 9702: sub no_cache {
 9703:     my ($r) = @_;
 9704:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9705: 	$env{'request.method'} ne 'GET') { return ''; }
 9706:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9707:     $r->no_cache(1);
 9708:     $r->header_out("Expires" => $date);
 9709:     $r->header_out("Pragma" => "no-cache");
 9710: }
 9711: 
 9712: sub content_type {
 9713:     my ($r,$type,$charset) = @_;
 9714:     if ($r) {
 9715: 	#  Note that printout.pl calls this with undef for $r.
 9716: 	&no_cache($r);
 9717:     }
 9718:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9719:     unless ($charset) {
 9720: 	$charset=&Apache::lonlocal::current_encoding;
 9721:     }
 9722:     if ($charset) { $type.='; charset='.$charset; }
 9723:     if ($r) {
 9724: 	$r->content_type($type);
 9725:     } else {
 9726: 	print("Content-type: $type\n\n");
 9727:     }
 9728: }
 9729: 
 9730: =pod
 9731: 
 9732: =item * &add_to_env($name,$value) 
 9733: 
 9734: adds $name to the %env hash with value
 9735: $value, if $name already exists, the entry is converted to an array
 9736: reference and $value is added to the array.
 9737: 
 9738: =cut
 9739: 
 9740: sub add_to_env {
 9741:   my ($name,$value)=@_;
 9742:   if (defined($env{$name})) {
 9743:     if (ref($env{$name})) {
 9744:       #already have multiple values
 9745:       push(@{ $env{$name} },$value);
 9746:     } else {
 9747:       #first time seeing multiple values, convert hash entry to an arrayref
 9748:       my $first=$env{$name};
 9749:       undef($env{$name});
 9750:       push(@{ $env{$name} },$first,$value);
 9751:     }
 9752:   } else {
 9753:     $env{$name}=$value;
 9754:   }
 9755: }
 9756: 
 9757: =pod
 9758: 
 9759: =item * &get_env_multiple($name) 
 9760: 
 9761: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9762: values may be defined and end up as an array ref.
 9763: 
 9764: returns an array of values
 9765: 
 9766: =cut
 9767: 
 9768: sub get_env_multiple {
 9769:     my ($name) = @_;
 9770:     my @values;
 9771:     if (defined($env{$name})) {
 9772:         # exists is it an array
 9773:         if (ref($env{$name})) {
 9774:             @values=@{ $env{$name} };
 9775:         } else {
 9776:             $values[0]=$env{$name};
 9777:         }
 9778:     }
 9779:     return(@values);
 9780: }
 9781: 
 9782: sub ask_for_embedded_content {
 9783:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9784:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9785:         %currsubfile,%unused,$rem);
 9786:     my $counter = 0;
 9787:     my $numnew = 0;
 9788:     my $numremref = 0;
 9789:     my $numinvalid = 0;
 9790:     my $numpathchg = 0;
 9791:     my $numexisting = 0;
 9792:     my $numunused = 0;
 9793:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9794:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
 9795:     my $heading = &mt('Upload embedded files');
 9796:     my $buttontext = &mt('Upload');
 9797: 
 9798:     if ($env{'request.course.id'}) {
 9799:         if ($actionurl eq '/adm/dependencies') {
 9800:             $navmap = Apache::lonnavmaps::navmap->new();
 9801:         }
 9802:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9803:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9804:     }
 9805:     if (($actionurl eq '/adm/portfolio') || 
 9806:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9807:         my $current_path='/';
 9808:         if ($env{'form.currentpath'}) {
 9809:             $current_path = $env{'form.currentpath'};
 9810:         }
 9811:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9812:             $udom = $cdom;
 9813:             $uname = $cnum;
 9814:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9815:         } else {
 9816:             $udom = $env{'user.domain'};
 9817:             $uname = $env{'user.name'};
 9818:             $url = '/userfiles/portfolio';
 9819:         }
 9820:         $toplevel = $url.'/';
 9821:         $url .= $current_path;
 9822:         $getpropath = 1;
 9823:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9824:              ($actionurl eq '/adm/imsimport')) { 
 9825:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9826:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9827:         $toplevel = $url;
 9828:         if ($rest ne '') {
 9829:             $url .= $rest;
 9830:         }
 9831:     } elsif ($actionurl eq '/adm/coursedocs') {
 9832:         if (ref($args) eq 'HASH') {
 9833:             $url = $args->{'docs_url'};
 9834:             $toplevel = $url;
 9835:             if ($args->{'context'} eq 'paste') {
 9836:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9837:                 ($path) = 
 9838:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9839:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9840:                 $fileloc =~ s{^/}{};
 9841:             }
 9842:         }
 9843:     } elsif ($actionurl eq '/adm/dependencies')  {
 9844:         if ($env{'request.course.id'} ne '') {
 9845:             if (ref($args) eq 'HASH') {
 9846:                 $url = $args->{'docs_url'};
 9847:                 $title = $args->{'docs_title'};
 9848:                 $toplevel = $url; 
 9849:                 unless ($toplevel =~ m{^/}) {
 9850:                     $toplevel = "/$url";
 9851:                 }
 9852:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9853:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
 9854:                     $path = $1;
 9855:                 } else {
 9856:                     ($path) =
 9857:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9858:                 }
 9859:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9860:                 $fileloc =~ s{^/}{};
 9861:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9862:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9863:             }
 9864:         }
 9865:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9866:         $udom = $cdom;
 9867:         $uname = $cnum;
 9868:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
 9869:         $toplevel = $url;
 9870:         $path = $url;
 9871:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
 9872:         $fileloc =~ s{^/}{};
 9873:     }
 9874:     foreach my $file (keys(%{$allfiles})) {
 9875:         my $embed_file;
 9876:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
 9877:             $embed_file = $1;
 9878:         } else {
 9879:             $embed_file = $file;
 9880:         }
 9881:         my ($absolutepath,$cleaned_file);
 9882:         if ($embed_file =~ m{^\w+://}) {
 9883:             $cleaned_file = $embed_file;
 9884:             $newfiles{$cleaned_file} = 1;
 9885:             $mapping{$cleaned_file} = $embed_file;
 9886:         } else {
 9887:             $cleaned_file = &clean_path($embed_file);
 9888:             if ($embed_file =~ m{^/}) {
 9889:                 $absolutepath = $embed_file;
 9890:             }
 9891:             if ($cleaned_file =~ m{/}) {
 9892:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
 9893:                 $path = &check_for_traversal($path,$url,$toplevel);
 9894:                 my $item = $fname;
 9895:                 if ($path ne '') {
 9896:                     $item = $path.'/'.$fname;
 9897:                     $subdependencies{$path}{$fname} = 1;
 9898:                 } else {
 9899:                     $dependencies{$item} = 1;
 9900:                 }
 9901:                 if ($absolutepath) {
 9902:                     $mapping{$item} = $absolutepath;
 9903:                 } else {
 9904:                     $mapping{$item} = $embed_file;
 9905:                 }
 9906:             } else {
 9907:                 $dependencies{$embed_file} = 1;
 9908:                 if ($absolutepath) {
 9909:                     $mapping{$cleaned_file} = $absolutepath;
 9910:                 } else {
 9911:                     $mapping{$cleaned_file} = $embed_file;
 9912:                 }
 9913:             }
 9914:         }
 9915:     }
 9916:     my $dirptr = 16384;
 9917:     foreach my $path (keys(%subdependencies)) {
 9918:         $currsubfile{$path} = {};
 9919:         if (($actionurl eq '/adm/portfolio') || 
 9920:             ($actionurl eq '/adm/coursegrp_portfolio')) {
 9921:             my ($sublistref,$listerror) =
 9922:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9923:             if (ref($sublistref) eq 'ARRAY') {
 9924:                 foreach my $line (@{$sublistref}) {
 9925:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9926:                     $currsubfile{$path}{$file_name} = 1;
 9927:                 }
 9928:             }
 9929:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9930:             if (opendir(my $dir,$url.'/'.$path)) {
 9931:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9932:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9933:             }
 9934:         } elsif (($actionurl eq '/adm/dependencies') ||
 9935:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9936:                   ($args->{'context'} eq 'paste')) ||
 9937:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9938:             if ($env{'request.course.id'} ne '') {
 9939:                 my $dir;
 9940:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9941:                     $dir = $fileloc;
 9942:                 } else {
 9943:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9944:                 }
 9945:                 if ($dir ne '') {
 9946:                     my ($sublistref,$listerror) =
 9947:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9948:                     if (ref($sublistref) eq 'ARRAY') {
 9949:                         foreach my $line (@{$sublistref}) {
 9950:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9951:                                 undef,$mtime)=split(/\&/,$line,12);
 9952:                             unless (($testdir&$dirptr) ||
 9953:                                     ($file_name =~ /^\.\.?$/)) {
 9954:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9955:                             }
 9956:                         }
 9957:                     }
 9958:                 }
 9959:             }
 9960:         }
 9961:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9962:             if (exists($currsubfile{$path}{$file})) {
 9963:                 my $item = $path.'/'.$file;
 9964:                 unless ($mapping{$item} eq $item) {
 9965:                     $pathchanges{$item} = 1;
 9966:                 }
 9967:                 $existing{$item} = 1;
 9968:                 $numexisting ++;
 9969:             } else {
 9970:                 $newfiles{$path.'/'.$file} = 1;
 9971:             }
 9972:         }
 9973:         if ($actionurl eq '/adm/dependencies') {
 9974:             foreach my $path (keys(%currsubfile)) {
 9975:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9976:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9977:                          unless ($subdependencies{$path}{$file}) {
 9978:                              next if (($rem ne '') &&
 9979:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9980:                                        (ref($navmap) &&
 9981:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9982:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9983:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9984:                              $unused{$path.'/'.$file} = 1; 
 9985:                          }
 9986:                     }
 9987:                 }
 9988:             }
 9989:         }
 9990:     }
 9991:     my %currfile;
 9992:     if (($actionurl eq '/adm/portfolio') ||
 9993:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9994:         my ($dirlistref,$listerror) =
 9995:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9996:         if (ref($dirlistref) eq 'ARRAY') {
 9997:             foreach my $line (@{$dirlistref}) {
 9998:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9999:                 $currfile{$file_name} = 1;
10000:             }
10001:         }
10002:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10003:         if (opendir(my $dir,$url)) {
10004:             my @dir_list = grep(!/^\./,readdir($dir));
10005:             map {$currfile{$_} = 1;} @dir_list;
10006:         }
10007:     } elsif (($actionurl eq '/adm/dependencies') ||
10008:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10009:               ($args->{'context'} eq 'paste')) ||
10010:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10011:         if ($env{'request.course.id'} ne '') {
10012:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10013:             if ($dir ne '') {
10014:                 my ($dirlistref,$listerror) =
10015:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10016:                 if (ref($dirlistref) eq 'ARRAY') {
10017:                     foreach my $line (@{$dirlistref}) {
10018:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10019:                             $size,undef,$mtime)=split(/\&/,$line,12);
10020:                         unless (($testdir&$dirptr) ||
10021:                                 ($file_name =~ /^\.\.?$/)) {
10022:                             $currfile{$file_name} = [$size,$mtime];
10023:                         }
10024:                     }
10025:                 }
10026:             }
10027:         }
10028:     }
10029:     foreach my $file (keys(%dependencies)) {
10030:         if (exists($currfile{$file})) {
10031:             unless ($mapping{$file} eq $file) {
10032:                 $pathchanges{$file} = 1;
10033:             }
10034:             $existing{$file} = 1;
10035:             $numexisting ++;
10036:         } else {
10037:             $newfiles{$file} = 1;
10038:         }
10039:     }
10040:     foreach my $file (keys(%currfile)) {
10041:         unless (($file eq $filename) ||
10042:                 ($file eq $filename.'.bak') ||
10043:                 ($dependencies{$file})) {
10044:             if ($actionurl eq '/adm/dependencies') {
10045:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10046:                     next if (($rem ne '') &&
10047:                              (($env{"httpref.$rem".$file} ne '') ||
10048:                               (ref($navmap) &&
10049:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10050:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10051:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10052:                 }
10053:             }
10054:             $unused{$file} = 1;
10055:         }
10056:     }
10057:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10058:         ($args->{'context'} eq 'paste')) {
10059:         $counter = scalar(keys(%existing));
10060:         $numpathchg = scalar(keys(%pathchanges));
10061:         return ($output,$counter,$numpathchg,\%existing);
10062:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
10063:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10064:         $counter = scalar(keys(%existing));
10065:         $numpathchg = scalar(keys(%pathchanges));
10066:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10067:     }
10068:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10069:         if ($actionurl eq '/adm/dependencies') {
10070:             next if ($embed_file =~ m{^\w+://});
10071:         }
10072:         $upload_output .= &start_data_table_row().
10073:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10074:                           '<span class="LC_filename">'.$embed_file.'</span>';
10075:         unless ($mapping{$embed_file} eq $embed_file) {
10076:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10077:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10078:         }
10079:         $upload_output .= '</td>';
10080:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10081:             $upload_output.='<td align="right">'.
10082:                             '<span class="LC_info LC_fontsize_medium">'.
10083:                             &mt("URL points to web address").'</span>';
10084:             $numremref++;
10085:         } elsif ($args->{'error_on_invalid_names'}
10086:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10087:             $upload_output.='<td align="right"><span class="LC_warning">'.
10088:                             &mt('Invalid characters').'</span>';
10089:             $numinvalid++;
10090:         } else {
10091:             $upload_output .= '<td>'.
10092:                               &embedded_file_element('upload_embedded',$counter,
10093:                                                      $embed_file,\%mapping,
10094:                                                      $allfiles,$codebase,'upload');
10095:             $counter ++;
10096:             $numnew ++;
10097:         }
10098:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10099:     }
10100:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10101:         if ($actionurl eq '/adm/dependencies') {
10102:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10103:             $modify_output .= &start_data_table_row().
10104:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10105:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10106:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10107:                               '<td>'.$size.'</td>'.
10108:                               '<td>'.$mtime.'</td>'.
10109:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10110:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10111:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10112:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10113:                               &embedded_file_element('upload_embedded',$counter,
10114:                                                      $embed_file,\%mapping,
10115:                                                      $allfiles,$codebase,'modify').
10116:                               '</div></td>'.
10117:                               &end_data_table_row()."\n";
10118:             $counter ++;
10119:         } else {
10120:             $upload_output .= &start_data_table_row().
10121:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10122:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10123:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10124:                               &Apache::loncommon::end_data_table_row()."\n";
10125:         }
10126:     }
10127:     my $delidx = $counter;
10128:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10129:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10130:         $delete_output .= &start_data_table_row().
10131:                           '<td><img src="'.&icon($oldfile).'" />'.
10132:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10133:                           '<td>'.$size.'</td>'.
10134:                           '<td>'.$mtime.'</td>'.
10135:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10136:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10137:                           &embedded_file_element('upload_embedded',$delidx,
10138:                                                  $oldfile,\%mapping,$allfiles,
10139:                                                  $codebase,'delete').'</td>'.
10140:                           &end_data_table_row()."\n"; 
10141:         $numunused ++;
10142:         $delidx ++;
10143:     }
10144:     if ($upload_output) {
10145:         $upload_output = &start_data_table().
10146:                          $upload_output.
10147:                          &end_data_table()."\n";
10148:     }
10149:     if ($modify_output) {
10150:         $modify_output = &start_data_table().
10151:                          &start_data_table_header_row().
10152:                          '<th>'.&mt('File').'</th>'.
10153:                          '<th>'.&mt('Size (KB)').'</th>'.
10154:                          '<th>'.&mt('Modified').'</th>'.
10155:                          '<th>'.&mt('Upload replacement?').'</th>'.
10156:                          &end_data_table_header_row().
10157:                          $modify_output.
10158:                          &end_data_table()."\n";
10159:     }
10160:     if ($delete_output) {
10161:         $delete_output = &start_data_table().
10162:                          &start_data_table_header_row().
10163:                          '<th>'.&mt('File').'</th>'.
10164:                          '<th>'.&mt('Size (KB)').'</th>'.
10165:                          '<th>'.&mt('Modified').'</th>'.
10166:                          '<th>'.&mt('Delete?').'</th>'.
10167:                          &end_data_table_header_row().
10168:                          $delete_output.
10169:                          &end_data_table()."\n";
10170:     }
10171:     my $applies = 0;
10172:     if ($numremref) {
10173:         $applies ++;
10174:     }
10175:     if ($numinvalid) {
10176:         $applies ++;
10177:     }
10178:     if ($numexisting) {
10179:         $applies ++;
10180:     }
10181:     if ($counter || $numunused) {
10182:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10183:                   ' method="post" enctype="multipart/form-data">'."\n".
10184:                   $state.'<h3>'.$heading.'</h3>'; 
10185:         if ($actionurl eq '/adm/dependencies') {
10186:             if ($numnew) {
10187:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10188:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10189:                            $upload_output.'<br />'."\n";
10190:             }
10191:             if ($numexisting) {
10192:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10193:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10194:                            $modify_output.'<br />'."\n";
10195:                            $buttontext = &mt('Save changes');
10196:             }
10197:             if ($numunused) {
10198:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10199:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10200:                            $delete_output.'<br />'."\n";
10201:                            $buttontext = &mt('Save changes');
10202:             }
10203:         } else {
10204:             $output .= $upload_output.'<br />'."\n";
10205:         }
10206:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10207:                    $counter.'" />'."\n";
10208:         if ($actionurl eq '/adm/dependencies') { 
10209:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10210:                        $numnew.'" />'."\n";
10211:         } elsif ($actionurl eq '') {
10212:             $output .=  '<input type="hidden" name="phase" value="three" />';
10213:         }
10214:     } elsif ($applies) {
10215:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10216:         if ($applies > 1) {
10217:             $output .=  
10218:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10219:             if ($numremref) {
10220:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10221:             }
10222:             if ($numinvalid) {
10223:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10224:             }
10225:             if ($numexisting) {
10226:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10227:             }
10228:             $output .= '</ul><br />';
10229:         } elsif ($numremref) {
10230:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10231:         } elsif ($numinvalid) {
10232:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10233:         } elsif ($numexisting) {
10234:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10235:         }
10236:         $output .= $upload_output.'<br />';
10237:     }
10238:     my ($pathchange_output,$chgcount);
10239:     $chgcount = $counter;
10240:     if (keys(%pathchanges) > 0) {
10241:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10242:             if ($counter) {
10243:                 $output .= &embedded_file_element('pathchange',$chgcount,
10244:                                                   $embed_file,\%mapping,
10245:                                                   $allfiles,$codebase,'change');
10246:             } else {
10247:                 $pathchange_output .= 
10248:                     &start_data_table_row().
10249:                     '<td><input type ="checkbox" name="namechange" value="'.
10250:                     $chgcount.'" checked="checked" /></td>'.
10251:                     '<td>'.$mapping{$embed_file}.'</td>'.
10252:                     '<td>'.$embed_file.
10253:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10254:                                            \%mapping,$allfiles,$codebase,'change').
10255:                     '</td>'.&end_data_table_row();
10256:             }
10257:             $numpathchg ++;
10258:             $chgcount ++;
10259:         }
10260:     }
10261:     if (($counter) || ($numunused)) {
10262:         if ($numpathchg) {
10263:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10264:                        $numpathchg.'" />'."\n";
10265:         }
10266:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10267:             ($actionurl eq '/adm/imsimport')) {
10268:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10269:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10270:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10271:         } elsif ($actionurl eq '/adm/dependencies') {
10272:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10273:         }
10274:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10275:     } elsif ($numpathchg) {
10276:         my %pathchange = ();
10277:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10278:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10279:             $output .= '<p>'.&mt('or').'</p>'; 
10280:         }
10281:     }
10282:     return ($output,$counter,$numpathchg);
10283: }
10284: 
10285: =pod
10286: 
10287: =item * clean_path($name)
10288: 
10289: Performs clean-up of directories, subdirectories and filename in an
10290: embedded object, referenced in an HTML file which is being uploaded
10291: to a course or portfolio, where 
10292: "Upload embedded images/multimedia files if HTML file" checkbox was
10293: checked.
10294: 
10295: Clean-up is similar to replacements in lonnet::clean_filename()
10296: except each / between sub-directory and next level is preserved.
10297: 
10298: =cut
10299: 
10300: sub clean_path {
10301:     my ($embed_file) = @_;
10302:     $embed_file =~s{^/+}{};
10303:     my @contents;
10304:     if ($embed_file =~ m{/}) {
10305:         @contents = split(/\//,$embed_file);
10306:     } else {
10307:         @contents = ($embed_file);
10308:     }
10309:     my $lastidx = scalar(@contents)-1;
10310:     for (my $i=0; $i<=$lastidx; $i++) { 
10311:         $contents[$i]=~s{\\}{/}g;
10312:         $contents[$i]=~s/\s+/\_/g;
10313:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10314:         if ($i == $lastidx) {
10315:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10316:         }
10317:     }
10318:     if ($lastidx > 0) {
10319:         return join('/',@contents);
10320:     } else {
10321:         return $contents[0];
10322:     }
10323: }
10324: 
10325: sub embedded_file_element {
10326:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10327:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10328:                    (ref($codebase) eq 'HASH'));
10329:     my $output;
10330:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10331:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10332:     }
10333:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10334:                &escape($embed_file).'" />';
10335:     unless (($context eq 'upload_embedded') && 
10336:             ($mapping->{$embed_file} eq $embed_file)) {
10337:         $output .='
10338:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10339:     }
10340:     my $attrib;
10341:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10342:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10343:     }
10344:     $output .=
10345:         "\n\t\t".
10346:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10347:         $attrib.'" />';
10348:     if (exists($codebase->{$mapping->{$embed_file}})) {
10349:         $output .=
10350:             "\n\t\t".
10351:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10352:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10353:     }
10354:     return $output;
10355: }
10356: 
10357: sub get_dependency_details {
10358:     my ($currfile,$currsubfile,$embed_file) = @_;
10359:     my ($size,$mtime,$showsize,$showmtime);
10360:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10361:         if ($embed_file =~ m{/}) {
10362:             my ($path,$fname) = split(/\//,$embed_file);
10363:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10364:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10365:             }
10366:         } else {
10367:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10368:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10369:             }
10370:         }
10371:         $showsize = $size/1024.0;
10372:         $showsize = sprintf("%.1f",$showsize);
10373:         if ($mtime > 0) {
10374:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10375:         }
10376:     }
10377:     return ($showsize,$showmtime);
10378: }
10379: 
10380: sub ask_embedded_js {
10381:     return <<"END";
10382: <script type="text/javascript"">
10383: // <![CDATA[
10384: function toggleBrowse(counter) {
10385:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10386:     var fileid = document.getElementById('embedded_item_'+counter);
10387:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10388:     if (chkboxid.checked == true) {
10389:         uploaddivid.style.display='block';
10390:     } else {
10391:         uploaddivid.style.display='none';
10392:         fileid.value = '';
10393:     }
10394: }
10395: // ]]>
10396: </script>
10397: 
10398: END
10399: }
10400: 
10401: sub upload_embedded {
10402:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10403:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10404:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10405:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10406:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10407:         my $orig_uploaded_filename =
10408:             $env{'form.embedded_item_'.$i.'.filename'};
10409:         foreach my $type ('orig','ref','attrib','codebase') {
10410:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10411:                 $env{'form.embedded_'.$type.'_'.$i} =
10412:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10413:             }
10414:         }
10415:         my ($path,$fname) =
10416:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10417:         # no path, whole string is fname
10418:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10419:         $fname = &Apache::lonnet::clean_filename($fname);
10420:         # See if there is anything left
10421:         next if ($fname eq '');
10422: 
10423:         # Check if file already exists as a file or directory.
10424:         my ($state,$msg);
10425:         if ($context eq 'portfolio') {
10426:             my $port_path = $dirpath;
10427:             if ($group ne '') {
10428:                 $port_path = "groups/$group/$port_path";
10429:             }
10430:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10431:                                               $fname,$group,'embedded_item_'.$i,
10432:                                               $dir_root,$port_path,$disk_quota,
10433:                                               $current_disk_usage,$uname,$udom);
10434:             if ($state eq 'will_exceed_quota'
10435:                 || $state eq 'file_locked') {
10436:                 $output .= $msg;
10437:                 next;
10438:             }
10439:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10440:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10441:             if ($state eq 'exists') {
10442:                 $output .= $msg;
10443:                 next;
10444:             }
10445:         }
10446:         # Check if extension is valid
10447:         if (($fname =~ /\.(\w+)$/) &&
10448:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10449:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10450:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10451:             next;
10452:         } elsif (($fname =~ /\.(\w+)$/) &&
10453:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10454:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10455:             next;
10456:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10457:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10458:             next;
10459:         }
10460:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10461:         my $subdir = $path;
10462:         $subdir =~ s{/+$}{};
10463:         if ($context eq 'portfolio') {
10464:             my $result;
10465:             if ($state eq 'existingfile') {
10466:                 $result=
10467:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10468:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10469:             } else {
10470:                 $result=
10471:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10472:                                                     $dirpath.
10473:                                                     $env{'form.currentpath'}.$subdir);
10474:                 if ($result !~ m|^/uploaded/|) {
10475:                     $output .= '<span class="LC_error">'
10476:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10477:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10478:                                .'</span><br />';
10479:                     next;
10480:                 } else {
10481:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10482:                                $path.$fname.'</span>').'<br />';     
10483:                 }
10484:             }
10485:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10486:             my $extendedsubdir = $dirpath.'/'.$subdir;
10487:             $extendedsubdir =~ s{/+$}{};
10488:             my $result =
10489:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10490:             if ($result !~ m|^/uploaded/|) {
10491:                 $output .= '<span class="LC_error">'
10492:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10493:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10494:                            .'</span><br />';
10495:                     next;
10496:             } else {
10497:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10498:                            $path.$fname.'</span>').'<br />';
10499:                 if ($context eq 'syllabus') {
10500:                     &Apache::lonnet::make_public_indefinitely($result);
10501:                 }
10502:             }
10503:         } else {
10504: # Save the file
10505:             my $target = $env{'form.embedded_item_'.$i};
10506:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10507:             my $dest = $fullpath.$fname;
10508:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10509:             my @parts=split(/\//,"$dirpath/$path");
10510:             my $count;
10511:             my $filepath = $dir_root;
10512:             foreach my $subdir (@parts) {
10513:                 $filepath .= "/$subdir";
10514:                 if (!-e $filepath) {
10515:                     mkdir($filepath,0770);
10516:                 }
10517:             }
10518:             my $fh;
10519:             if (!open($fh,'>'.$dest)) {
10520:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10521:                 $output .= '<span class="LC_error">'.
10522:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10523:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10524:                            '</span><br />';
10525:             } else {
10526:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10527:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10528:                     $output .= '<span class="LC_error">'.
10529:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10530:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10531:                               '</span><br />';
10532:                 } else {
10533:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10534:                                $url.'</span>').'<br />';
10535:                     unless ($context eq 'testbank') {
10536:                         $footer .= &mt('View embedded file: [_1]',
10537:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10538:                     }
10539:                 }
10540:                 close($fh);
10541:             }
10542:         }
10543:         if ($env{'form.embedded_ref_'.$i}) {
10544:             $pathchange{$i} = 1;
10545:         }
10546:     }
10547:     if ($output) {
10548:         $output = '<p>'.$output.'</p>';
10549:     }
10550:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10551:     $returnflag = 'ok';
10552:     my $numpathchgs = scalar(keys(%pathchange));
10553:     if ($numpathchgs > 0) {
10554:         if ($context eq 'portfolio') {
10555:             $output .= '<p>'.&mt('or').'</p>';
10556:         } elsif ($context eq 'testbank') {
10557:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10558:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10559:             $returnflag = 'modify_orightml';
10560:         }
10561:     }
10562:     return ($output.$footer,$returnflag,$numpathchgs);
10563: }
10564: 
10565: sub modify_html_form {
10566:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10567:     my $end = 0;
10568:     my $modifyform;
10569:     if ($context eq 'upload_embedded') {
10570:         return unless (ref($pathchange) eq 'HASH');
10571:         if ($env{'form.number_embedded_items'}) {
10572:             $end += $env{'form.number_embedded_items'};
10573:         }
10574:         if ($env{'form.number_pathchange_items'}) {
10575:             $end += $env{'form.number_pathchange_items'};
10576:         }
10577:         if ($end) {
10578:             for (my $i=0; $i<$end; $i++) {
10579:                 if ($i < $env{'form.number_embedded_items'}) {
10580:                     next unless($pathchange->{$i});
10581:                 }
10582:                 $modifyform .=
10583:                     &start_data_table_row().
10584:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10585:                     'checked="checked" /></td>'.
10586:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10587:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10588:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10589:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10590:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10591:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10592:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10593:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10594:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10595:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10596:                     &end_data_table_row();
10597:             }
10598:         }
10599:     } else {
10600:         $modifyform = $pathchgtable;
10601:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10602:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10603:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10604:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10605:         }
10606:     }
10607:     if ($modifyform) {
10608:         if ($actionurl eq '/adm/dependencies') {
10609:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10610:         }
10611:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10612:                '<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".
10613:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10614:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10615:                '</ol></p>'."\n".'<p>'.
10616:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10617:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10618:                &start_data_table()."\n".
10619:                &start_data_table_header_row().
10620:                '<th>'.&mt('Change?').'</th>'.
10621:                '<th>'.&mt('Current reference').'</th>'.
10622:                '<th>'.&mt('Required reference').'</th>'.
10623:                &end_data_table_header_row()."\n".
10624:                $modifyform.
10625:                &end_data_table().'<br />'."\n".$hiddenstate.
10626:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10627:                '</form>'."\n";
10628:     }
10629:     return;
10630: }
10631: 
10632: sub modify_html_refs {
10633:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10634:     my $container;
10635:     if ($context eq 'portfolio') {
10636:         $container = $env{'form.container'};
10637:     } elsif ($context eq 'coursedoc') {
10638:         $container = $env{'form.primaryurl'};
10639:     } elsif ($context eq 'manage_dependencies') {
10640:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10641:         $container = "/$container";
10642:     } elsif ($context eq 'syllabus') {
10643:         $container = $url;
10644:     } else {
10645:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10646:     }
10647:     my (%allfiles,%codebase,$output,$content);
10648:     my @changes = &get_env_multiple('form.namechange');
10649:     unless ((@changes > 0) || ($context eq 'syllabus')) {
10650:         if (wantarray) {
10651:             return ('',0,0); 
10652:         } else {
10653:             return;
10654:         }
10655:     }
10656:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10657:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10658:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10659:             if (wantarray) {
10660:                 return ('',0,0);
10661:             } else {
10662:                 return;
10663:             }
10664:         } 
10665:         $content = &Apache::lonnet::getfile($container);
10666:         if ($content eq '-1') {
10667:             if (wantarray) {
10668:                 return ('',0,0);
10669:             } else {
10670:                 return;
10671:             }
10672:         }
10673:     } else {
10674:         unless ($container =~ /^\Q$dir_root\E/) {
10675:             if (wantarray) {
10676:                 return ('',0,0);
10677:             } else {
10678:                 return;
10679:             }
10680:         } 
10681:         if (open(my $fh,"<$container")) {
10682:             $content = join('', <$fh>);
10683:             close($fh);
10684:         } else {
10685:             if (wantarray) {
10686:                 return ('',0,0);
10687:             } else {
10688:                 return;
10689:             }
10690:         }
10691:     }
10692:     my ($count,$codebasecount) = (0,0);
10693:     my $mm = new File::MMagic;
10694:     my $mime_type = $mm->checktype_contents($content);
10695:     if ($mime_type eq 'text/html') {
10696:         my $parse_result = 
10697:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10698:                                                     \%codebase,\$content);
10699:         if ($parse_result eq 'ok') {
10700:             foreach my $i (@changes) {
10701:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10702:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10703:                 if ($allfiles{$ref}) {
10704:                     my $newname =  $orig;
10705:                     my ($attrib_regexp,$codebase);
10706:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10707:                     if ($attrib_regexp =~ /:/) {
10708:                         $attrib_regexp =~ s/\:/|/g;
10709:                     }
10710:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10711:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10712:                         $count += $numchg;
10713:                         $allfiles{$newname} = $allfiles{$ref};
10714:                         delete($allfiles{$ref});
10715:                     }
10716:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10717:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10718:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10719:                         $codebasecount ++;
10720:                     }
10721:                 }
10722:             }
10723:             my $skiprewrites;
10724:             if ($count || $codebasecount) {
10725:                 my $saveresult;
10726:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10727:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10728:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10729:                     if ($url eq $container) {
10730:                         my ($fname) = ($container =~ m{/([^/]+)$});
10731:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10732:                                             $count,'<span class="LC_filename">'.
10733:                                             $fname.'</span>').'</p>';
10734:                     } else {
10735:                          $output = '<p class="LC_error">'.
10736:                                    &mt('Error: update failed for: [_1].',
10737:                                    '<span class="LC_filename">'.
10738:                                    $container.'</span>').'</p>';
10739:                     }
10740:                     if ($context eq 'syllabus') {
10741:                         unless ($saveresult eq 'ok') {
10742:                             $skiprewrites = 1;
10743:                         }
10744:                     }
10745:                 } else {
10746:                     if (open(my $fh,">$container")) {
10747:                         print $fh $content;
10748:                         close($fh);
10749:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10750:                                   $count,'<span class="LC_filename">'.
10751:                                   $container.'</span>').'</p>';
10752:                     } else {
10753:                          $output = '<p class="LC_error">'.
10754:                                    &mt('Error: could not update [_1].',
10755:                                    '<span class="LC_filename">'.
10756:                                    $container.'</span>').'</p>';
10757:                     }
10758:                 }
10759:             }
10760:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10761:                 my ($actionurl,$state);
10762:                 $actionurl = "/public/$udom/$uname/syllabus";
10763:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10764:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10765:                                               \%codebase,
10766:                                               {'context' => 'rewrites',
10767:                                                'ignore_remote_references' => 1,});
10768:                 if (ref($mapping) eq 'HASH') {
10769:                     my $rewrites = 0;
10770:                     foreach my $key (keys(%{$mapping})) {
10771:                         next if ($key =~ m{^https?://});
10772:                         my $ref = $mapping->{$key};
10773:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10774:                         my $attrib;
10775:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10776:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10777:                         }
10778:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10779:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10780:                             $rewrites += $numchg;
10781:                         }
10782:                     }
10783:                     if ($rewrites) {
10784:                         my $saveresult; 
10785:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10786:                         if ($url eq $container) {
10787:                             my ($fname) = ($container =~ m{/([^/]+)$});
10788:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10789:                                             $count,'<span class="LC_filename">'.
10790:                                             $fname.'</span>').'</p>';
10791:                         } else {
10792:                             $output .= '<p class="LC_error">'.
10793:                                        &mt('Error: could not update links in [_1].',
10794:                                        '<span class="LC_filename">'.
10795:                                        $container.'</span>').'</p>';
10796: 
10797:                         }
10798:                     }
10799:                 }
10800:             }
10801:         } else {
10802:             &logthis('Failed to parse '.$container.
10803:                      ' to modify references: '.$parse_result);
10804:         }
10805:     }
10806:     if (wantarray) {
10807:         return ($output,$count,$codebasecount);
10808:     } else {
10809:         return $output;
10810:     }
10811: }
10812: 
10813: sub check_for_existing {
10814:     my ($path,$fname,$element) = @_;
10815:     my ($state,$msg);
10816:     if (-d $path.'/'.$fname) {
10817:         $state = 'exists';
10818:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10819:     } elsif (-e $path.'/'.$fname) {
10820:         $state = 'exists';
10821:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10822:     }
10823:     if ($state eq 'exists') {
10824:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10825:     }
10826:     return ($state,$msg);
10827: }
10828: 
10829: sub check_for_upload {
10830:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10831:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10832:     my $filesize = length($env{'form.'.$element});
10833:     if (!$filesize) {
10834:         my $msg = '<span class="LC_error">'.
10835:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10836:                       '<span class="LC_filename">'.$fname.'</span>',
10837:                       $filesize).'<br />'.
10838:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10839:                   '</span>';
10840:         return ('zero_bytes',$msg);
10841:     }
10842:     $filesize =  $filesize/1000; #express in k (1024?)
10843:     my $getpropath = 1;
10844:     my ($dirlistref,$listerror) =
10845:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10846:     my $found_file = 0;
10847:     my $locked_file = 0;
10848:     my @lockers;
10849:     my $navmap;
10850:     if ($env{'request.course.id'}) {
10851:         $navmap = Apache::lonnavmaps::navmap->new();
10852:     }
10853:     if (ref($dirlistref) eq 'ARRAY') {
10854:         foreach my $line (@{$dirlistref}) {
10855:             my ($file_name,$rest)=split(/\&/,$line,2);
10856:             if ($file_name eq $fname){
10857:                 $file_name = $path.$file_name;
10858:                 if ($group ne '') {
10859:                     $file_name = $group.$file_name;
10860:                 }
10861:                 $found_file = 1;
10862:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10863:                     foreach my $lock (@lockers) {
10864:                         if (ref($lock) eq 'ARRAY') {
10865:                             my ($symb,$crsid) = @{$lock};
10866:                             if ($crsid eq $env{'request.course.id'}) {
10867:                                 if (ref($navmap)) {
10868:                                     my $res = $navmap->getBySymb($symb);
10869:                                     foreach my $part (@{$res->parts()}) { 
10870:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10871:                                         unless (($slot_status == $res->RESERVED) ||
10872:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10873:                                             $locked_file = 1;
10874:                                         }
10875:                                     }
10876:                                 } else {
10877:                                     $locked_file = 1;
10878:                                 }
10879:                             } else {
10880:                                 $locked_file = 1;
10881:                             }
10882:                         }
10883:                    }
10884:                 } else {
10885:                     my @info = split(/\&/,$rest);
10886:                     my $currsize = $info[6]/1000;
10887:                     if ($currsize < $filesize) {
10888:                         my $extra = $filesize - $currsize;
10889:                         if (($current_disk_usage + $extra) > $disk_quota) {
10890:                             my $msg = '<span class="LC_error">'.
10891:                                       &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.',
10892:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10893:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10894:                                                    $disk_quota,$current_disk_usage);
10895:                             return ('will_exceed_quota',$msg);
10896:                         }
10897:                     }
10898:                 }
10899:             }
10900:         }
10901:     }
10902:     if (($current_disk_usage + $filesize) > $disk_quota){
10903:         my $msg = '<span class="LC_error">'.
10904:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10905:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10906:         return ('will_exceed_quota',$msg);
10907:     } elsif ($found_file) {
10908:         if ($locked_file) {
10909:             my $msg = '<span class="LC_error">';
10910:             $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>');
10911:             $msg .= '</span><br />';
10912:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10913:             return ('file_locked',$msg);
10914:         } else {
10915:             my $msg = '<span class="LC_error">';
10916:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10917:             $msg .= '</span>';
10918:             return ('existingfile',$msg);
10919:         }
10920:     }
10921: }
10922: 
10923: sub check_for_traversal {
10924:     my ($path,$url,$toplevel) = @_;
10925:     my @parts=split(/\//,$path);
10926:     my $cleanpath;
10927:     my $fullpath = $url;
10928:     for (my $i=0;$i<@parts;$i++) {
10929:         next if ($parts[$i] eq '.');
10930:         if ($parts[$i] eq '..') {
10931:             $fullpath =~ s{([^/]+/)$}{};
10932:         } else {
10933:             $fullpath .= $parts[$i].'/';
10934:         }
10935:     }
10936:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10937:         $cleanpath = $1;
10938:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10939:         my $curr_toprel = $1;
10940:         my @parts = split(/\//,$curr_toprel);
10941:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10942:         my @urlparts = split(/\//,$url_toprel);
10943:         my $doubledots;
10944:         my $startdiff = -1;
10945:         for (my $i=0; $i<@urlparts; $i++) {
10946:             if ($startdiff == -1) {
10947:                 unless ($urlparts[$i] eq $parts[$i]) {
10948:                     $startdiff = $i;
10949:                     $doubledots .= '../';
10950:                 }
10951:             } else {
10952:                 $doubledots .= '../';
10953:             }
10954:         }
10955:         if ($startdiff > -1) {
10956:             $cleanpath = $doubledots;
10957:             for (my $i=$startdiff; $i<@parts; $i++) {
10958:                 $cleanpath .= $parts[$i].'/';
10959:             }
10960:         }
10961:     }
10962:     $cleanpath =~ s{(/)$}{};
10963:     return $cleanpath;
10964: }
10965: 
10966: sub is_archive_file {
10967:     my ($mimetype) = @_;
10968:     if (($mimetype eq 'application/octet-stream') ||
10969:         ($mimetype eq 'application/x-stuffit') ||
10970:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10971:         return 1;
10972:     }
10973:     return;
10974: }
10975: 
10976: sub decompress_form {
10977:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10978:     my %lt = &Apache::lonlocal::texthash (
10979:         this => 'This file is an archive file.',
10980:         camt => 'This file is a Camtasia archive file.',
10981:         itsc => 'Its contents are as follows:',
10982:         youm => 'You may wish to extract its contents.',
10983:         extr => 'Extract contents',
10984:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10985:         proa => 'Process automatically?',
10986:         yes  => 'Yes',
10987:         no   => 'No',
10988:         fold => 'Title for folder containing movie',
10989:         movi => 'Title for page containing embedded movie', 
10990:     );
10991:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10992:     my ($is_camtasia,$topdir,%toplevel,@paths);
10993:     my $info = &list_archive_contents($fileloc,\@paths);
10994:     if (@paths) {
10995:         foreach my $path (@paths) {
10996:             $path =~ s{^/}{};
10997:             if ($path =~ m{^([^/]+)/$}) {
10998:                 $topdir = $1;
10999:             }
11000:             if ($path =~ m{^([^/]+)/}) {
11001:                 $toplevel{$1} = $path;
11002:             } else {
11003:                 $toplevel{$path} = $path;
11004:             }
11005:         }
11006:     }
11007:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11008:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11009:                         "$topdir/media/",
11010:                         "$topdir/media/$topdir.mp4",
11011:                         "$topdir/media/FirstFrame.png",
11012:                         "$topdir/media/player.swf",
11013:                         "$topdir/media/swfobject.js",
11014:                         "$topdir/media/expressInstall.swf");
11015:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
11016:                          "$topdir/$topdir.mp4",
11017:                          "$topdir/$topdir\_config.xml",
11018:                          "$topdir/$topdir\_controller.swf",
11019:                          "$topdir/$topdir\_embed.css",
11020:                          "$topdir/$topdir\_First_Frame.png",
11021:                          "$topdir/$topdir\_player.html",
11022:                          "$topdir/$topdir\_Thumbnails.png",
11023:                          "$topdir/playerProductInstall.swf",
11024:                          "$topdir/scripts/",
11025:                          "$topdir/scripts/config_xml.js",
11026:                          "$topdir/scripts/handlebars.js",
11027:                          "$topdir/scripts/jquery-1.7.1.min.js",
11028:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11029:                          "$topdir/scripts/modernizr.js",
11030:                          "$topdir/scripts/player-min.js",
11031:                          "$topdir/scripts/swfobject.js",
11032:                          "$topdir/skins/",
11033:                          "$topdir/skins/configuration_express.xml",
11034:                          "$topdir/skins/express_show/",
11035:                          "$topdir/skins/express_show/player-min.css",
11036:                          "$topdir/skins/express_show/spritesheet.png");
11037:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11038:         if (@diffs == 0) {
11039:             $is_camtasia = 6;
11040:         } else {
11041:             @diffs = &compare_arrays(\@paths,\@camtasia8);
11042:             if (@diffs == 0) {
11043:                 $is_camtasia = 8;
11044:             }
11045:         }
11046:     }
11047:     my $output;
11048:     if ($is_camtasia) {
11049:         $output = <<"ENDCAM";
11050: <script type="text/javascript" language="Javascript">
11051: // <![CDATA[
11052: 
11053: function camtasiaToggle() {
11054:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11055:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11056:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11057: 
11058:                 document.getElementById('camtasia_titles').style.display='block';
11059:             } else {
11060:                 document.getElementById('camtasia_titles').style.display='none';
11061:             }
11062:         }
11063:     }
11064:     return;
11065: }
11066: 
11067: // ]]>
11068: </script>
11069: <p>$lt{'camt'}</p>
11070: ENDCAM
11071:     } else {
11072:         $output = '<p>'.$lt{'this'};
11073:         if ($info eq '') {
11074:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11075:         } else {
11076:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11077:                        '<div><pre>'.$info.'</pre></div>';
11078:         }
11079:     }
11080:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11081:     my $duplicates;
11082:     my $num = 0;
11083:     if (ref($dirlist) eq 'ARRAY') {
11084:         foreach my $item (@{$dirlist}) {
11085:             if (ref($item) eq 'ARRAY') {
11086:                 if (exists($toplevel{$item->[0]})) {
11087:                     $duplicates .= 
11088:                         &start_data_table_row().
11089:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11090:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11091:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11092:                         'value="1" />'.&mt('Yes').'</label>'.
11093:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11094:                         '<td>'.$item->[0].'</td>';
11095:                     if ($item->[2]) {
11096:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11097:                     } else {
11098:                         $duplicates .= '<td>'.&mt('File').'</td>';
11099:                     }
11100:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11101:                                    '<td>'.
11102:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11103:                                    '</td>'.
11104:                                    &end_data_table_row();
11105:                     $num ++;
11106:                 }
11107:             }
11108:         }
11109:     }
11110:     my $itemcount;
11111:     if (@paths > 0) {
11112:         $itemcount = scalar(@paths);
11113:     } else {
11114:         $itemcount = 1;
11115:     }
11116:     if ($is_camtasia) {
11117:         $output .= $lt{'auto'}.'<br />'.
11118:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11119:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11120:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11121:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11122:                    $lt{'no'}.'</label></span><br />'.
11123:                    '<div id="camtasia_titles" style="display:block">'.
11124:                    &Apache::lonhtmlcommon::start_pick_box().
11125:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11126:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11127:                    &Apache::lonhtmlcommon::row_closure().
11128:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11129:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11130:                    &Apache::lonhtmlcommon::row_closure(1).
11131:                    &Apache::lonhtmlcommon::end_pick_box().
11132:                    '</div>';
11133:     }
11134:     $output .= 
11135:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11136:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11137:         "\n";
11138:     if ($duplicates ne '') {
11139:         $output .= '<p><span class="LC_warning">'.
11140:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11141:                    &start_data_table().
11142:                    &start_data_table_header_row().
11143:                    '<th>'.&mt('Overwrite?').'</th>'.
11144:                    '<th>'.&mt('Name').'</th>'.
11145:                    '<th>'.&mt('Type').'</th>'.
11146:                    '<th>'.&mt('Size').'</th>'.
11147:                    '<th>'.&mt('Last modified').'</th>'.
11148:                    &end_data_table_header_row().
11149:                    $duplicates.
11150:                    &end_data_table().
11151:                    '</p>';
11152:     }
11153:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11154:     if (ref($hiddenelements) eq 'HASH') {
11155:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11156:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11157:         }
11158:     }
11159:     $output .= <<"END";
11160: <br />
11161: <input type="submit" name="decompress" value="$lt{'extr'}" />
11162: </form>
11163: $noextract
11164: END
11165:     return $output;
11166: }
11167: 
11168: sub decompression_utility {
11169:     my ($program) = @_;
11170:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11171:     my $location;
11172:     if (grep(/^\Q$program\E$/,@utilities)) { 
11173:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11174:                          '/usr/sbin/') {
11175:             if (-x $dir.$program) {
11176:                 $location = $dir.$program;
11177:                 last;
11178:             }
11179:         }
11180:     }
11181:     return $location;
11182: }
11183: 
11184: sub list_archive_contents {
11185:     my ($file,$pathsref) = @_;
11186:     my (@cmd,$output);
11187:     my $needsregexp;
11188:     if ($file =~ /\.zip$/) {
11189:         @cmd = (&decompression_utility('unzip'),"-l");
11190:         $needsregexp = 1;
11191:     } elsif (($file =~ m/\.tar\.gz$/) ||
11192:              ($file =~ /\.tgz$/)) {
11193:         @cmd = (&decompression_utility('tar'),"-ztf");
11194:     } elsif ($file =~ /\.tar\.bz2$/) {
11195:         @cmd = (&decompression_utility('tar'),"-jtf");
11196:     } elsif ($file =~ m|\.tar$|) {
11197:         @cmd = (&decompression_utility('tar'),"-tf");
11198:     }
11199:     if (@cmd) {
11200:         undef($!);
11201:         undef($@);
11202:         if (open(my $fh,"-|", @cmd, $file)) {
11203:             while (my $line = <$fh>) {
11204:                 $output .= $line;
11205:                 chomp($line);
11206:                 my $item;
11207:                 if ($needsregexp) {
11208:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11209:                 } else {
11210:                     $item = $line;
11211:                 }
11212:                 if ($item ne '') {
11213:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11214:                         push(@{$pathsref},$item);
11215:                     } 
11216:                 }
11217:             }
11218:             close($fh);
11219:         }
11220:     }
11221:     return $output;
11222: }
11223: 
11224: sub decompress_uploaded_file {
11225:     my ($file,$dir) = @_;
11226:     &Apache::lonnet::appenv({'cgi.file' => $file});
11227:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11228:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11229:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11230:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11231:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11232:     my $decompressed = $env{'cgi.decompressed'};
11233:     &Apache::lonnet::delenv('cgi.file');
11234:     &Apache::lonnet::delenv('cgi.dir');
11235:     &Apache::lonnet::delenv('cgi.decompressed');
11236:     return ($decompressed,$result);
11237: }
11238: 
11239: sub process_decompression {
11240:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11241:     my ($dir,$error,$warning,$output);
11242:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11243:         $error = &mt('Filename not a supported archive file type.').
11244:                  '<br />'.&mt('Filename should end with one of: [_1].',
11245:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11246:     } else {
11247:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11248:         if ($docuhome eq 'no_host') {
11249:             $error = &mt('Could not determine home server for course.');
11250:         } else {
11251:             my @ids=&Apache::lonnet::current_machine_ids();
11252:             my $currdir = "$dir_root/$destination";
11253:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11254:                 $dir = &LONCAPA::propath($docudom,$docuname).
11255:                        "$dir_root/$destination";
11256:             } else {
11257:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11258:                        "$dir_root/$docudom/$docuname/$destination";
11259:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11260:                     $error = &mt('Archive file not found.');
11261:                 }
11262:             }
11263:             my (@to_overwrite,@to_skip);
11264:             if ($env{'form.archive_overwrite_total'} > 0) {
11265:                 my $total = $env{'form.archive_overwrite_total'};
11266:                 for (my $i=0; $i<$total; $i++) {
11267:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11268:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11269:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11270:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11271:                     }
11272:                 }
11273:             }
11274:             my $numskip = scalar(@to_skip);
11275:             if (($numskip > 0) && 
11276:                 ($numskip == $env{'form.archive_itemcount'})) {
11277:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11278:             } elsif ($dir eq '') {
11279:                 $error = &mt('Directory containing archive file unavailable.');
11280:             } elsif (!$error) {
11281:                 my ($decompressed,$display);
11282:                 if ($numskip > 0) {
11283:                     my $tempdir = time.'_'.$$.int(rand(10000));
11284:                     mkdir("$dir/$tempdir",0755);
11285:                     system("mv $dir/$file $dir/$tempdir/$file");
11286:                     ($decompressed,$display) = 
11287:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11288:                     foreach my $item (@to_skip) {
11289:                         if (($item ne '') && ($item !~ /\.\./)) {
11290:                             if (-f "$dir/$tempdir/$item") { 
11291:                                 unlink("$dir/$tempdir/$item");
11292:                             } elsif (-d "$dir/$tempdir/$item") {
11293:                                 system("rm -rf $dir/$tempdir/$item");
11294:                             }
11295:                         }
11296:                     }
11297:                     system("mv $dir/$tempdir/* $dir");
11298:                     rmdir("$dir/$tempdir");   
11299:                 } else {
11300:                     ($decompressed,$display) = 
11301:                         &decompress_uploaded_file($file,$dir);
11302:                 }
11303:                 if ($decompressed eq 'ok') {
11304:                     $output = '<p class="LC_info">'.
11305:                               &mt('Files extracted successfully from archive.').
11306:                               '</p>'."\n";
11307:                     my ($warning,$result,@contents);
11308:                     my ($newdirlistref,$newlisterror) =
11309:                         &Apache::lonnet::dirlist($currdir,$docudom,
11310:                                                  $docuname,1);
11311:                     my (%is_dir,%changes,@newitems);
11312:                     my $dirptr = 16384;
11313:                     if (ref($newdirlistref) eq 'ARRAY') {
11314:                         foreach my $dir_line (@{$newdirlistref}) {
11315:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11316:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11317:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11318:                                 push(@newitems,$item);
11319:                                 if ($dirptr&$testdir) {
11320:                                     $is_dir{$item} = 1;
11321:                                 }
11322:                                 $changes{$item} = 1;
11323:                             }
11324:                         }
11325:                     }
11326:                     if (keys(%changes) > 0) {
11327:                         foreach my $item (sort(@newitems)) {
11328:                             if ($changes{$item}) {
11329:                                 push(@contents,$item);
11330:                             }
11331:                         }
11332:                     }
11333:                     if (@contents > 0) {
11334:                         my $wantform;
11335:                         unless ($env{'form.autoextract_camtasia'}) {
11336:                             $wantform = 1;
11337:                         }
11338:                         my (%children,%parent,%dirorder,%titles);
11339:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11340:                                                                 $currdir,\%is_dir,
11341:                                                                 \%children,\%parent,
11342:                                                                 \@contents,\%dirorder,
11343:                                                                 \%titles,$wantform);
11344:                         if ($datatable ne '') {
11345:                             $output .= &archive_options_form('decompressed',$datatable,
11346:                                                              $count,$hiddenelem);
11347:                             my $startcount = 6;
11348:                             $output .= &archive_javascript($startcount,$count,
11349:                                                            \%titles,\%children);
11350:                         }
11351:                         if ($env{'form.autoextract_camtasia'}) {
11352:                             my $version = $env{'form.autoextract_camtasia'};
11353:                             my %displayed;
11354:                             my $total = 1;
11355:                             $env{'form.archive_directory'} = [];
11356:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11357:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11358:                                 $path =~ s{/$}{};
11359:                                 my $item;
11360:                                 if ($path ne '') {
11361:                                     $item = "$path/$titles{$i}";
11362:                                 } else {
11363:                                     $item = $titles{$i};
11364:                                 }
11365:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11366:                                 if ($item eq $contents[0]) {
11367:                                     push(@{$env{'form.archive_directory'}},$i);
11368:                                     $env{'form.archive_'.$i} = 'display';
11369:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11370:                                     $displayed{'folder'} = $i;
11371:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11372:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
11373:                                     $env{'form.archive_'.$i} = 'display';
11374:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11375:                                     $displayed{'web'} = $i;
11376:                                 } else {
11377:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11378:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11379:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11380:                                         push(@{$env{'form.archive_directory'}},$i);
11381:                                     }
11382:                                     $env{'form.archive_'.$i} = 'dependency';
11383:                                 }
11384:                                 $total ++;
11385:                             }
11386:                             for (my $i=1; $i<$total; $i++) {
11387:                                 next if ($i == $displayed{'web'});
11388:                                 next if ($i == $displayed{'folder'});
11389:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11390:                             }
11391:                             $env{'form.phase'} = 'decompress_cleanup';
11392:                             $env{'form.archivedelete'} = 1;
11393:                             $env{'form.archive_count'} = $total-1;
11394:                             $output .=
11395:                                 &process_extracted_files('coursedocs',$docudom,
11396:                                                          $docuname,$destination,
11397:                                                          $dir_root,$hiddenelem);
11398:                         }
11399:                     } else {
11400:                         $warning = &mt('No new items extracted from archive file.');
11401:                     }
11402:                 } else {
11403:                     $output = $display;
11404:                     $error = &mt('An error occurred during extraction from the archive file.');
11405:                 }
11406:             }
11407:         }
11408:     }
11409:     if ($error) {
11410:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11411:                    $error.'</p>'."\n";
11412:     }
11413:     if ($warning) {
11414:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11415:     }
11416:     return $output;
11417: }
11418: 
11419: sub get_extracted {
11420:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11421:         $titles,$wantform) = @_;
11422:     my $count = 0;
11423:     my $depth = 0;
11424:     my $datatable;
11425:     my @hierarchy;
11426:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11427:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11428:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11429:     foreach my $item (@{$contents}) {
11430:         $count ++;
11431:         @{$dirorder->{$count}} = @hierarchy;
11432:         $titles->{$count} = $item;
11433:         &archive_hierarchy($depth,$count,$parent,$children);
11434:         if ($wantform) {
11435:             $datatable .= &archive_row($is_dir->{$item},$item,
11436:                                        $currdir,$depth,$count);
11437:         }
11438:         if ($is_dir->{$item}) {
11439:             $depth ++;
11440:             push(@hierarchy,$count);
11441:             $parent->{$depth} = $count;
11442:             $datatable .=
11443:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11444:                                            \$depth,\$count,\@hierarchy,$dirorder,
11445:                                            $children,$parent,$titles,$wantform);
11446:             $depth --;
11447:             pop(@hierarchy);
11448:         }
11449:     }
11450:     return ($count,$datatable);
11451: }
11452: 
11453: sub recurse_extracted_archive {
11454:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11455:         $children,$parent,$titles,$wantform) = @_;
11456:     my $result='';
11457:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11458:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11459:             (ref($dirorder) eq 'HASH')) {
11460:         return $result;
11461:     }
11462:     my $dirptr = 16384;
11463:     my ($newdirlistref,$newlisterror) =
11464:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11465:     if (ref($newdirlistref) eq 'ARRAY') {
11466:         foreach my $dir_line (@{$newdirlistref}) {
11467:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11468:             unless ($item =~ /^\.+$/) {
11469:                 $$count ++;
11470:                 @{$dirorder->{$$count}} = @{$hierarchy};
11471:                 $titles->{$$count} = $item;
11472:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11473: 
11474:                 my $is_dir;
11475:                 if ($dirptr&$testdir) {
11476:                     $is_dir = 1;
11477:                 }
11478:                 if ($wantform) {
11479:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11480:                 }
11481:                 if ($is_dir) {
11482:                     $$depth ++;
11483:                     push(@{$hierarchy},$$count);
11484:                     $parent->{$$depth} = $$count;
11485:                     $result .=
11486:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11487:                                                    $docuname,$depth,$count,
11488:                                                    $hierarchy,$dirorder,$children,
11489:                                                    $parent,$titles,$wantform);
11490:                     $$depth --;
11491:                     pop(@{$hierarchy});
11492:                 }
11493:             }
11494:         }
11495:     }
11496:     return $result;
11497: }
11498: 
11499: sub archive_hierarchy {
11500:     my ($depth,$count,$parent,$children) =@_;
11501:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11502:         if (exists($parent->{$depth})) {
11503:              $children->{$parent->{$depth}} .= $count.':';
11504:         }
11505:     }
11506:     return;
11507: }
11508: 
11509: sub archive_row {
11510:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11511:     my ($name) = ($item =~ m{([^/]+)$});
11512:     my %choices = &Apache::lonlocal::texthash (
11513:                                        'display'    => 'Add as file',
11514:                                        'dependency' => 'Include as dependency',
11515:                                        'discard'    => 'Discard',
11516:                                       );
11517:     if ($is_dir) {
11518:         $choices{'display'} = &mt('Add as folder'); 
11519:     }
11520:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11521:     my $offset = 0;
11522:     foreach my $action ('display','dependency','discard') {
11523:         $offset ++;
11524:         if ($action ne 'display') {
11525:             $offset ++;
11526:         }  
11527:         $output .= '<td><span class="LC_nobreak">'.
11528:                    '<label><input type="radio" name="archive_'.$count.
11529:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11530:         my $text = $choices{$action};
11531:         if ($is_dir) {
11532:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11533:             if ($action eq 'display') {
11534:                 $text = &mt('Add as folder');
11535:             }
11536:         } else {
11537:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11538: 
11539:         }
11540:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11541:         if ($action eq 'dependency') {
11542:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11543:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11544:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11545:                        '<option value=""></option>'."\n".
11546:                        '</select>'."\n".
11547:                        '</div>';
11548:         } elsif ($action eq 'display') {
11549:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11550:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11551:                        '</div>';
11552:         }
11553:         $output .= '</td>';
11554:     }
11555:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11556:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11557:     for (my $i=0; $i<$depth; $i++) {
11558:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11559:     }
11560:     if ($is_dir) {
11561:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11562:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11563:     } else {
11564:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11565:     }
11566:     $output .= '&nbsp;'.$name.'</td>'."\n".
11567:                &end_data_table_row();
11568:     return $output;
11569: }
11570: 
11571: sub archive_options_form {
11572:     my ($form,$display,$count,$hiddenelem) = @_;
11573:     my %lt = &Apache::lonlocal::texthash(
11574:                perm => 'Permanently remove archive file?',
11575:                hows => 'How should each extracted item be incorporated in the course?',
11576:                cont => 'Content actions for all',
11577:                addf => 'Add as folder/file',
11578:                incd => 'Include as dependency for a displayed file',
11579:                disc => 'Discard',
11580:                no   => 'No',
11581:                yes  => 'Yes',
11582:                save => 'Save',
11583:     );
11584:     my $output = <<"END";
11585: <form name="$form" method="post" action="">
11586: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11587: <label>
11588:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11589: </label>
11590: &nbsp;
11591: <label>
11592:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11593: </span>
11594: </p>
11595: <input type="hidden" name="phase" value="decompress_cleanup" />
11596: <br />$lt{'hows'}
11597: <div class="LC_columnSection">
11598:   <fieldset>
11599:     <legend>$lt{'cont'}</legend>
11600:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11601:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11602:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11603:   </fieldset>
11604: </div>
11605: END
11606:     return $output.
11607:            &start_data_table()."\n".
11608:            $display."\n".
11609:            &end_data_table()."\n".
11610:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11611:            $hiddenelem.
11612:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11613:            '</form>';
11614: }
11615: 
11616: sub archive_javascript {
11617:     my ($startcount,$numitems,$titles,$children) = @_;
11618:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11619:     my $maintitle = $env{'form.comment'};
11620:     my $scripttag = <<START;
11621: <script type="text/javascript">
11622: // <![CDATA[
11623: 
11624: function checkAll(form,prefix) {
11625:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11626:     for (var i=0; i < form.elements.length; i++) {
11627:         var id = form.elements[i].id;
11628:         if ((id != '') && (id != undefined)) {
11629:             if (idstr.test(id)) {
11630:                 if (form.elements[i].type == 'radio') {
11631:                     form.elements[i].checked = true;
11632:                     var nostart = i-$startcount;
11633:                     var offset = nostart%7;
11634:                     var count = (nostart-offset)/7;    
11635:                     dependencyCheck(form,count,offset);
11636:                 }
11637:             }
11638:         }
11639:     }
11640: }
11641: 
11642: function propagateCheck(form,count) {
11643:     if (count > 0) {
11644:         var startelement = $startcount + ((count-1) * 7);
11645:         for (var j=1; j<6; j++) {
11646:             if ((j != 2) && (j != 4)) {
11647:                 var item = startelement + j; 
11648:                 if (form.elements[item].type == 'radio') {
11649:                     if (form.elements[item].checked) {
11650:                         containerCheck(form,count,j);
11651:                         break;
11652:                     }
11653:                 }
11654:             }
11655:         }
11656:     }
11657: }
11658: 
11659: numitems = $numitems
11660: var titles = new Array(numitems);
11661: var parents = new Array(numitems);
11662: for (var i=0; i<numitems; i++) {
11663:     parents[i] = new Array;
11664: }
11665: var maintitle = '$maintitle';
11666: 
11667: START
11668: 
11669:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11670:         my @contents = split(/:/,$children->{$container});
11671:         for (my $i=0; $i<@contents; $i ++) {
11672:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11673:         }
11674:     }
11675: 
11676:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11677:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11678:     }
11679: 
11680:     $scripttag .= <<END;
11681: 
11682: function containerCheck(form,count,offset) {
11683:     if (count > 0) {
11684:         dependencyCheck(form,count,offset);
11685:         var item = (offset+$startcount)+7*(count-1);
11686:         form.elements[item].checked = true;
11687:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11688:             if (parents[count].length > 0) {
11689:                 for (var j=0; j<parents[count].length; j++) {
11690:                     containerCheck(form,parents[count][j],offset);
11691:                 }
11692:             }
11693:         }
11694:     }
11695: }
11696: 
11697: function dependencyCheck(form,count,offset) {
11698:     if (count > 0) {
11699:         var chosen = (offset+$startcount)+7*(count-1);
11700:         var depitem = $startcount + ((count-1) * 7) + 4;
11701:         var currtype = form.elements[depitem].type;
11702:         if (form.elements[chosen].value == 'dependency') {
11703:             document.getElementById('arc_depon_'+count).style.display='block'; 
11704:             form.elements[depitem].options.length = 0;
11705:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11706:             for (var i=1; i<=numitems; i++) {
11707:                 if (i == count) {
11708:                     continue;
11709:                 }
11710:                 var startelement = $startcount + (i-1) * 7;
11711:                 for (var j=1; j<6; j++) {
11712:                     if ((j != 2) && (j!= 4)) {
11713:                         var item = startelement + j;
11714:                         if (form.elements[item].type == 'radio') {
11715:                             if (form.elements[item].checked) {
11716:                                 if (form.elements[item].value == 'display') {
11717:                                     var n = form.elements[depitem].options.length;
11718:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11719:                                 }
11720:                             }
11721:                         }
11722:                     }
11723:                 }
11724:             }
11725:         } else {
11726:             document.getElementById('arc_depon_'+count).style.display='none';
11727:             form.elements[depitem].options.length = 0;
11728:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11729:         }
11730:         titleCheck(form,count,offset);
11731:     }
11732: }
11733: 
11734: function propagateSelect(form,count,offset) {
11735:     if (count > 0) {
11736:         var item = (1+offset+$startcount)+7*(count-1);
11737:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11738:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11739:             if (parents[count].length > 0) {
11740:                 for (var j=0; j<parents[count].length; j++) {
11741:                     containerSelect(form,parents[count][j],offset,picked);
11742:                 }
11743:             }
11744:         }
11745:     }
11746: }
11747: 
11748: function containerSelect(form,count,offset,picked) {
11749:     if (count > 0) {
11750:         var item = (offset+$startcount)+7*(count-1);
11751:         if (form.elements[item].type == 'radio') {
11752:             if (form.elements[item].value == 'dependency') {
11753:                 if (form.elements[item+1].type == 'select-one') {
11754:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11755:                         if (form.elements[item+1].options[i].value == picked) {
11756:                             form.elements[item+1].selectedIndex = i;
11757:                             break;
11758:                         }
11759:                     }
11760:                 }
11761:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11762:                     if (parents[count].length > 0) {
11763:                         for (var j=0; j<parents[count].length; j++) {
11764:                             containerSelect(form,parents[count][j],offset,picked);
11765:                         }
11766:                     }
11767:                 }
11768:             }
11769:         }
11770:     }
11771: }
11772: 
11773: function titleCheck(form,count,offset) {
11774:     if (count > 0) {
11775:         var chosen = (offset+$startcount)+7*(count-1);
11776:         var depitem = $startcount + ((count-1) * 7) + 2;
11777:         var currtype = form.elements[depitem].type;
11778:         if (form.elements[chosen].value == 'display') {
11779:             document.getElementById('arc_title_'+count).style.display='block';
11780:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11781:                 document.getElementById('archive_title_'+count).value=maintitle;
11782:             }
11783:         } else {
11784:             document.getElementById('arc_title_'+count).style.display='none';
11785:             if (currtype == 'text') { 
11786:                 document.getElementById('archive_title_'+count).value='';
11787:             }
11788:         }
11789:     }
11790:     return;
11791: }
11792: 
11793: // ]]>
11794: </script>
11795: END
11796:     return $scripttag;
11797: }
11798: 
11799: sub process_extracted_files {
11800:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11801:     my $numitems = $env{'form.archive_count'};
11802:     return unless ($numitems);
11803:     my @ids=&Apache::lonnet::current_machine_ids();
11804:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11805:         %folders,%containers,%mapinner,%prompttofetch);
11806:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11807:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11808:         $prefix = &LONCAPA::propath($docudom,$docuname);
11809:         $pathtocheck = "$dir_root/$destination";
11810:         $dir = $dir_root;
11811:         $ishome = 1;
11812:     } else {
11813:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11814:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11815:         $dir = "$dir_root/$docudom/$docuname";    
11816:     }
11817:     my $currdir = "$dir_root/$destination";
11818:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11819:     if ($env{'form.folderpath'}) {
11820:         my @items = split('&',$env{'form.folderpath'});
11821:         $folders{'0'} = $items[-2];
11822:         if ($env{'form.folderpath'} =~ /\:1$/) {
11823:             $containers{'0'}='page';
11824:         } else {  
11825:             $containers{'0'}='sequence';
11826:         }
11827:     }
11828:     my @archdirs = &get_env_multiple('form.archive_directory');
11829:     if ($numitems) {
11830:         for (my $i=1; $i<=$numitems; $i++) {
11831:             my $path = $env{'form.archive_content_'.$i};
11832:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11833:                 my $item = $1;
11834:                 $toplevelitems{$item} = $i;
11835:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11836:                     $is_dir{$item} = 1;
11837:                 }
11838:             }
11839:         }
11840:     }
11841:     my ($output,%children,%parent,%titles,%dirorder,$result);
11842:     if (keys(%toplevelitems) > 0) {
11843:         my @contents = sort(keys(%toplevelitems));
11844:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11845:                                            \%parent,\@contents,\%dirorder,\%titles);
11846:     }
11847:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11848:     if ($numitems) {
11849:         for (my $i=1; $i<=$numitems; $i++) {
11850:             next if ($env{'form.archive_'.$i} eq 'dependency');
11851:             my $path = $env{'form.archive_content_'.$i};
11852:             if ($path =~ /^\Q$pathtocheck\E/) {
11853:                 if ($env{'form.archive_'.$i} eq 'discard') {
11854:                     if ($prefix ne '' && $path ne '') {
11855:                         if (-e $prefix.$path) {
11856:                             if ((@archdirs > 0) && 
11857:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11858:                                 $todeletedir{$prefix.$path} = 1;
11859:                             } else {
11860:                                 $todelete{$prefix.$path} = 1;
11861:                             }
11862:                         }
11863:                     }
11864:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11865:                     my ($docstitle,$title,$url,$outer);
11866:                     ($title) = ($path =~ m{/([^/]+)$});
11867:                     $docstitle = $env{'form.archive_title_'.$i};
11868:                     if ($docstitle eq '') {
11869:                         $docstitle = $title;
11870:                     }
11871:                     $outer = 0;
11872:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11873:                         if (@{$dirorder{$i}} > 0) {
11874:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11875:                                 if ($env{'form.archive_'.$item} eq 'display') {
11876:                                     $outer = $item;
11877:                                     last;
11878:                                 }
11879:                             }
11880:                         }
11881:                     }
11882:                     my ($errtext,$fatal) = 
11883:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11884:                                                '/'.$folders{$outer}.'.'.
11885:                                                $containers{$outer});
11886:                     next if ($fatal);
11887:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11888:                         if ($context eq 'coursedocs') {
11889:                             $mapinner{$i} = time;
11890:                             $folders{$i} = 'default_'.$mapinner{$i};
11891:                             $containers{$i} = 'sequence';
11892:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11893:                                       $folders{$i}.'.'.$containers{$i};
11894:                             my $newidx = &LONCAPA::map::getresidx();
11895:                             $LONCAPA::map::resources[$newidx]=
11896:                                 $docstitle.':'.$url.':false:normal:res';
11897:                             push(@LONCAPA::map::order,$newidx);
11898:                             my ($outtext,$errtext) =
11899:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11900:                                                         $docuname.'/'.$folders{$outer}.
11901:                                                         '.'.$containers{$outer},1,1);
11902:                             $newseqid{$i} = $newidx;
11903:                             unless ($errtext) {
11904:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11905:                             }
11906:                         }
11907:                     } else {
11908:                         if ($context eq 'coursedocs') {
11909:                             my $newidx=&LONCAPA::map::getresidx();
11910:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11911:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11912:                                       $title;
11913:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11914:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11915:                             }
11916:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11917:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11918:                             }
11919:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11920:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11921:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11922:                                 unless ($ishome) {
11923:                                     my $fetch = "$newdest{$i}/$title";
11924:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11925:                                     $prompttofetch{$fetch} = 1;
11926:                                 }
11927:                             }
11928:                             $LONCAPA::map::resources[$newidx]=
11929:                                 $docstitle.':'.$url.':false:normal:res';
11930:                             push(@LONCAPA::map::order, $newidx);
11931:                             my ($outtext,$errtext)=
11932:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11933:                                                         $docuname.'/'.$folders{$outer}.
11934:                                                         '.'.$containers{$outer},1,1);
11935:                             unless ($errtext) {
11936:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11937:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11938:                                 }
11939:                             }
11940:                         }
11941:                     }
11942:                 }
11943:             } else {
11944:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11945:             }
11946:         }
11947:         for (my $i=1; $i<=$numitems; $i++) {
11948:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11949:             my $path = $env{'form.archive_content_'.$i};
11950:             if ($path =~ /^\Q$pathtocheck\E/) {
11951:                 my ($title) = ($path =~ m{/([^/]+)$});
11952:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11953:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11954:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11955:                         my ($itemidx,$fullpath,$relpath);
11956:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11957:                             my $container = $dirorder{$referrer{$i}}->[-1];
11958:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11959:                                 if ($dirorder{$i}->[$j] eq $container) {
11960:                                     $itemidx = $j;
11961:                                 }
11962:                             }
11963:                         }
11964:                         if ($itemidx eq '') {
11965:                             $itemidx =  0;
11966:                         } 
11967:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11968:                             if ($mapinner{$referrer{$i}}) {
11969:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11970:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11971:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11972:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11973:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11974:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11975:                                             if (!-e $fullpath) {
11976:                                                 mkdir($fullpath,0755);
11977:                                             }
11978:                                         }
11979:                                     } else {
11980:                                         last;
11981:                                     }
11982:                                 }
11983:                             }
11984:                         } elsif ($newdest{$referrer{$i}}) {
11985:                             $fullpath = $newdest{$referrer{$i}};
11986:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11987:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11988:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11989:                                     last;
11990:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11991:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11992:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11993:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11994:                                         if (!-e $fullpath) {
11995:                                             mkdir($fullpath,0755);
11996:                                         }
11997:                                     }
11998:                                 } else {
11999:                                     last;
12000:                                 }
12001:                             }
12002:                         }
12003:                         if ($fullpath ne '') {
12004:                             if (-e "$prefix$path") {
12005:                                 system("mv $prefix$path $fullpath/$title");
12006:                             }
12007:                             if (-e "$fullpath/$title") {
12008:                                 my $showpath;
12009:                                 if ($relpath ne '') {
12010:                                     $showpath = "$relpath/$title";
12011:                                 } else {
12012:                                     $showpath = "/$title";
12013:                                 } 
12014:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12015:                             } 
12016:                             unless ($ishome) {
12017:                                 my $fetch = "$fullpath/$title";
12018:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
12019:                                 $prompttofetch{$fetch} = 1;
12020:                             }
12021:                         }
12022:                     }
12023:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12024:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12025:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12026:                 }
12027:             } else {
12028:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12029:             }
12030:         }
12031:         if (keys(%todelete)) {
12032:             foreach my $key (keys(%todelete)) {
12033:                 unlink($key);
12034:             }
12035:         }
12036:         if (keys(%todeletedir)) {
12037:             foreach my $key (keys(%todeletedir)) {
12038:                 rmdir($key);
12039:             }
12040:         }
12041:         foreach my $dir (sort(keys(%is_dir))) {
12042:             if (($pathtocheck ne '') && ($dir ne ''))  {
12043:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12044:             }
12045:         }
12046:         if ($result ne '') {
12047:             $output .= '<ul>'."\n".
12048:                        $result."\n".
12049:                        '</ul>';
12050:         }
12051:         unless ($ishome) {
12052:             my $replicationfail;
12053:             foreach my $item (keys(%prompttofetch)) {
12054:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12055:                 unless ($fetchresult eq 'ok') {
12056:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12057:                 }
12058:             }
12059:             if ($replicationfail) {
12060:                 $output .= '<p class="LC_error">'.
12061:                            &mt('Course home server failed to retrieve:').'<ul>'.
12062:                            $replicationfail.
12063:                            '</ul></p>';
12064:             }
12065:         }
12066:     } else {
12067:         $warning = &mt('No items found in archive.');
12068:     }
12069:     if ($error) {
12070:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12071:                    $error.'</p>'."\n";
12072:     }
12073:     if ($warning) {
12074:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12075:     }
12076:     return $output;
12077: }
12078: 
12079: sub cleanup_empty_dirs {
12080:     my ($path) = @_;
12081:     if (($path ne '') && (-d $path)) {
12082:         if (opendir(my $dirh,$path)) {
12083:             my @dircontents = grep(!/^\./,readdir($dirh));
12084:             my $numitems = 0;
12085:             foreach my $item (@dircontents) {
12086:                 if (-d "$path/$item") {
12087:                     &cleanup_empty_dirs("$path/$item");
12088:                     if (-e "$path/$item") {
12089:                         $numitems ++;
12090:                     }
12091:                 } else {
12092:                     $numitems ++;
12093:                 }
12094:             }
12095:             if ($numitems == 0) {
12096:                 rmdir($path);
12097:             }
12098:             closedir($dirh);
12099:         }
12100:     }
12101:     return;
12102: }
12103: 
12104: =pod
12105: 
12106: =item * &get_folder_hierarchy()
12107: 
12108: Provides hierarchy of names of folders/sub-folders containing the current
12109: item,
12110: 
12111: Inputs: 3
12112:      - $navmap - navmaps object
12113: 
12114:      - $map - url for map (either the trigger itself, or map containing
12115:                            the resource, which is the trigger).
12116: 
12117:      - $showitem - 1 => show title for map itself; 0 => do not show.
12118: 
12119: Outputs: 1 @pathitems - array of folder/subfolder names.
12120: 
12121: =cut
12122: 
12123: sub get_folder_hierarchy {
12124:     my ($navmap,$map,$showitem) = @_;
12125:     my @pathitems;
12126:     if (ref($navmap)) {
12127:         my $mapres = $navmap->getResourceByUrl($map);
12128:         if (ref($mapres)) {
12129:             my $pcslist = $mapres->map_hierarchy();
12130:             if ($pcslist ne '') {
12131:                 my @pcs = split(/,/,$pcslist);
12132:                 foreach my $pc (@pcs) {
12133:                     if ($pc == 1) {
12134:                         push(@pathitems,&mt('Main Content'));
12135:                     } else {
12136:                         my $res = $navmap->getByMapPc($pc);
12137:                         if (ref($res)) {
12138:                             my $title = $res->compTitle();
12139:                             $title =~ s/\W+/_/g;
12140:                             if ($title ne '') {
12141:                                 push(@pathitems,$title);
12142:                             }
12143:                         }
12144:                     }
12145:                 }
12146:             }
12147:             if ($showitem) {
12148:                 if ($mapres->{ID} eq '0.0') {
12149:                     push(@pathitems,&mt('Main Content'));
12150:                 } else {
12151:                     my $maptitle = $mapres->compTitle();
12152:                     $maptitle =~ s/\W+/_/g;
12153:                     if ($maptitle ne '') {
12154:                         push(@pathitems,$maptitle);
12155:                     }
12156:                 }
12157:             }
12158:         }
12159:     }
12160:     return @pathitems;
12161: }
12162: 
12163: =pod
12164: 
12165: =item * &get_turnedin_filepath()
12166: 
12167: Determines path in a user's portfolio file for storage of files uploaded
12168: to a specific essayresponse or dropbox item.
12169: 
12170: Inputs: 3 required + 1 optional.
12171: $symb is symb for resource, $uname and $udom are for current user (required).
12172: $caller is optional (can be "submission", if routine is called when storing
12173: an upoaded file when "Submit Answer" button was pressed).
12174: 
12175: Returns array containing $path and $multiresp. 
12176: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12177: than one file upload item.  Callers of routine should append partid as a 
12178: subdirectory to $path in cases where $multiresp is 1.
12179: 
12180: Called by: homework/essayresponse.pm and homework/structuretags.pm
12181: 
12182: =cut
12183: 
12184: sub get_turnedin_filepath {
12185:     my ($symb,$uname,$udom,$caller) = @_;
12186:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12187:     my $turnindir;
12188:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12189:     $turnindir = $userhash{'turnindir'};
12190:     my ($path,$multiresp);
12191:     if ($turnindir eq '') {
12192:         if ($caller eq 'submission') {
12193:             $turnindir = &mt('turned in');
12194:             $turnindir =~ s/\W+/_/g;
12195:             my %newhash = (
12196:                             'turnindir' => $turnindir,
12197:                           );
12198:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12199:         }
12200:     }
12201:     if ($turnindir ne '') {
12202:         $path = '/'.$turnindir.'/';
12203:         my ($multipart,$turnin,@pathitems);
12204:         my $navmap = Apache::lonnavmaps::navmap->new();
12205:         if (defined($navmap)) {
12206:             my $mapres = $navmap->getResourceByUrl($map);
12207:             if (ref($mapres)) {
12208:                 my $pcslist = $mapres->map_hierarchy();
12209:                 if ($pcslist ne '') {
12210:                     foreach my $pc (split(/,/,$pcslist)) {
12211:                         my $res = $navmap->getByMapPc($pc);
12212:                         if (ref($res)) {
12213:                             my $title = $res->compTitle();
12214:                             $title =~ s/\W+/_/g;
12215:                             if ($title ne '') {
12216:                                 if (($pc > 1) && (length($title) > 12)) {
12217:                                     $title = substr($title,0,12);
12218:                                 }
12219:                                 push(@pathitems,$title);
12220:                             }
12221:                         }
12222:                     }
12223:                 }
12224:                 my $maptitle = $mapres->compTitle();
12225:                 $maptitle =~ s/\W+/_/g;
12226:                 if ($maptitle ne '') {
12227:                     if (length($maptitle) > 12) {
12228:                         $maptitle = substr($maptitle,0,12);
12229:                     }
12230:                     push(@pathitems,$maptitle);
12231:                 }
12232:                 unless ($env{'request.state'} eq 'construct') {
12233:                     my $res = $navmap->getBySymb($symb);
12234:                     if (ref($res)) {
12235:                         my $partlist = $res->parts();
12236:                         my $totaluploads = 0;
12237:                         if (ref($partlist) eq 'ARRAY') {
12238:                             foreach my $part (@{$partlist}) {
12239:                                 my @types = $res->responseType($part);
12240:                                 my @ids = $res->responseIds($part);
12241:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12242:                                     if ($types[$i] eq 'essay') {
12243:                                         my $partid = $part.'_'.$ids[$i];
12244:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12245:                                             $totaluploads ++;
12246:                                         }
12247:                                     }
12248:                                 }
12249:                             }
12250:                             if ($totaluploads > 1) {
12251:                                 $multiresp = 1;
12252:                             }
12253:                         }
12254:                     }
12255:                 }
12256:             } else {
12257:                 return;
12258:             }
12259:         } else {
12260:             return;
12261:         }
12262:         my $restitle=&Apache::lonnet::gettitle($symb);
12263:         $restitle =~ s/\W+/_/g;
12264:         if ($restitle eq '') {
12265:             $restitle = ($resurl =~ m{/[^/]+$});
12266:             if ($restitle eq '') {
12267:                 $restitle = time;
12268:             }
12269:         }
12270:         if (length($restitle) > 12) {
12271:             $restitle = substr($restitle,0,12);
12272:         }
12273:         push(@pathitems,$restitle);
12274:         $path .= join('/',@pathitems);
12275:     }
12276:     return ($path,$multiresp);
12277: }
12278: 
12279: =pod
12280: 
12281: =back
12282: 
12283: =head1 CSV Upload/Handling functions
12284: 
12285: =over 4
12286: 
12287: =item * &upfile_store($r)
12288: 
12289: Store uploaded file, $r should be the HTTP Request object,
12290: needs $env{'form.upfile'}
12291: returns $datatoken to be put into hidden field
12292: 
12293: =cut
12294: 
12295: sub upfile_store {
12296:     my $r=shift;
12297:     $env{'form.upfile'}=~s/\r/\n/gs;
12298:     $env{'form.upfile'}=~s/\f/\n/gs;
12299:     $env{'form.upfile'}=~s/\n+/\n/gs;
12300:     $env{'form.upfile'}=~s/\n+$//gs;
12301: 
12302:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12303: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12304:     {
12305:         my $datafile = $r->dir_config('lonDaemons').
12306:                            '/tmp/'.$datatoken.'.tmp';
12307:         if ( open(my $fh,">$datafile") ) {
12308:             print $fh $env{'form.upfile'};
12309:             close($fh);
12310:         }
12311:     }
12312:     return $datatoken;
12313: }
12314: 
12315: =pod
12316: 
12317: =item * &load_tmp_file($r)
12318: 
12319: Load uploaded file from tmp, $r should be the HTTP Request object,
12320: needs $env{'form.datatoken'},
12321: sets $env{'form.upfile'} to the contents of the file
12322: 
12323: =cut
12324: 
12325: sub load_tmp_file {
12326:     my $r=shift;
12327:     my @studentdata=();
12328:     {
12329:         my $studentfile = $r->dir_config('lonDaemons').
12330:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12331:         if ( open(my $fh,"<$studentfile") ) {
12332:             @studentdata=<$fh>;
12333:             close($fh);
12334:         }
12335:     }
12336:     $env{'form.upfile'}=join('',@studentdata);
12337: }
12338: 
12339: =pod
12340: 
12341: =item * &upfile_record_sep()
12342: 
12343: Separate uploaded file into records
12344: returns array of records,
12345: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12346: 
12347: =cut
12348: 
12349: sub upfile_record_sep {
12350:     if ($env{'form.upfiletype'} eq 'xml') {
12351:     } else {
12352: 	my @records;
12353: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12354: 	    if ($line=~/^\s*$/) { next; }
12355: 	    push(@records,$line);
12356: 	}
12357: 	return @records;
12358:     }
12359: }
12360: 
12361: =pod
12362: 
12363: =item * &record_sep($record)
12364: 
12365: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12366: 
12367: =cut
12368: 
12369: sub takeleft {
12370:     my $index=shift;
12371:     return substr('0000'.$index,-4,4);
12372: }
12373: 
12374: sub record_sep {
12375:     my $record=shift;
12376:     my %components=();
12377:     if ($env{'form.upfiletype'} eq 'xml') {
12378:     } elsif ($env{'form.upfiletype'} eq 'space') {
12379:         my $i=0;
12380:         foreach my $field (split(/\s+/,$record)) {
12381:             $field=~s/^(\"|\')//;
12382:             $field=~s/(\"|\')$//;
12383:             $components{&takeleft($i)}=$field;
12384:             $i++;
12385:         }
12386:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12387:         my $i=0;
12388:         foreach my $field (split(/\t/,$record)) {
12389:             $field=~s/^(\"|\')//;
12390:             $field=~s/(\"|\')$//;
12391:             $components{&takeleft($i)}=$field;
12392:             $i++;
12393:         }
12394:     } else {
12395:         my $separator=',';
12396:         if ($env{'form.upfiletype'} eq 'semisv') {
12397:             $separator=';';
12398:         }
12399:         my $i=0;
12400: # the character we are looking for to indicate the end of a quote or a record 
12401:         my $looking_for=$separator;
12402: # do not add the characters to the fields
12403:         my $ignore=0;
12404: # we just encountered a separator (or the beginning of the record)
12405:         my $just_found_separator=1;
12406: # store the field we are working on here
12407:         my $field='';
12408: # work our way through all characters in record
12409:         foreach my $character ($record=~/(.)/g) {
12410:             if ($character eq $looking_for) {
12411:                if ($character ne $separator) {
12412: # Found the end of a quote, again looking for separator
12413:                   $looking_for=$separator;
12414:                   $ignore=1;
12415:                } else {
12416: # Found a separator, store away what we got
12417:                   $components{&takeleft($i)}=$field;
12418: 	          $i++;
12419:                   $just_found_separator=1;
12420:                   $ignore=0;
12421:                   $field='';
12422:                }
12423:                next;
12424:             }
12425: # single or double quotation marks after a separator indicate beginning of a quote
12426: # we are now looking for the end of the quote and need to ignore separators
12427:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12428:                $looking_for=$character;
12429:                next;
12430:             }
12431: # ignore would be true after we reached the end of a quote
12432:             if ($ignore) { next; }
12433:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12434:             $field.=$character;
12435:             $just_found_separator=0; 
12436:         }
12437: # catch the very last entry, since we never encountered the separator
12438:         $components{&takeleft($i)}=$field;
12439:     }
12440:     return %components;
12441: }
12442: 
12443: ######################################################
12444: ######################################################
12445: 
12446: =pod
12447: 
12448: =item * &upfile_select_html()
12449: 
12450: Return HTML code to select a file from the users machine and specify 
12451: the file type.
12452: 
12453: =cut
12454: 
12455: ######################################################
12456: ######################################################
12457: sub upfile_select_html {
12458:     my %Types = (
12459:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12460:                  semisv => &mt('Semicolon separated values'),
12461:                  space => &mt('Space separated'),
12462:                  tab   => &mt('Tabulator separated'),
12463: #                 xml   => &mt('HTML/XML'),
12464:                  );
12465:     my $Str = '<input type="file" name="upfile" size="50" />'.
12466:         '<br />'.&mt('Type').': <select name="upfiletype">';
12467:     foreach my $type (sort(keys(%Types))) {
12468:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12469:     }
12470:     $Str .= "</select>\n";
12471:     return $Str;
12472: }
12473: 
12474: sub get_samples {
12475:     my ($records,$toget) = @_;
12476:     my @samples=({});
12477:     my $got=0;
12478:     foreach my $rec (@$records) {
12479: 	my %temp = &record_sep($rec);
12480: 	if (! grep(/\S/, values(%temp))) { next; }
12481: 	if (%temp) {
12482: 	    $samples[$got]=\%temp;
12483: 	    $got++;
12484: 	    if ($got == $toget) { last; }
12485: 	}
12486:     }
12487:     return \@samples;
12488: }
12489: 
12490: ######################################################
12491: ######################################################
12492: 
12493: =pod
12494: 
12495: =item * &csv_print_samples($r,$records)
12496: 
12497: Prints a table of sample values from each column uploaded $r is an
12498: Apache Request ref, $records is an arrayref from
12499: &Apache::loncommon::upfile_record_sep
12500: 
12501: =cut
12502: 
12503: ######################################################
12504: ######################################################
12505: sub csv_print_samples {
12506:     my ($r,$records) = @_;
12507:     my $samples = &get_samples($records,5);
12508: 
12509:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12510:               &start_data_table_header_row());
12511:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12512:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12513:     $r->print(&end_data_table_header_row());
12514:     foreach my $hash (@$samples) {
12515: 	$r->print(&start_data_table_row());
12516: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12517: 	    $r->print('<td>');
12518: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12519: 	    $r->print('</td>');
12520: 	}
12521: 	$r->print(&end_data_table_row());
12522:     }
12523:     $r->print(&end_data_table().'<br />'."\n");
12524: }
12525: 
12526: ######################################################
12527: ######################################################
12528: 
12529: =pod
12530: 
12531: =item * &csv_print_select_table($r,$records,$d)
12532: 
12533: Prints a table to create associations between values and table columns.
12534: 
12535: $r is an Apache Request ref,
12536: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12537: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12538: 
12539: =cut
12540: 
12541: ######################################################
12542: ######################################################
12543: sub csv_print_select_table {
12544:     my ($r,$records,$d) = @_;
12545:     my $i=0;
12546:     my $samples = &get_samples($records,1);
12547:     $r->print(&mt('Associate columns with student attributes.')."\n".
12548: 	      &start_data_table().&start_data_table_header_row().
12549:               '<th>'.&mt('Attribute').'</th>'.
12550:               '<th>'.&mt('Column').'</th>'.
12551:               &end_data_table_header_row()."\n");
12552:     foreach my $array_ref (@$d) {
12553: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12554: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12555: 
12556: 	$r->print('<td><select name="f'.$i.'"'.
12557: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12558: 	$r->print('<option value="none"></option>');
12559: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12560: 	    $r->print('<option value="'.$sample.'"'.
12561:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12562:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12563: 	}
12564: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12565: 	$i++;
12566:     }
12567:     $r->print(&end_data_table());
12568:     $i--;
12569:     return $i;
12570: }
12571: 
12572: ######################################################
12573: ######################################################
12574: 
12575: =pod
12576: 
12577: =item * &csv_samples_select_table($r,$records,$d)
12578: 
12579: Prints a table of sample values from the upload and can make associate samples to internal names.
12580: 
12581: $r is an Apache Request ref,
12582: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12583: $d is an array of 2 element arrays (internal name, displayed name)
12584: 
12585: =cut
12586: 
12587: ######################################################
12588: ######################################################
12589: sub csv_samples_select_table {
12590:     my ($r,$records,$d) = @_;
12591:     my $i=0;
12592:     #
12593:     my $max_samples = 5;
12594:     my $samples = &get_samples($records,$max_samples);
12595:     $r->print(&start_data_table().
12596:               &start_data_table_header_row().'<th>'.
12597:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12598:               &end_data_table_header_row());
12599: 
12600:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12601: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12602: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12603: 	foreach my $option (@$d) {
12604: 	    my ($value,$display,$defaultcol)=@{ $option };
12605: 	    $r->print('<option value="'.$value.'"'.
12606:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12607:                       $display.'</option>');
12608: 	}
12609: 	$r->print('</select></td><td>');
12610: 	foreach my $line (0..($max_samples-1)) {
12611: 	    if (defined($samples->[$line]{$key})) { 
12612: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12613: 	    }
12614: 	}
12615: 	$r->print('</td>'.&end_data_table_row());
12616: 	$i++;
12617:     }
12618:     $r->print(&end_data_table());
12619:     $i--;
12620:     return($i);
12621: }
12622: 
12623: ######################################################
12624: ######################################################
12625: 
12626: =pod
12627: 
12628: =item * &clean_excel_name($name)
12629: 
12630: Returns a replacement for $name which does not contain any illegal characters.
12631: 
12632: =cut
12633: 
12634: ######################################################
12635: ######################################################
12636: sub clean_excel_name {
12637:     my ($name) = @_;
12638:     $name =~ s/[:\*\?\/\\]//g;
12639:     if (length($name) > 31) {
12640:         $name = substr($name,0,31);
12641:     }
12642:     return $name;
12643: }
12644: 
12645: =pod
12646: 
12647: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12648: 
12649: Returns either 1 or undef
12650: 
12651: 1 if the part is to be hidden, undef if it is to be shown
12652: 
12653: Arguments are:
12654: 
12655: $id the id of the part to be checked
12656: $symb, optional the symb of the resource to check
12657: $udom, optional the domain of the user to check for
12658: $uname, optional the username of the user to check for
12659: 
12660: =cut
12661: 
12662: sub check_if_partid_hidden {
12663:     my ($id,$symb,$udom,$uname) = @_;
12664:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12665: 					 $symb,$udom,$uname);
12666:     my $truth=1;
12667:     #if the string starts with !, then the list is the list to show not hide
12668:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12669:     my @hiddenlist=split(/,/,$hiddenparts);
12670:     foreach my $checkid (@hiddenlist) {
12671: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12672:     }
12673:     return !$truth;
12674: }
12675: 
12676: 
12677: ############################################################
12678: ############################################################
12679: 
12680: =pod
12681: 
12682: =back 
12683: 
12684: =head1 cgi-bin script and graphing routines
12685: 
12686: =over 4
12687: 
12688: =item * &get_cgi_id()
12689: 
12690: Inputs: none
12691: 
12692: Returns an id which can be used to pass environment variables
12693: to various cgi-bin scripts.  These environment variables will
12694: be removed from the users environment after a given time by
12695: the routine &Apache::lonnet::transfer_profile_to_env.
12696: 
12697: =cut
12698: 
12699: ############################################################
12700: ############################################################
12701: my $uniq=0;
12702: sub get_cgi_id {
12703:     $uniq=($uniq+1)%100000;
12704:     return (time.'_'.$$.'_'.$uniq);
12705: }
12706: 
12707: ############################################################
12708: ############################################################
12709: 
12710: =pod
12711: 
12712: =item * &DrawBarGraph()
12713: 
12714: Facilitates the plotting of data in a (stacked) bar graph.
12715: Puts plot definition data into the users environment in order for 
12716: graph.png to plot it.  Returns an <img> tag for the plot.
12717: The bars on the plot are labeled '1','2',...,'n'.
12718: 
12719: Inputs:
12720: 
12721: =over 4
12722: 
12723: =item $Title: string, the title of the plot
12724: 
12725: =item $xlabel: string, text describing the X-axis of the plot
12726: 
12727: =item $ylabel: string, text describing the Y-axis of the plot
12728: 
12729: =item $Max: scalar, the maximum Y value to use in the plot
12730: If $Max is < any data point, the graph will not be rendered.
12731: 
12732: =item $colors: array ref holding the colors to be used for the data sets when
12733: they are plotted.  If undefined, default values will be used.
12734: 
12735: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12736: 
12737: =item @Values: An array of array references.  Each array reference holds data
12738: to be plotted in a stacked bar chart.
12739: 
12740: =item If the final element of @Values is a hash reference the key/value
12741: pairs will be added to the graph definition.
12742: 
12743: =back
12744: 
12745: Returns:
12746: 
12747: An <img> tag which references graph.png and the appropriate identifying
12748: information for the plot.
12749: 
12750: =cut
12751: 
12752: ############################################################
12753: ############################################################
12754: sub DrawBarGraph {
12755:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12756:     #
12757:     if (! defined($colors)) {
12758:         $colors = ['#33ff00', 
12759:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12760:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12761:                   ]; 
12762:     }
12763:     my $extra_settings = {};
12764:     if (ref($Values[-1]) eq 'HASH') {
12765:         $extra_settings = pop(@Values);
12766:     }
12767:     #
12768:     my $identifier = &get_cgi_id();
12769:     my $id = 'cgi.'.$identifier;        
12770:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12771:         return '';
12772:     }
12773:     #
12774:     my @Labels;
12775:     if (defined($labels)) {
12776:         @Labels = @$labels;
12777:     } else {
12778:         for (my $i=0;$i<@{$Values[0]};$i++) {
12779:             push (@Labels,$i+1);
12780:         }
12781:     }
12782:     #
12783:     my $NumBars = scalar(@{$Values[0]});
12784:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12785:     my %ValuesHash;
12786:     my $NumSets=1;
12787:     foreach my $array (@Values) {
12788:         next if (! ref($array));
12789:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12790:             join(',',@$array);
12791:     }
12792:     #
12793:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12794:     if ($NumBars < 3) {
12795:         $width = 120+$NumBars*32;
12796:         $xskip = 1;
12797:         $bar_width = 30;
12798:     } elsif ($NumBars < 5) {
12799:         $width = 120+$NumBars*20;
12800:         $xskip = 1;
12801:         $bar_width = 20;
12802:     } elsif ($NumBars < 10) {
12803:         $width = 120+$NumBars*15;
12804:         $xskip = 1;
12805:         $bar_width = 15;
12806:     } elsif ($NumBars <= 25) {
12807:         $width = 120+$NumBars*11;
12808:         $xskip = 5;
12809:         $bar_width = 8;
12810:     } elsif ($NumBars <= 50) {
12811:         $width = 120+$NumBars*8;
12812:         $xskip = 5;
12813:         $bar_width = 4;
12814:     } else {
12815:         $width = 120+$NumBars*8;
12816:         $xskip = 5;
12817:         $bar_width = 4;
12818:     }
12819:     #
12820:     $Max = 1 if ($Max < 1);
12821:     if ( int($Max) < $Max ) {
12822:         $Max++;
12823:         $Max = int($Max);
12824:     }
12825:     $Title  = '' if (! defined($Title));
12826:     $xlabel = '' if (! defined($xlabel));
12827:     $ylabel = '' if (! defined($ylabel));
12828:     $ValuesHash{$id.'.title'}    = &escape($Title);
12829:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12830:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12831:     $ValuesHash{$id.'.y_max_value'} = $Max;
12832:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12833:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12834:     $ValuesHash{$id.'.PlotType'} = 'bar';
12835:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12836:     $ValuesHash{$id.'.height'}   = $height;
12837:     $ValuesHash{$id.'.width'}    = $width;
12838:     $ValuesHash{$id.'.xskip'}    = $xskip;
12839:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12840:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12841:     #
12842:     # Deal with other parameters
12843:     while (my ($key,$value) = each(%$extra_settings)) {
12844:         $ValuesHash{$id.'.'.$key} = $value;
12845:     }
12846:     #
12847:     &Apache::lonnet::appenv(\%ValuesHash);
12848:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12849: }
12850: 
12851: ############################################################
12852: ############################################################
12853: 
12854: =pod
12855: 
12856: =item * &DrawXYGraph()
12857: 
12858: Facilitates the plotting of data in an XY graph.
12859: Puts plot definition data into the users environment in order for 
12860: graph.png to plot it.  Returns an <img> tag for the plot.
12861: 
12862: Inputs:
12863: 
12864: =over 4
12865: 
12866: =item $Title: string, the title of the plot
12867: 
12868: =item $xlabel: string, text describing the X-axis of the plot
12869: 
12870: =item $ylabel: string, text describing the Y-axis of the plot
12871: 
12872: =item $Max: scalar, the maximum Y value to use in the plot
12873: If $Max is < any data point, the graph will not be rendered.
12874: 
12875: =item $colors: Array ref containing the hex color codes for the data to be 
12876: plotted in.  If undefined, default values will be used.
12877: 
12878: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12879: 
12880: =item $Ydata: Array ref containing Array refs.  
12881: Each of the contained arrays will be plotted as a separate curve.
12882: 
12883: =item %Values: hash indicating or overriding any default values which are 
12884: passed to graph.png.  
12885: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12886: 
12887: =back
12888: 
12889: Returns:
12890: 
12891: An <img> tag which references graph.png and the appropriate identifying
12892: information for the plot.
12893: 
12894: =cut
12895: 
12896: ############################################################
12897: ############################################################
12898: sub DrawXYGraph {
12899:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12900:     #
12901:     # Create the identifier for the graph
12902:     my $identifier = &get_cgi_id();
12903:     my $id = 'cgi.'.$identifier;
12904:     #
12905:     $Title  = '' if (! defined($Title));
12906:     $xlabel = '' if (! defined($xlabel));
12907:     $ylabel = '' if (! defined($ylabel));
12908:     my %ValuesHash = 
12909:         (
12910:          $id.'.title'  => &escape($Title),
12911:          $id.'.xlabel' => &escape($xlabel),
12912:          $id.'.ylabel' => &escape($ylabel),
12913:          $id.'.y_max_value'=> $Max,
12914:          $id.'.labels'     => join(',',@$Xlabels),
12915:          $id.'.PlotType'   => 'XY',
12916:          );
12917:     #
12918:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12919:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12920:     }
12921:     #
12922:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12923:         return '';
12924:     }
12925:     my $NumSets=1;
12926:     foreach my $array (@{$Ydata}){
12927:         next if (! ref($array));
12928:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12929:     }
12930:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12931:     #
12932:     # Deal with other parameters
12933:     while (my ($key,$value) = each(%Values)) {
12934:         $ValuesHash{$id.'.'.$key} = $value;
12935:     }
12936:     #
12937:     &Apache::lonnet::appenv(\%ValuesHash);
12938:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12939: }
12940: 
12941: ############################################################
12942: ############################################################
12943: 
12944: =pod
12945: 
12946: =item * &DrawXYYGraph()
12947: 
12948: Facilitates the plotting of data in an XY graph with two Y axes.
12949: Puts plot definition data into the users environment in order for 
12950: graph.png to plot it.  Returns an <img> tag for the plot.
12951: 
12952: Inputs:
12953: 
12954: =over 4
12955: 
12956: =item $Title: string, the title of the plot
12957: 
12958: =item $xlabel: string, text describing the X-axis of the plot
12959: 
12960: =item $ylabel: string, text describing the Y-axis of the plot
12961: 
12962: =item $colors: Array ref containing the hex color codes for the data to be 
12963: plotted in.  If undefined, default values will be used.
12964: 
12965: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12966: 
12967: =item $Ydata1: The first data set
12968: 
12969: =item $Min1: The minimum value of the left Y-axis
12970: 
12971: =item $Max1: The maximum value of the left Y-axis
12972: 
12973: =item $Ydata2: The second data set
12974: 
12975: =item $Min2: The minimum value of the right Y-axis
12976: 
12977: =item $Max2: The maximum value of the left Y-axis
12978: 
12979: =item %Values: hash indicating or overriding any default values which are 
12980: passed to graph.png.  
12981: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12982: 
12983: =back
12984: 
12985: Returns:
12986: 
12987: An <img> tag which references graph.png and the appropriate identifying
12988: information for the plot.
12989: 
12990: =cut
12991: 
12992: ############################################################
12993: ############################################################
12994: sub DrawXYYGraph {
12995:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12996:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12997:     #
12998:     # Create the identifier for the graph
12999:     my $identifier = &get_cgi_id();
13000:     my $id = 'cgi.'.$identifier;
13001:     #
13002:     $Title  = '' if (! defined($Title));
13003:     $xlabel = '' if (! defined($xlabel));
13004:     $ylabel = '' if (! defined($ylabel));
13005:     my %ValuesHash = 
13006:         (
13007:          $id.'.title'  => &escape($Title),
13008:          $id.'.xlabel' => &escape($xlabel),
13009:          $id.'.ylabel' => &escape($ylabel),
13010:          $id.'.labels' => join(',',@$Xlabels),
13011:          $id.'.PlotType' => 'XY',
13012:          $id.'.NumSets' => 2,
13013:          $id.'.two_axes' => 1,
13014:          $id.'.y1_max_value' => $Max1,
13015:          $id.'.y1_min_value' => $Min1,
13016:          $id.'.y2_max_value' => $Max2,
13017:          $id.'.y2_min_value' => $Min2,
13018:          );
13019:     #
13020:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13021:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13022:     }
13023:     #
13024:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13025:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13026:         return '';
13027:     }
13028:     my $NumSets=1;
13029:     foreach my $array ($Ydata1,$Ydata2){
13030:         next if (! ref($array));
13031:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13032:     }
13033:     #
13034:     # Deal with other parameters
13035:     while (my ($key,$value) = each(%Values)) {
13036:         $ValuesHash{$id.'.'.$key} = $value;
13037:     }
13038:     #
13039:     &Apache::lonnet::appenv(\%ValuesHash);
13040:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13041: }
13042: 
13043: ############################################################
13044: ############################################################
13045: 
13046: =pod
13047: 
13048: =back 
13049: 
13050: =head1 Statistics helper routines?  
13051: 
13052: Bad place for them but what the hell.
13053: 
13054: =over 4
13055: 
13056: =item * &chartlink()
13057: 
13058: Returns a link to the chart for a specific student.  
13059: 
13060: Inputs:
13061: 
13062: =over 4
13063: 
13064: =item $linktext: The text of the link
13065: 
13066: =item $sname: The students username
13067: 
13068: =item $sdomain: The students domain
13069: 
13070: =back
13071: 
13072: =back
13073: 
13074: =cut
13075: 
13076: ############################################################
13077: ############################################################
13078: sub chartlink {
13079:     my ($linktext, $sname, $sdomain) = @_;
13080:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13081:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13082:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13083:        '">'.$linktext.'</a>';
13084: }
13085: 
13086: #######################################################
13087: #######################################################
13088: 
13089: =pod
13090: 
13091: =head1 Course Environment Routines
13092: 
13093: =over 4
13094: 
13095: =item * &restore_course_settings()
13096: 
13097: =item * &store_course_settings()
13098: 
13099: Restores/Store indicated form parameters from the course environment.
13100: Will not overwrite existing values of the form parameters.
13101: 
13102: Inputs: 
13103: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13104: 
13105: a hash ref describing the data to be stored.  For example:
13106:    
13107: %Save_Parameters = ('Status' => 'scalar',
13108:     'chartoutputmode' => 'scalar',
13109:     'chartoutputdata' => 'scalar',
13110:     'Section' => 'array',
13111:     'Group' => 'array',
13112:     'StudentData' => 'array',
13113:     'Maps' => 'array');
13114: 
13115: Returns: both routines return nothing
13116: 
13117: =back
13118: 
13119: =cut
13120: 
13121: #######################################################
13122: #######################################################
13123: sub store_course_settings {
13124:     return &store_settings($env{'request.course.id'},@_);
13125: }
13126: 
13127: sub store_settings {
13128:     # save to the environment
13129:     # appenv the same items, just to be safe
13130:     my $udom  = $env{'user.domain'};
13131:     my $uname = $env{'user.name'};
13132:     my ($context,$prefix,$Settings) = @_;
13133:     my %SaveHash;
13134:     my %AppHash;
13135:     while (my ($setting,$type) = each(%$Settings)) {
13136:         my $basename = join('.','internal',$context,$prefix,$setting);
13137:         my $envname = 'environment.'.$basename;
13138:         if (exists($env{'form.'.$setting})) {
13139:             # Save this value away
13140:             if ($type eq 'scalar' &&
13141:                 (! exists($env{$envname}) || 
13142:                  $env{$envname} ne $env{'form.'.$setting})) {
13143:                 $SaveHash{$basename} = $env{'form.'.$setting};
13144:                 $AppHash{$envname}   = $env{'form.'.$setting};
13145:             } elsif ($type eq 'array') {
13146:                 my $stored_form;
13147:                 if (ref($env{'form.'.$setting})) {
13148:                     $stored_form = join(',',
13149:                                         map {
13150:                                             &escape($_);
13151:                                         } sort(@{$env{'form.'.$setting}}));
13152:                 } else {
13153:                     $stored_form = 
13154:                         &escape($env{'form.'.$setting});
13155:                 }
13156:                 # Determine if the array contents are the same.
13157:                 if ($stored_form ne $env{$envname}) {
13158:                     $SaveHash{$basename} = $stored_form;
13159:                     $AppHash{$envname}   = $stored_form;
13160:                 }
13161:             }
13162:         }
13163:     }
13164:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13165:                                           $udom,$uname);
13166:     if ($put_result !~ /^(ok|delayed)/) {
13167:         &Apache::lonnet::logthis('unable to save form parameters, '.
13168:                                  'got error:'.$put_result);
13169:     }
13170:     # Make sure these settings stick around in this session, too
13171:     &Apache::lonnet::appenv(\%AppHash);
13172:     return;
13173: }
13174: 
13175: sub restore_course_settings {
13176:     return &restore_settings($env{'request.course.id'},@_);
13177: }
13178: 
13179: sub restore_settings {
13180:     my ($context,$prefix,$Settings) = @_;
13181:     while (my ($setting,$type) = each(%$Settings)) {
13182:         next if (exists($env{'form.'.$setting}));
13183:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13184:             '.'.$setting;
13185:         if (exists($env{$envname})) {
13186:             if ($type eq 'scalar') {
13187:                 $env{'form.'.$setting} = $env{$envname};
13188:             } elsif ($type eq 'array') {
13189:                 $env{'form.'.$setting} = [ 
13190:                                            map { 
13191:                                                &unescape($_); 
13192:                                            } split(',',$env{$envname})
13193:                                            ];
13194:             }
13195:         }
13196:     }
13197: }
13198: 
13199: #######################################################
13200: #######################################################
13201: 
13202: =pod
13203: 
13204: =head1 Domain E-mail Routines  
13205: 
13206: =over 4
13207: 
13208: =item * &build_recipient_list()
13209: 
13210: Build recipient lists for following types of e-mail:
13211: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13212: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13213: module change checking, student/employee ID conflict checks, as
13214: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13215: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13216: 
13217: Inputs:
13218: defmail (scalar - email address of default recipient), 
13219: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13220: requestsmail, updatesmail, or idconflictsmail).
13221: 
13222: defdom (domain for which to retrieve configuration settings),
13223: 
13224: origmail (scalar - email address of recipient from loncapa.conf, 
13225: i.e., predates configuration by DC via domainprefs.pm 
13226: 
13227: Returns: comma separated list of addresses to which to send e-mail.
13228: 
13229: =back
13230: 
13231: =cut
13232: 
13233: ############################################################
13234: ############################################################
13235: sub build_recipient_list {
13236:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13237:     my @recipients;
13238:     my $otheremails;
13239:     my %domconfig =
13240:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13241:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13242:         if (exists($domconfig{'contacts'}{$mailing})) {
13243:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13244:                 my @contacts = ('adminemail','supportemail');
13245:                 foreach my $item (@contacts) {
13246:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13247:                         my $addr = $domconfig{'contacts'}{$item}; 
13248:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13249:                             push(@recipients,$addr);
13250:                         }
13251:                     }
13252:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13253:                 }
13254:             }
13255:         } elsif ($origmail ne '') {
13256:             push(@recipients,$origmail);
13257:         }
13258:     } elsif ($origmail ne '') {
13259:         push(@recipients,$origmail);
13260:     }
13261:     if (defined($defmail)) {
13262:         if ($defmail ne '') {
13263:             push(@recipients,$defmail);
13264:         }
13265:     }
13266:     if ($otheremails) {
13267:         my @others;
13268:         if ($otheremails =~ /,/) {
13269:             @others = split(/,/,$otheremails);
13270:         } else {
13271:             push(@others,$otheremails);
13272:         }
13273:         foreach my $addr (@others) {
13274:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13275:                 push(@recipients,$addr);
13276:             }
13277:         }
13278:     }
13279:     my $recipientlist = join(',',@recipients); 
13280:     return $recipientlist;
13281: }
13282: 
13283: ############################################################
13284: ############################################################
13285: 
13286: =pod
13287: 
13288: =head1 Course Catalog Routines
13289: 
13290: =over 4
13291: 
13292: =item * &gather_categories()
13293: 
13294: Converts category definitions - keys of categories hash stored in  
13295: coursecategories in configuration.db on the primary library server in a 
13296: domain - to an array.  Also generates javascript and idx hash used to 
13297: generate Domain Coordinator interface for editing Course Categories.
13298: 
13299: Inputs:
13300: 
13301: categories (reference to hash of category definitions).
13302: 
13303: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13304:       categories and subcategories).
13305: 
13306: idx (reference to hash of counters used in Domain Coordinator interface for 
13307:       editing Course Categories).
13308: 
13309: jsarray (reference to array of categories used to create Javascript arrays for
13310:          Domain Coordinator interface for editing Course Categories).
13311: 
13312: Returns: nothing
13313: 
13314: Side effects: populates cats, idx and jsarray. 
13315: 
13316: =cut
13317: 
13318: sub gather_categories {
13319:     my ($categories,$cats,$idx,$jsarray) = @_;
13320:     my %counters;
13321:     my $num = 0;
13322:     foreach my $item (keys(%{$categories})) {
13323:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13324:         if ($container eq '' && $depth == 0) {
13325:             $cats->[$depth][$categories->{$item}] = $cat;
13326:         } else {
13327:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13328:         }
13329:         my ($escitem,$tail) = split(/:/,$item,2);
13330:         if ($counters{$tail} eq '') {
13331:             $counters{$tail} = $num;
13332:             $num ++;
13333:         }
13334:         if (ref($idx) eq 'HASH') {
13335:             $idx->{$item} = $counters{$tail};
13336:         }
13337:         if (ref($jsarray) eq 'ARRAY') {
13338:             push(@{$jsarray->[$counters{$tail}]},$item);
13339:         }
13340:     }
13341:     return;
13342: }
13343: 
13344: =pod
13345: 
13346: =item * &extract_categories()
13347: 
13348: Used to generate breadcrumb trails for course categories.
13349: 
13350: Inputs:
13351: 
13352: categories (reference to hash of category definitions).
13353: 
13354: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13355:       categories and subcategories).
13356: 
13357: trails (reference to array of breacrumb trails for each category).
13358: 
13359: allitems (reference to hash - key is category key 
13360:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13361: 
13362: idx (reference to hash of counters used in Domain Coordinator interface for
13363:       editing Course Categories).
13364: 
13365: jsarray (reference to array of categories used to create Javascript arrays for
13366:          Domain Coordinator interface for editing Course Categories).
13367: 
13368: subcats (reference to hash of arrays containing all subcategories within each 
13369:          category, -recursive)
13370: 
13371: Returns: nothing
13372: 
13373: Side effects: populates trails and allitems hash references.
13374: 
13375: =cut
13376: 
13377: sub extract_categories {
13378:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13379:     if (ref($categories) eq 'HASH') {
13380:         &gather_categories($categories,$cats,$idx,$jsarray);
13381:         if (ref($cats->[0]) eq 'ARRAY') {
13382:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13383:                 my $name = $cats->[0][$i];
13384:                 my $item = &escape($name).'::0';
13385:                 my $trailstr;
13386:                 if ($name eq 'instcode') {
13387:                     $trailstr = &mt('Official courses (with institutional codes)');
13388:                 } elsif ($name eq 'communities') {
13389:                     $trailstr = &mt('Communities');
13390:                 } else {
13391:                     $trailstr = $name;
13392:                 }
13393:                 if ($allitems->{$item} eq '') {
13394:                     push(@{$trails},$trailstr);
13395:                     $allitems->{$item} = scalar(@{$trails})-1;
13396:                 }
13397:                 my @parents = ($name);
13398:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13399:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13400:                         my $category = $cats->[1]{$name}[$j];
13401:                         if (ref($subcats) eq 'HASH') {
13402:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13403:                         }
13404:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13405:                     }
13406:                 } else {
13407:                     if (ref($subcats) eq 'HASH') {
13408:                         $subcats->{$item} = [];
13409:                     }
13410:                 }
13411:             }
13412:         }
13413:     }
13414:     return;
13415: }
13416: 
13417: =pod
13418: 
13419: =item * &recurse_categories()
13420: 
13421: Recursively used to generate breadcrumb trails for course categories.
13422: 
13423: Inputs:
13424: 
13425: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13426:       categories and subcategories).
13427: 
13428: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13429: 
13430: category (current course category, for which breadcrumb trail is being generated).
13431: 
13432: trails (reference to array of breadcrumb trails for each category).
13433: 
13434: allitems (reference to hash - key is category key
13435:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13436: 
13437: parents (array containing containers directories for current category, 
13438:          back to top level). 
13439: 
13440: Returns: nothing
13441: 
13442: Side effects: populates trails and allitems hash references
13443: 
13444: =cut
13445: 
13446: sub recurse_categories {
13447:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13448:     my $shallower = $depth - 1;
13449:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13450:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13451:             my $name = $cats->[$depth]{$category}[$k];
13452:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13453:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13454:             if ($allitems->{$item} eq '') {
13455:                 push(@{$trails},$trailstr);
13456:                 $allitems->{$item} = scalar(@{$trails})-1;
13457:             }
13458:             my $deeper = $depth+1;
13459:             push(@{$parents},$category);
13460:             if (ref($subcats) eq 'HASH') {
13461:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13462:                 for (my $j=@{$parents}; $j>=0; $j--) {
13463:                     my $higher;
13464:                     if ($j > 0) {
13465:                         $higher = &escape($parents->[$j]).':'.
13466:                                   &escape($parents->[$j-1]).':'.$j;
13467:                     } else {
13468:                         $higher = &escape($parents->[$j]).'::'.$j;
13469:                     }
13470:                     push(@{$subcats->{$higher}},$subcat);
13471:                 }
13472:             }
13473:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13474:                                 $subcats);
13475:             pop(@{$parents});
13476:         }
13477:     } else {
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:     }
13485:     return;
13486: }
13487: 
13488: =pod
13489: 
13490: =item * &assign_categories_table()
13491: 
13492: Create a datatable for display of hierarchical categories in a domain,
13493: with checkboxes to allow a course to be categorized. 
13494: 
13495: Inputs:
13496: 
13497: cathash - reference to hash of categories defined for the domain (from
13498:           configuration.db)
13499: 
13500: currcat - scalar with an & separated list of categories assigned to a course. 
13501: 
13502: type    - scalar contains course type (Course or Community).
13503: 
13504: Returns: $output (markup to be displayed) 
13505: 
13506: =cut
13507: 
13508: sub assign_categories_table {
13509:     my ($cathash,$currcat,$type) = @_;
13510:     my $output;
13511:     if (ref($cathash) eq 'HASH') {
13512:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13513:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13514:         $maxdepth = scalar(@cats);
13515:         if (@cats > 0) {
13516:             my $itemcount = 0;
13517:             if (ref($cats[0]) eq 'ARRAY') {
13518:                 my @currcategories;
13519:                 if ($currcat ne '') {
13520:                     @currcategories = split('&',$currcat);
13521:                 }
13522:                 my $table;
13523:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13524:                     my $parent = $cats[0][$i];
13525:                     next if ($parent eq 'instcode');
13526:                     if ($type eq 'Community') {
13527:                         next unless ($parent eq 'communities');
13528:                     } else {
13529:                         next if ($parent eq 'communities');
13530:                     }
13531:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13532:                     my $item = &escape($parent).'::0';
13533:                     my $checked = '';
13534:                     if (@currcategories > 0) {
13535:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13536:                             $checked = ' checked="checked"';
13537:                         }
13538:                     }
13539:                     my $parent_title = $parent;
13540:                     if ($parent eq 'communities') {
13541:                         $parent_title = &mt('Communities');
13542:                     }
13543:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13544:                               '<input type="checkbox" name="usecategory" value="'.
13545:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13546:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13547:                     my $depth = 1;
13548:                     push(@path,$parent);
13549:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13550:                     pop(@path);
13551:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13552:                     $itemcount ++;
13553:                 }
13554:                 if ($itemcount) {
13555:                     $output = &Apache::loncommon::start_data_table().
13556:                               $table.
13557:                               &Apache::loncommon::end_data_table();
13558:                 }
13559:             }
13560:         }
13561:     }
13562:     return $output;
13563: }
13564: 
13565: =pod
13566: 
13567: =item * &assign_category_rows()
13568: 
13569: Create a datatable row for display of nested categories in a domain,
13570: with checkboxes to allow a course to be categorized,called recursively.
13571: 
13572: Inputs:
13573: 
13574: itemcount - track row number for alternating colors
13575: 
13576: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13577:       categories and subcategories.
13578: 
13579: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13580: 
13581: parent - parent of current category item
13582: 
13583: path - Array containing all categories back up through the hierarchy from the
13584:        current category to the top level.
13585: 
13586: currcategories - reference to array of current categories assigned to the course
13587: 
13588: Returns: $output (markup to be displayed).
13589: 
13590: =cut
13591: 
13592: sub assign_category_rows {
13593:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13594:     my ($text,$name,$item,$chgstr);
13595:     if (ref($cats) eq 'ARRAY') {
13596:         my $maxdepth = scalar(@{$cats});
13597:         if (ref($cats->[$depth]) eq 'HASH') {
13598:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13599:                 my $numchildren = @{$cats->[$depth]{$parent}};
13600:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13601:                 $text .= '<td><table class="LC_data_table">';
13602:                 for (my $j=0; $j<$numchildren; $j++) {
13603:                     $name = $cats->[$depth]{$parent}[$j];
13604:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13605:                     my $deeper = $depth+1;
13606:                     my $checked = '';
13607:                     if (ref($currcategories) eq 'ARRAY') {
13608:                         if (@{$currcategories} > 0) {
13609:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13610:                                 $checked = ' checked="checked"';
13611:                             }
13612:                         }
13613:                     }
13614:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13615:                              '<input type="checkbox" name="usecategory" value="'.
13616:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13617:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13618:                              '</td><td>';
13619:                     if (ref($path) eq 'ARRAY') {
13620:                         push(@{$path},$name);
13621:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13622:                         pop(@{$path});
13623:                     }
13624:                     $text .= '</td></tr>';
13625:                 }
13626:                 $text .= '</table></td>';
13627:             }
13628:         }
13629:     }
13630:     return $text;
13631: }
13632: 
13633: ############################################################
13634: ############################################################
13635: 
13636: 
13637: sub commit_customrole {
13638:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13639:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13640:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13641:                          ($end?', ending '.localtime($end):'').': <b>'.
13642:               &Apache::lonnet::assigncustomrole(
13643:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13644:                  '</b><br />';
13645:     return $output;
13646: }
13647: 
13648: sub commit_standardrole {
13649:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13650:     my ($output,$logmsg,$linefeed);
13651:     if ($context eq 'auto') {
13652:         $linefeed = "\n";
13653:     } else {
13654:         $linefeed = "<br />\n";
13655:     }  
13656:     if ($three eq 'st') {
13657:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13658:                                          $one,$two,$sec,$context,$credits);
13659:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13660:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13661:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13662:         } else {
13663:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13664:                ($start?', '.&mt('starting').' '.localtime($start):'').
13665:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13666:             if ($context eq 'auto') {
13667:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13668:             } else {
13669:                $output .= '<b>'.$result.'</b>'.$linefeed.
13670:                &mt('Add to classlist').': <b>ok</b>';
13671:             }
13672:             $output .= $linefeed;
13673:         }
13674:     } else {
13675:         $output = &mt('Assigning').' '.$three.' in '.$url.
13676:                ($start?', '.&mt('starting').' '.localtime($start):'').
13677:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13678:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13679:         if ($context eq 'auto') {
13680:             $output .= $result.$linefeed;
13681:         } else {
13682:             $output .= '<b>'.$result.'</b>'.$linefeed;
13683:         }
13684:     }
13685:     return $output;
13686: }
13687: 
13688: sub commit_studentrole {
13689:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13690:         $credits) = @_;
13691:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13692:     if ($context eq 'auto') {
13693:         $linefeed = "\n";
13694:     } else {
13695:         $linefeed = '<br />'."\n";
13696:     }
13697:     if (defined($one) && defined($two)) {
13698:         my $cid=$one.'_'.$two;
13699:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13700:         my $secchange = 0;
13701:         my $expire_role_result;
13702:         my $modify_section_result;
13703:         if ($oldsec ne '-1') { 
13704:             if ($oldsec ne $sec) {
13705:                 $secchange = 1;
13706:                 my $now = time;
13707:                 my $uurl='/'.$cid;
13708:                 $uurl=~s/\_/\//g;
13709:                 if ($oldsec) {
13710:                     $uurl.='/'.$oldsec;
13711:                 }
13712:                 $oldsecurl = $uurl;
13713:                 $expire_role_result = 
13714:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13715:                 if ($env{'request.course.sec'} ne '') { 
13716:                     if ($expire_role_result eq 'refused') {
13717:                         my @roles = ('st');
13718:                         my @statuses = ('previous');
13719:                         my @roledoms = ($one);
13720:                         my $withsec = 1;
13721:                         my %roleshash = 
13722:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13723:                                               \@statuses,\@roles,\@roledoms,$withsec);
13724:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13725:                             my ($oldstart,$oldend) = 
13726:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13727:                             if ($oldend > 0 && $oldend <= $now) {
13728:                                 $expire_role_result = 'ok';
13729:                             }
13730:                         }
13731:                     }
13732:                 }
13733:                 $result = $expire_role_result;
13734:             }
13735:         }
13736:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13737:             $modify_section_result = 
13738:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13739:                                                            undef,undef,undef,$sec,
13740:                                                            $end,$start,'','',$cid,
13741:                                                            '',$context,$credits);
13742:             if ($modify_section_result =~ /^ok/) {
13743:                 if ($secchange == 1) {
13744:                     if ($sec eq '') {
13745:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13746:                     } else {
13747:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13748:                     }
13749:                 } elsif ($oldsec eq '-1') {
13750:                     if ($sec eq '') {
13751:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13752:                     } else {
13753:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13754:                     }
13755:                 } else {
13756:                     if ($sec eq '') {
13757:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13758:                     } else {
13759:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13760:                     }
13761:                 }
13762:             } else {
13763:                 if ($secchange) { 
13764:                     $$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;
13765:                 } else {
13766:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13767:                 }
13768:             }
13769:             $result = $modify_section_result;
13770:         } elsif ($secchange == 1) {
13771:             if ($oldsec eq '') {
13772:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13773:             } else {
13774:                 $$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;
13775:             }
13776:             if ($expire_role_result eq 'refused') {
13777:                 my $newsecurl = '/'.$cid;
13778:                 $newsecurl =~ s/\_/\//g;
13779:                 if ($sec ne '') {
13780:                     $newsecurl.='/'.$sec;
13781:                 }
13782:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13783:                     if ($sec eq '') {
13784:                         $$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;
13785:                     } else {
13786:                         $$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;
13787:                     }
13788:                 }
13789:             }
13790:         }
13791:     } else {
13792:         $$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;
13793:         $result = "error: incomplete course id\n";
13794:     }
13795:     return $result;
13796: }
13797: 
13798: sub show_role_extent {
13799:     my ($scope,$context,$role) = @_;
13800:     $scope =~ s{^/}{};
13801:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13802:     push(@courseroles,'co');
13803:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13804:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13805:         $scope =~ s{/}{_};
13806:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13807:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13808:         my ($audom,$auname) = split(/\//,$scope);
13809:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13810:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13811:     } else {
13812:         $scope =~ s{/$}{};
13813:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13814:                    &Apache::lonnet::domain($scope,'description').'</span>');
13815:     }
13816: }
13817: 
13818: ############################################################
13819: ############################################################
13820: 
13821: sub check_clone {
13822:     my ($args,$linefeed) = @_;
13823:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13824:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13825:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13826:     my $clonemsg;
13827:     my $can_clone = 0;
13828:     my $lctype = lc($args->{'crstype'});
13829:     if ($lctype ne 'community') {
13830:         $lctype = 'course';
13831:     }
13832:     if ($clonehome eq 'no_host') {
13833:         if ($args->{'crstype'} eq 'Community') {
13834:             $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'});
13835:         } else {
13836:             $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'});
13837:         }     
13838:     } else {
13839: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13840:         if ($args->{'crstype'} eq 'Community') {
13841:             if ($clonedesc{'type'} ne 'Community') {
13842:                  $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'});
13843:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13844:             }
13845:         }
13846: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13847:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13848: 	    $can_clone = 1;
13849: 	} else {
13850: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13851: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13852: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13853:             if (grep(/^\*$/,@cloners)) {
13854:                 $can_clone = 1;
13855:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13856:                 $can_clone = 1;
13857:             } else {
13858:                 my $ccrole = 'cc';
13859:                 if ($args->{'crstype'} eq 'Community') {
13860:                     $ccrole = 'co';
13861:                 }
13862: 	        my %roleshash =
13863: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13864: 					 $args->{'ccdomain'},
13865:                                          'userroles',['active'],[$ccrole],
13866: 					 [$args->{'clonedomain'}]);
13867: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13868:                     $can_clone = 1;
13869:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13870:                     $can_clone = 1;
13871:                 } else {
13872:                     if ($args->{'crstype'} eq 'Community') {
13873:                         $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'});
13874:                     } else {
13875:                         $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'});
13876:                     }
13877: 	        }
13878: 	    }
13879:         }
13880:     }
13881:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13882: }
13883: 
13884: sub construct_course {
13885:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13886:     my $outcome;
13887:     my $linefeed =  '<br />'."\n";
13888:     if ($context eq 'auto') {
13889:         $linefeed = "\n";
13890:     }
13891: 
13892: #
13893: # Are we cloning?
13894: #
13895:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13896:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13897: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13898: 	if ($context ne 'auto') {
13899:             if ($clonemsg ne '') {
13900: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13901:             }
13902: 	}
13903: 	$outcome .= $clonemsg.$linefeed;
13904: 
13905:         if (!$can_clone) {
13906: 	    return (0,$outcome);
13907: 	}
13908:     }
13909: 
13910: #
13911: # Open course
13912: #
13913:     my $crstype = lc($args->{'crstype'});
13914:     my %cenv=();
13915:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13916:                                              $args->{'cdescr'},
13917:                                              $args->{'curl'},
13918:                                              $args->{'course_home'},
13919:                                              $args->{'nonstandard'},
13920:                                              $args->{'crscode'},
13921:                                              $args->{'ccuname'}.':'.
13922:                                              $args->{'ccdomain'},
13923:                                              $args->{'crstype'},
13924:                                              $cnum,$context,$category);
13925: 
13926:     # Note: The testing routines depend on this being output; see 
13927:     # Utils::Course. This needs to at least be output as a comment
13928:     # if anyone ever decides to not show this, and Utils::Course::new
13929:     # will need to be suitably modified.
13930:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13931:     if ($$courseid =~ /^error:/) {
13932:         return (0,$outcome);
13933:     }
13934: 
13935: #
13936: # Check if created correctly
13937: #
13938:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13939:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13940:     if ($crsuhome eq 'no_host') {
13941:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13942:         return (0,$outcome);
13943:     }
13944:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13945: 
13946: #
13947: # Do the cloning
13948: #   
13949:     if ($can_clone && $cloneid) {
13950: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13951: 	if ($context ne 'auto') {
13952: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13953: 	}
13954: 	$outcome .= $clonemsg.$linefeed;
13955: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13956: # Copy all files
13957: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13958: # Restore URL
13959: 	$cenv{'url'}=$oldcenv{'url'};
13960: # Restore title
13961: 	$cenv{'description'}=$oldcenv{'description'};
13962: # Restore creation date, creator and creation context.
13963:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13964:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13965:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13966: # Mark as cloned
13967: 	$cenv{'clonedfrom'}=$cloneid;
13968: # Need to clone grading mode
13969:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13970:         $cenv{'grading'}=$newenv{'grading'};
13971: # Do not clone these environment entries
13972:         &Apache::lonnet::del('environment',
13973:                   ['default_enrollment_start_date',
13974:                    'default_enrollment_end_date',
13975:                    'question.email',
13976:                    'policy.email',
13977:                    'comment.email',
13978:                    'pch.users.denied',
13979:                    'plc.users.denied',
13980:                    'hidefromcat',
13981:                    'checkforpriv',
13982:                    'categories'],
13983:                    $$crsudom,$$crsunum);
13984:     }
13985: 
13986: #
13987: # Set environment (will override cloned, if existing)
13988: #
13989:     my @sections = ();
13990:     my @xlists = ();
13991:     if ($args->{'crstype'}) {
13992:         $cenv{'type'}=$args->{'crstype'};
13993:     }
13994:     if ($args->{'crsid'}) {
13995:         $cenv{'courseid'}=$args->{'crsid'};
13996:     }
13997:     if ($args->{'crscode'}) {
13998:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13999:     }
14000:     if ($args->{'crsquota'} ne '') {
14001:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14002:     } else {
14003:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14004:     }
14005:     if ($args->{'ccuname'}) {
14006:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14007:                                         ':'.$args->{'ccdomain'};
14008:     } else {
14009:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14010:     }
14011:     if ($args->{'defaultcredits'}) {
14012:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14013:     }
14014:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14015:     if ($args->{'crssections'}) {
14016:         $cenv{'internal.sectionnums'} = '';
14017:         if ($args->{'crssections'} =~ m/,/) {
14018:             @sections = split/,/,$args->{'crssections'};
14019:         } else {
14020:             $sections[0] = $args->{'crssections'};
14021:         }
14022:         if (@sections > 0) {
14023:             foreach my $item (@sections) {
14024:                 my ($sec,$gp) = split/:/,$item;
14025:                 my $class = $args->{'crscode'}.$sec;
14026:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14027:                 $cenv{'internal.sectionnums'} .= $item.',';
14028:                 unless ($addcheck eq 'ok') {
14029:                     push @badclasses, $class;
14030:                 }
14031:             }
14032:             $cenv{'internal.sectionnums'} =~ s/,$//;
14033:         }
14034:     }
14035: # do not hide course coordinator from staff listing, 
14036: # even if privileged
14037:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14038: # add course coordinator's domain to domains to check for privileged users
14039: # if different to course domain
14040:     if ($$crsudom ne $args->{'ccdomain'}) {
14041:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14042:     }
14043: # add crosslistings
14044:     if ($args->{'crsxlist'}) {
14045:         $cenv{'internal.crosslistings'}='';
14046:         if ($args->{'crsxlist'} =~ m/,/) {
14047:             @xlists = split/,/,$args->{'crsxlist'};
14048:         } else {
14049:             $xlists[0] = $args->{'crsxlist'};
14050:         }
14051:         if (@xlists > 0) {
14052:             foreach my $item (@xlists) {
14053:                 my ($xl,$gp) = split/:/,$item;
14054:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14055:                 $cenv{'internal.crosslistings'} .= $item.',';
14056:                 unless ($addcheck eq 'ok') {
14057:                     push @badclasses, $xl;
14058:                 }
14059:             }
14060:             $cenv{'internal.crosslistings'} =~ s/,$//;
14061:         }
14062:     }
14063:     if ($args->{'autoadds'}) {
14064:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14065:     }
14066:     if ($args->{'autodrops'}) {
14067:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14068:     }
14069: # check for notification of enrollment changes
14070:     my @notified = ();
14071:     if ($args->{'notify_owner'}) {
14072:         if ($args->{'ccuname'} ne '') {
14073:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14074:         }
14075:     }
14076:     if ($args->{'notify_dc'}) {
14077:         if ($uname ne '') { 
14078:             push(@notified,$uname.':'.$udom);
14079:         }
14080:     }
14081:     if (@notified > 0) {
14082:         my $notifylist;
14083:         if (@notified > 1) {
14084:             $notifylist = join(',',@notified);
14085:         } else {
14086:             $notifylist = $notified[0];
14087:         }
14088:         $cenv{'internal.notifylist'} = $notifylist;
14089:     }
14090:     if (@badclasses > 0) {
14091:         my %lt=&Apache::lonlocal::texthash(
14092:                 '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',
14093:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14094:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14095:         );
14096:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14097:                            ' ('.$lt{'adby'}.')';
14098:         if ($context eq 'auto') {
14099:             $outcome .= $badclass_msg.$linefeed;
14100:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14101:             foreach my $item (@badclasses) {
14102:                 if ($context eq 'auto') {
14103:                     $outcome .= " - $item\n";
14104:                 } else {
14105:                     $outcome .= "<li>$item</li>\n";
14106:                 }
14107:             }
14108:             if ($context eq 'auto') {
14109:                 $outcome .= $linefeed;
14110:             } else {
14111:                 $outcome .= "</ul><br /><br /></div>\n";
14112:             }
14113:         } 
14114:     }
14115:     if ($args->{'no_end_date'}) {
14116:         $args->{'endaccess'} = 0;
14117:     }
14118:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14119:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14120:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14121:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14122:     if ($args->{'showphotos'}) {
14123:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14124:     }
14125:     $cenv{'internal.authtype'} = $args->{'authtype'};
14126:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14127:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14128:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14129:             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'); 
14130:             if ($context eq 'auto') {
14131:                 $outcome .= $krb_msg;
14132:             } else {
14133:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14134:             }
14135:             $outcome .= $linefeed;
14136:         }
14137:     }
14138:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14139:        if ($args->{'setpolicy'}) {
14140:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14141:        }
14142:        if ($args->{'setcontent'}) {
14143:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14144:        }
14145:     }
14146:     if ($args->{'reshome'}) {
14147: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14148: 	$cenv{'reshome'}=~s/\/+$/\//;
14149:     }
14150: #
14151: # course has keyed access
14152: #
14153:     if ($args->{'setkeys'}) {
14154:        $cenv{'keyaccess'}='yes';
14155:     }
14156: # if specified, key authority is not course, but user
14157: # only active if keyaccess is yes
14158:     if ($args->{'keyauth'}) {
14159: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14160: 	$user = &LONCAPA::clean_username($user);
14161: 	$domain = &LONCAPA::clean_username($domain);
14162: 	if ($user ne '' && $domain ne '') {
14163: 	    $cenv{'keyauth'}=$user.':'.$domain;
14164: 	}
14165:     }
14166: 
14167:     if ($args->{'disresdis'}) {
14168:         $cenv{'pch.roles.denied'}='st';
14169:     }
14170:     if ($args->{'disablechat'}) {
14171:         $cenv{'plc.roles.denied'}='st';
14172:     }
14173: 
14174:     # Record we've not yet viewed the Course Initialization Helper for this 
14175:     # course
14176:     $cenv{'course.helper.not.run'} = 1;
14177:     #
14178:     # Use new Randomseed
14179:     #
14180:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14181:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14182:     #
14183:     # The encryption code and receipt prefix for this course
14184:     #
14185:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14186:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14187:     #
14188:     # By default, use standard grading
14189:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14190: 
14191:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14192:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14193: #
14194: # Open all assignments
14195: #
14196:     if ($args->{'openall'}) {
14197:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14198:        my %storecontent = ($storeunder         => time,
14199:                            $storeunder.'.type' => 'date_start');
14200:        
14201:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14202:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14203:    }
14204: #
14205: # Set first page
14206: #
14207:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14208: 	    || ($cloneid)) {
14209: 	use LONCAPA::map;
14210: 	$outcome .= &mt('Setting first resource').': ';
14211: 
14212: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14213:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14214: 
14215:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14216:         my $title; my $url;
14217:         if ($args->{'firstres'} eq 'syl') {
14218: 	    $title=&mt('Syllabus');
14219:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14220:         } else {
14221:             $title=&mt('Table of Contents');
14222:             $url='/adm/navmaps';
14223:         }
14224: 
14225:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14226: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14227: 
14228: 	if ($errtext) { $fatal=2; }
14229:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14230:     }
14231: 
14232:     return (1,$outcome);
14233: }
14234: 
14235: ############################################################
14236: ############################################################
14237: 
14238: #SD
14239: # only Community and Course, or anything else?
14240: sub course_type {
14241:     my ($cid) = @_;
14242:     if (!defined($cid)) {
14243:         $cid = $env{'request.course.id'};
14244:     }
14245:     if (defined($env{'course.'.$cid.'.type'})) {
14246:         return $env{'course.'.$cid.'.type'};
14247:     } else {
14248:         return 'Course';
14249:     }
14250: }
14251: 
14252: sub group_term {
14253:     my $crstype = &course_type();
14254:     my %names = (
14255:                   'Course' => 'group',
14256:                   'Community' => 'group',
14257:                 );
14258:     return $names{$crstype};
14259: }
14260: 
14261: sub course_types {
14262:     my @types = ('official','unofficial','community');
14263:     my %typename = (
14264:                          official   => 'Official course',
14265:                          unofficial => 'Unofficial course',
14266:                          community  => 'Community',
14267:                    );
14268:     return (\@types,\%typename);
14269: }
14270: 
14271: sub icon {
14272:     my ($file)=@_;
14273:     my $curfext = lc((split(/\./,$file))[-1]);
14274:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14275:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14276:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14277: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14278: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14279: 	            $curfext.".gif") {
14280: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14281: 		$curfext.".gif";
14282: 	}
14283:     }
14284:     return &lonhttpdurl($iconname);
14285: } 
14286: 
14287: sub lonhttpdurl {
14288: #
14289: # Had been used for "small fry" static images on separate port 8080.
14290: # Modify here if lightweight http functionality desired again.
14291: # Currently eliminated due to increasing firewall issues.
14292: #
14293:     my ($url)=@_;
14294:     return $url;
14295: }
14296: 
14297: sub connection_aborted {
14298:     my ($r)=@_;
14299:     $r->print(" ");$r->rflush();
14300:     my $c = $r->connection;
14301:     return $c->aborted();
14302: }
14303: 
14304: #    Escapes strings that may have embedded 's that will be put into
14305: #    strings as 'strings'.
14306: sub escape_single {
14307:     my ($input) = @_;
14308:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14309:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14310:     return $input;
14311: }
14312: 
14313: #  Same as escape_single, but escape's "'s  This 
14314: #  can be used for  "strings"
14315: sub escape_double {
14316:     my ($input) = @_;
14317:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14318:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14319:     return $input;
14320: }
14321:  
14322: #   Escapes the last element of a full URL.
14323: sub escape_url {
14324:     my ($url)   = @_;
14325:     my @urlslices = split(/\//, $url,-1);
14326:     my $lastitem = &escape(pop(@urlslices));
14327:     return join('/',@urlslices).'/'.$lastitem;
14328: }
14329: 
14330: sub compare_arrays {
14331:     my ($arrayref1,$arrayref2) = @_;
14332:     my (@difference,%count);
14333:     @difference = ();
14334:     %count = ();
14335:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14336:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14337:         foreach my $element (keys(%count)) {
14338:             if ($count{$element} == 1) {
14339:                 push(@difference,$element);
14340:             }
14341:         }
14342:     }
14343:     return @difference;
14344: }
14345: 
14346: # -------------------------------------------------------- Initialize user login
14347: sub init_user_environment {
14348:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14349:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14350: 
14351:     my $public=($username eq 'public' && $domain eq 'public');
14352: 
14353: # See if old ID present, if so, remove
14354: 
14355:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14356:     my $now=time;
14357: 
14358:     if ($public) {
14359: 	my $max_public=100;
14360: 	my $oldest;
14361: 	my $oldest_time=0;
14362: 	for(my $next=1;$next<=$max_public;$next++) {
14363: 	    if (-e $lonids."/publicuser_$next.id") {
14364: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14365: 		if ($mtime<$oldest_time || !$oldest_time) {
14366: 		    $oldest_time=$mtime;
14367: 		    $oldest=$next;
14368: 		}
14369: 	    } else {
14370: 		$cookie="publicuser_$next";
14371: 		last;
14372: 	    }
14373: 	}
14374: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14375:     } else {
14376: 	# if this isn't a robot, kill any existing non-robot sessions
14377: 	if (!$args->{'robot'}) {
14378: 	    opendir(DIR,$lonids);
14379: 	    while ($filename=readdir(DIR)) {
14380: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14381: 		    unlink($lonids.'/'.$filename);
14382: 		}
14383: 	    }
14384: 	    closedir(DIR);
14385: 	}
14386: # Give them a new cookie
14387: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14388: 		                   : $now.$$.int(rand(10000)));
14389: 	$cookie="$username\_$id\_$domain\_$authhost";
14390:     
14391: # Initialize roles
14392: 
14393: 	($userroles,$firstaccenv,$timerintenv) = 
14394:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14395:     }
14396: # ------------------------------------ Check browser type and MathML capability
14397: 
14398:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14399:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14400: 
14401: # ------------------------------------------------------------- Get environment
14402: 
14403:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14404:     my ($tmp) = keys(%userenv);
14405:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14406:     } else {
14407: 	undef(%userenv);
14408:     }
14409:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14410: 	$form->{'interface'}=$userenv{'interface'};
14411:     }
14412:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14413: 
14414: # --------------- Do not trust query string to be put directly into environment
14415:     foreach my $option ('interface','localpath','localres') {
14416:         $form->{$option}=~s/[\n\r\=]//gs;
14417:     }
14418: # --------------------------------------------------------- Write first profile
14419: 
14420:     {
14421: 	my %initial_env = 
14422: 	    ("user.name"          => $username,
14423: 	     "user.domain"        => $domain,
14424: 	     "user.home"          => $authhost,
14425: 	     "browser.type"       => $clientbrowser,
14426: 	     "browser.version"    => $clientversion,
14427: 	     "browser.mathml"     => $clientmathml,
14428: 	     "browser.unicode"    => $clientunicode,
14429: 	     "browser.os"         => $clientos,
14430:              "browser.mobile"     => $clientmobile,
14431:              "browser.info"       => $clientinfo,
14432: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14433: 	     "request.course.fn"  => '',
14434: 	     "request.course.uri" => '',
14435: 	     "request.course.sec" => '',
14436: 	     "request.role"       => 'cm',
14437: 	     "request.role.adv"   => $env{'user.adv'},
14438: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14439: 
14440:         if ($form->{'localpath'}) {
14441: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14442: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14443:         }
14444: 	
14445: 	if ($form->{'interface'}) {
14446: 	    $form->{'interface'}=~s/\W//gs;
14447: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14448: 	    $env{'browser.interface'}=$form->{'interface'};
14449: 	}
14450: 
14451:         if ($form->{'iptoken'}) {
14452:             my $lonhost = $r->dir_config('lonHostID');
14453:             $initial_env{"user.noloadbalance"} = $lonhost;
14454:             $env{'user.noloadbalance'} = $lonhost;
14455:         }
14456: 
14457:         my %is_adv = ( is_adv => $env{'user.adv'} );
14458:         my %domdef;
14459:         unless ($domain eq 'public') {
14460:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14461:         }
14462: 
14463:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14464:             $userenv{'availabletools.'.$tool} = 
14465:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14466:                                                   undef,\%userenv,\%domdef,\%is_adv);
14467:         }
14468: 
14469:         foreach my $crstype ('official','unofficial','community') {
14470:             $userenv{'canrequest.'.$crstype} =
14471:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14472:                                                   'reload','requestcourses',
14473:                                                   \%userenv,\%domdef,\%is_adv);
14474:         }
14475: 
14476:         $userenv{'canrequest.author'} =
14477:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14478:                                         'reload','requestauthor',
14479:                                         \%userenv,\%domdef,\%is_adv);
14480:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14481:                                              $domain,$username);
14482:         my $reqstatus = $reqauthor{'author_status'};
14483:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
14484:             if (ref($reqauthor{'author'}) eq 'HASH') {
14485:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14486:                                                   $reqauthor{'author'}{'timestamp'};
14487:             }
14488:         }
14489: 
14490: 	$env{'user.environment'} = "$lonids/$cookie.id";
14491: 
14492: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14493: 		 &GDBM_WRCREAT(),0640)) {
14494: 	    &_add_to_env(\%disk_env,\%initial_env);
14495: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14496: 	    &_add_to_env(\%disk_env,$userroles);
14497:             if (ref($firstaccenv) eq 'HASH') {
14498:                 &_add_to_env(\%disk_env,$firstaccenv);
14499:             }
14500:             if (ref($timerintenv) eq 'HASH') {
14501:                 &_add_to_env(\%disk_env,$timerintenv);
14502:             }
14503: 	    if (ref($args->{'extra_env'})) {
14504: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14505: 	    }
14506: 	    untie(%disk_env);
14507: 	} else {
14508: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14509: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14510: 	    return 'error: '.$!;
14511: 	}
14512:     }
14513:     $env{'request.role'}='cm';
14514:     $env{'request.role.adv'}=$env{'user.adv'};
14515:     $env{'browser.type'}=$clientbrowser;
14516: 
14517:     return $cookie;
14518: 
14519: }
14520: 
14521: sub _add_to_env {
14522:     my ($idf,$env_data,$prefix) = @_;
14523:     if (ref($env_data) eq 'HASH') {
14524:         while (my ($key,$value) = each(%$env_data)) {
14525: 	    $idf->{$prefix.$key} = $value;
14526: 	    $env{$prefix.$key}   = $value;
14527:         }
14528:     }
14529: }
14530: 
14531: # --- Get the symbolic name of a problem and the url
14532: sub get_symb {
14533:     my ($request,$silent) = @_;
14534:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14535:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14536:     if ($symb eq '') {
14537:         if (!$silent) {
14538:             if (ref($request)) { 
14539:                 $request->print("Unable to handle ambiguous references:$url:.");
14540:             }
14541:             return ();
14542:         }
14543:     }
14544:     &Apache::lonenc::check_decrypt(\$symb);
14545:     return ($symb);
14546: }
14547: 
14548: # --------------------------------------------------------------Get annotation
14549: 
14550: sub get_annotation {
14551:     my ($symb,$enc) = @_;
14552: 
14553:     my $key = $symb;
14554:     if (!$enc) {
14555:         $key =
14556:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14557:     }
14558:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14559:     return $annotation{$key};
14560: }
14561: 
14562: sub clean_symb {
14563:     my ($symb,$delete_enc) = @_;
14564: 
14565:     &Apache::lonenc::check_decrypt(\$symb);
14566:     my $enc = $env{'request.enc'};
14567:     if ($delete_enc) {
14568:         delete($env{'request.enc'});
14569:     }
14570: 
14571:     return ($symb,$enc);
14572: }
14573: 
14574: sub build_release_hashes {
14575:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14576:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14577:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14578:                   (ref($randomizetry) eq 'HASH'));
14579:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14580:         my ($item,$name,$value) = split(/:/,$key);
14581:         if ($item eq 'parameter') {
14582:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14583:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14584:                     push(@{$checkparms->{$name}},$value);
14585:                 }
14586:             } else {
14587:                 push(@{$checkparms->{$name}},$value);
14588:             }
14589:         } elsif ($item eq 'resourcetag') {
14590:             if ($name eq 'responsetype') {
14591:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14592:             }
14593:         } elsif ($item eq 'course') {
14594:             if ($name eq 'crstype') {
14595:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14596:             }
14597:         }
14598:     }
14599:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14600:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14601:     return;
14602: }
14603: 
14604: sub update_content_constraints {
14605:     my ($cdom,$cnum,$chome,$cid) = @_;
14606:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14607:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14608:     my %checkresponsetypes;
14609:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14610:         my ($item,$name,$value) = split(/:/,$key);
14611:         if ($item eq 'resourcetag') {
14612:             if ($name eq 'responsetype') {
14613:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14614:             }
14615:         }
14616:     }
14617:     my $navmap = Apache::lonnavmaps::navmap->new();
14618:     if (defined($navmap)) {
14619:         my %allresponses;
14620:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14621:             my %responses = $res->responseTypes();
14622:             foreach my $key (keys(%responses)) {
14623:                 next unless(exists($checkresponsetypes{$key}));
14624:                 $allresponses{$key} += $responses{$key};
14625:             }
14626:         }
14627:         foreach my $key (keys(%allresponses)) {
14628:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14629:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14630:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14631:             }
14632:         }
14633:         undef($navmap);
14634:     }
14635:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14636:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14637:     }
14638:     return;
14639: }
14640: 
14641: sub allmaps_incourse {
14642:     my ($cdom,$cnum,$chome,$cid) = @_;
14643:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14644:         $cid = $env{'request.course.id'};
14645:         $cdom = $env{'course.'.$cid.'.domain'};
14646:         $cnum = $env{'course.'.$cid.'.num'};
14647:         $chome = $env{'course.'.$cid.'.home'};
14648:     }
14649:     my %allmaps = ();
14650:     my $lastchange =
14651:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14652:     if ($lastchange > $env{'request.course.tied'}) {
14653:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14654:         unless ($ferr) {
14655:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14656:         }
14657:     }
14658:     my $navmap = Apache::lonnavmaps::navmap->new();
14659:     if (defined($navmap)) {
14660:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14661:             $allmaps{$res->src()} = 1;
14662:         }
14663:     }
14664:     return \%allmaps;
14665: }
14666: 
14667: sub parse_supplemental_title {
14668:     my ($title) = @_;
14669: 
14670:     my ($foldertitle,$renametitle);
14671:     if ($title =~ /&amp;&amp;&amp;/) {
14672:         $title = &HTML::Entites::decode($title);
14673:     }
14674:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14675:         $renametitle=$4;
14676:         my ($time,$uname,$udom) = ($1,$2,$3);
14677:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14678:         my $name =  &plainname($uname,$udom);
14679:         $name = &HTML::Entities::encode($name,'"<>&\'');
14680:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14681:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14682:             $name.': <br />'.$foldertitle;
14683:     }
14684:     if (wantarray) {
14685:         return ($title,$foldertitle,$renametitle);
14686:     }
14687:     return $title;
14688: }
14689: 
14690: sub recurse_supplemental {
14691:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14692:     if ($suppmap) {
14693:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14694:         if ($fatal) {
14695:             $errors ++;
14696:         } else {
14697:             if ($#LONCAPA::map::resources > 0) {
14698:                 foreach my $res (@LONCAPA::map::resources) {
14699:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14700:                     if (($src ne '') && ($status eq 'res')) {
14701:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
14702:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
14703:                         } else {
14704:                             $numfiles ++;
14705:                         }
14706:                     }
14707:                 }
14708:             }
14709:         }
14710:     }
14711:     return ($numfiles,$errors);
14712: }
14713: 
14714: sub symb_to_docspath {
14715:     my ($symb) = @_;
14716:     return unless ($symb);
14717:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14718:     if ($resurl=~/\.(sequence|page)$/) {
14719:         $mapurl=$resurl;
14720:     } elsif ($resurl eq 'adm/navmaps') {
14721:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14722:     }
14723:     my $mapresobj;
14724:     my $navmap = Apache::lonnavmaps::navmap->new();
14725:     if (ref($navmap)) {
14726:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14727:     }
14728:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14729:     my $type=$2;
14730:     my $path;
14731:     if (ref($mapresobj)) {
14732:         my $pcslist = $mapresobj->map_hierarchy();
14733:         if ($pcslist ne '') {
14734:             foreach my $pc (split(/,/,$pcslist)) {
14735:                 next if ($pc <= 1);
14736:                 my $res = $navmap->getByMapPc($pc);
14737:                 if (ref($res)) {
14738:                     my $thisurl = $res->src();
14739:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14740:                     my $thistitle = $res->title();
14741:                     $path .= '&'.
14742:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14743:                              &escape($thistitle).
14744:                              ':'.$res->randompick().
14745:                              ':'.$res->randomout().
14746:                              ':'.$res->encrypted().
14747:                              ':'.$res->randomorder().
14748:                              ':'.$res->is_page();
14749:                 }
14750:             }
14751:         }
14752:         $path =~ s/^\&//;
14753:         my $maptitle = $mapresobj->title();
14754:         if ($mapurl eq 'default') {
14755:             $maptitle = 'Main Content';
14756:         }
14757:         $path .= (($path ne '')? '&' : '').
14758:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14759:                  &escape($maptitle).
14760:                  ':'.$mapresobj->randompick().
14761:                  ':'.$mapresobj->randomout().
14762:                  ':'.$mapresobj->encrypted().
14763:                  ':'.$mapresobj->randomorder().
14764:                  ':'.$mapresobj->is_page();
14765:     } else {
14766:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14767:         my $ispage = (($type eq 'page')? 1 : '');
14768:         if ($mapurl eq 'default') {
14769:             $maptitle = 'Main Content';
14770:         }
14771:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14772:                 &escape($maptitle).':::::'.$ispage;
14773:     }
14774:     unless ($mapurl eq 'default') {
14775:         $path = 'default&'.
14776:                 &escape('Main Content').
14777:                 ':::::&'.$path;
14778:     }
14779:     return $path;
14780: }
14781: 
14782: sub captcha_display {
14783:     my ($context,$lonhost) = @_;
14784:     my ($output,$error);
14785:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14786:     if ($captcha eq 'original') {
14787:         $output = &create_captcha();
14788:         unless ($output) {
14789:             $error = 'captcha'; 
14790:         }
14791:     } elsif ($captcha eq 'recaptcha') {
14792:         $output = &create_recaptcha($pubkey);
14793:         unless ($output) {
14794:             $error = 'recaptcha'; 
14795:         }
14796:     }
14797:     return ($output,$error);
14798: }
14799: 
14800: sub captcha_response {
14801:     my ($context,$lonhost) = @_;
14802:     my ($captcha_chk,$captcha_error);
14803:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14804:     if ($captcha eq 'original') {
14805:         ($captcha_chk,$captcha_error) = &check_captcha();
14806:     } elsif ($captcha eq 'recaptcha') {
14807:         $captcha_chk = &check_recaptcha($privkey);
14808:     } else {
14809:         $captcha_chk = 1;
14810:     }
14811:     return ($captcha_chk,$captcha_error);
14812: }
14813: 
14814: sub get_captcha_config {
14815:     my ($context,$lonhost) = @_;
14816:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14817:     my $hostname = &Apache::lonnet::hostname($lonhost);
14818:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14819:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14820:     if ($context eq 'usercreation') {
14821:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14822:         if (ref($domconfig{$context}) eq 'HASH') {
14823:             $hashtocheck = $domconfig{$context}{'cancreate'};
14824:             if (ref($hashtocheck) eq 'HASH') {
14825:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14826:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14827:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14828:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14829:                     }
14830:                     if ($privkey && $pubkey) {
14831:                         $captcha = 'recaptcha';
14832:                     } else {
14833:                         $captcha = 'original';
14834:                     }
14835:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14836:                     $captcha = 'original';
14837:                 }
14838:             }
14839:         } else {
14840:             $captcha = 'captcha';
14841:         }
14842:     } elsif ($context eq 'login') {
14843:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14844:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14845:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14846:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14847:             if ($privkey && $pubkey) {
14848:                 $captcha = 'recaptcha';
14849:             } else {
14850:                 $captcha = 'original';
14851:             }
14852:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14853:             $captcha = 'original';
14854:         }
14855:     }
14856:     return ($captcha,$pubkey,$privkey);
14857: }
14858: 
14859: sub create_captcha {
14860:     my %captcha_params = &captcha_settings();
14861:     my ($output,$maxtries,$tries) = ('',10,0);
14862:     while ($tries < $maxtries) {
14863:         $tries ++;
14864:         my $captcha = Authen::Captcha->new (
14865:                                            output_folder => $captcha_params{'output_dir'},
14866:                                            data_folder   => $captcha_params{'db_dir'},
14867:                                           );
14868:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14869: 
14870:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14871:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14872:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14873:                      '<input type="text" size="5" name="code" value="" /><br />'.
14874:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14875:             last;
14876:         }
14877:     }
14878:     return $output;
14879: }
14880: 
14881: sub captcha_settings {
14882:     my %captcha_params = (
14883:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14884:                            www_output_dir => "/captchaspool",
14885:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14886:                            numchars       => '5',
14887:                          );
14888:     return %captcha_params;
14889: }
14890: 
14891: sub check_captcha {
14892:     my ($captcha_chk,$captcha_error);
14893:     my $code = $env{'form.code'};
14894:     my $md5sum = $env{'form.crypt'};
14895:     my %captcha_params = &captcha_settings();
14896:     my $captcha = Authen::Captcha->new(
14897:                       output_folder => $captcha_params{'output_dir'},
14898:                       data_folder   => $captcha_params{'db_dir'},
14899:                   );
14900:     $captcha_chk = $captcha->check_code($code,$md5sum);
14901:     my %captcha_hash = (
14902:                         0       => 'Code not checked (file error)',
14903:                        -1      => 'Failed: code expired',
14904:                        -2      => 'Failed: invalid code (not in database)',
14905:                        -3      => 'Failed: invalid code (code does not match crypt)',
14906:     );
14907:     if ($captcha_chk != 1) {
14908:         $captcha_error = $captcha_hash{$captcha_chk}
14909:     }
14910:     return ($captcha_chk,$captcha_error);
14911: }
14912: 
14913: sub create_recaptcha {
14914:     my ($pubkey) = @_;
14915:     my $use_ssl;
14916:     if ($ENV{'SERVER_PORT'} == 443) {
14917:         $use_ssl = 1;
14918:     }
14919:     my $captcha = Captcha::reCAPTCHA->new;
14920:     return $captcha->get_options_setter({theme => 'white'})."\n".
14921:            $captcha->get_html($pubkey,undef,$use_ssl).
14922:            &mt('If either word is hard to read, [_1] will replace them.',
14923:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14924:            '<br /><br />';
14925: }
14926: 
14927: sub check_recaptcha {
14928:     my ($privkey) = @_;
14929:     my $captcha_chk;
14930:     my $captcha = Captcha::reCAPTCHA->new;
14931:     my $captcha_result =
14932:         $captcha->check_answer(
14933:                                 $privkey,
14934:                                 $ENV{'REMOTE_ADDR'},
14935:                                 $env{'form.recaptcha_challenge_field'},
14936:                                 $env{'form.recaptcha_response_field'},
14937:                               );
14938:     if ($captcha_result->{is_valid}) {
14939:         $captcha_chk = 1;
14940:     }
14941:     return $captcha_chk;
14942: }
14943: 
14944: sub cleanup_html {
14945:     my ($incoming) = @_;
14946:     my $outgoing;
14947:     if ($incoming ne '') {
14948:         $outgoing = $incoming;
14949:         $outgoing =~ s/;/&#059;/g;
14950:         $outgoing =~ s/\#/&#035;/g;
14951:         $outgoing =~ s/\&/&#038;/g;
14952:         $outgoing =~ s/</&#060;/g;
14953:         $outgoing =~ s/>/&#062;/g;
14954:         $outgoing =~ s/\(/&#040/g;
14955:         $outgoing =~ s/\)/&#041;/g;
14956:         $outgoing =~ s/"/&#034;/g;
14957:         $outgoing =~ s/'/&#039;/g;
14958:         $outgoing =~ s/\$/&#036;/g;
14959:         $outgoing =~ s{/}{&#047;}g;
14960:         $outgoing =~ s/=/&#061;/g;
14961:         $outgoing =~ s/\\/&#092;/g
14962:     }
14963:     return $outgoing;
14964: }
14965: 
14966: =pod
14967: 
14968: =back
14969: 
14970: =cut
14971: 
14972: 1;
14973: __END__;
14974: 

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