Annotation of loncom/interface/loncommon.pm, revision 1.1172

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1172  ! raeburn     4: # $Id: loncommon.pm,v 1.1171 2014/01/21 14:38:51 kruse Exp $
1.10      albertel    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: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.479     albertel   72: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    73: use DateTime::TimeZone;
1.687     raeburn    74: use DateTime::Locale::Catalog;
1.1091    foxr       75: use Text::Aspell;
1.1094    raeburn    76: use Authen::Captcha;
                     77: use Captcha::reCAPTCHA;
1.117     www        78: 
1.517     raeburn    79: # ---------------------------------------------- Designs
                     80: use vars qw(%defaultdesign);
                     81: 
1.22      www        82: my $readit;
                     83: 
1.517     raeburn    84: 
1.157     matthew    85: ##
                     86: ## Global Variables
                     87: ##
1.46      matthew    88: 
1.643     foxr       89: 
                     90: # ----------------------------------------------- SSI with retries:
                     91: #
                     92: 
                     93: =pod
                     94: 
1.648     raeburn    95: =head1 Server Side include with retries:
1.643     foxr       96: 
                     97: =over 4
                     98: 
1.648     raeburn    99: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      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:
1.648     raeburn   106: 
                    107: =over 4
                    108: 
1.643     foxr      109: resource   - Identifies the resource to insert.
1.648     raeburn   110: 
1.643     foxr      111: retries    - Count of the number of retries allowed.
1.648     raeburn   112: 
1.643     foxr      113: form       - Hash that identifies the rendering options.
                    114: 
1.648     raeburn   115: =back
                    116: 
                    117: Returns:
                    118: 
                    119: =over 4
                    120: 
1.643     foxr      121: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   122: 
1.643     foxr      123: response   - The response from the last attempt (which may or may not have been successful.
                    124: 
1.648     raeburn   125: =back
                    126: 
                    127: =back
                    128: 
1.643     foxr      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;
1.650     www       144:         if (!$ok) {
                    145:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    146:         }
1.643     foxr      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: 
1.20      www       159: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  160: my %language;
1.124     www       161: my %supported_language;
1.1088    foxr      162: my %supported_codes;
1.1048    foxr      163: my %latex_language;		# For choosing hyphenation in <transl..>
                    164: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  165: my %cprtag;
1.192     taceyjo1  166: my %scprtag;
1.351     www       167: my %fe; my %fd; my %fm;
1.41      ng        168: my %category_extensions;
1.12      harris41  169: 
1.46      matthew   170: # ---------------------------------------------- Thesaurus variables
1.144     matthew   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.
1.46      matthew   176: 
                    177: my %Keywords;
                    178: my $thesaurus_db_file;
                    179: 
1.144     matthew   180: #
                    181: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    182: # thesaurus.tab, and filecategories.tab.
                    183: #
1.18      www       184: BEGIN {
1.46      matthew   185:     # Variable initialization
                    186:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    187:     #
1.22      www       188:     unless ($readit) {
1.12      harris41  189: # ------------------------------------------------------------------- languages
                    190:     {
1.158     raeburn   191:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    192:                                    '/language.tab';
                    193:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  194:             while (my $line = <$fh>) {
                    195:                 next if ($line=~/^\#/);
                    196:                 chomp($line);
1.1088    foxr      197:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   198:                 $language{$key}=$val.' - '.$enc;
                    199:                 if ($sup) {
                    200:                     $supported_language{$key}=$sup;
1.1088    foxr      201: 		    $supported_codes{$key}   = $code;
1.158     raeburn   202:                 }
1.1048    foxr      203: 		if ($latex) {
                    204: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      205: 		    $latex_language{$code} = $latex;
1.1048    foxr      206: 		}
1.158     raeburn   207:             }
                    208:             close($fh);
                    209:         }
1.12      harris41  210:     }
                    211: # ------------------------------------------------------------------ copyrights
                    212:     {
1.158     raeburn   213:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    214:                                   '/copyright.tab';
                    215:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  216:             while (my $line = <$fh>) {
                    217:                 next if ($line=~/^\#/);
                    218:                 chomp($line);
                    219:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   220:                 $cprtag{$key}=$val;
                    221:             }
                    222:             close($fh);
                    223:         }
1.12      harris41  224:     }
1.351     www       225: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  226:     {
                    227:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    228:                                   '/source_copyright.tab';
                    229:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  230:             while (my $line = <$fh>) {
                    231:                 next if ($line =~ /^\#/);
                    232:                 chomp($line);
                    233:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  234:                 $scprtag{$key}=$val;
                    235:             }
                    236:             close($fh);
                    237:         }
                    238:     }
1.63      www       239: 
1.517     raeburn   240: # -------------------------------------------------------------- default domain designs
1.63      www       241:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   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);
1.63      www       251:     }
                    252: 
1.15      harris41  253: # ------------------------------------------------------------- file categories
                    254:     {
1.158     raeburn   255:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    256:                                   '/filecategories.tab';
                    257:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  258: 	    while (my $line = <$fh>) {
                    259: 		next if ($line =~ /^\#/);
                    260: 		chomp($line);
                    261:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   262:                 push @{$category_extensions{lc($category)}},$extension;
                    263:             }
                    264:             close($fh);
                    265:         }
                    266: 
1.15      harris41  267:     }
1.12      harris41  268: # ------------------------------------------------------------------ file types
                    269:     {
1.158     raeburn   270:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    271:                '/filetypes.tab';
                    272:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  273:             while (my $line = <$fh>) {
                    274: 		next if ($line =~ /^\#/);
                    275: 		chomp($line);
                    276:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   277:                 if ($descr ne '') {
                    278:                     $fe{$ending}=lc($emb);
                    279:                     $fd{$ending}=$descr;
1.351     www       280:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   281:                 }
                    282:             }
                    283:             close($fh);
                    284:         }
1.12      harris41  285:     }
1.22      www       286:     &Apache::lonnet::logthis(
1.705     tempelho  287:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       288:     $readit=1;
1.46      matthew   289:     }  # end of unless($readit) 
1.32      matthew   290:     
                    291: }
1.112     bowersj2  292: 
1.42      matthew   293: ###############################################################
                    294: ##           HTML and Javascript Helper Functions            ##
                    295: ###############################################################
                    296: 
                    297: =pod 
                    298: 
1.112     bowersj2  299: =head1 HTML and Javascript Functions
1.42      matthew   300: 
1.112     bowersj2  301: =over 4
                    302: 
1.648     raeburn   303: =item * &browser_and_searcher_javascript()
1.112     bowersj2  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.
1.42      matthew   309: 
1.648     raeburn   310: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   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
1.185     www       318: with the given extension.  Can be a comma separated list.
1.42      matthew   319: 
                    320: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
1.648     raeburn   323: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   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.
1.542     raeburn   329: 
1.42      matthew   330: =cut
                    331: 
                    332: sub browser_and_searcher_javascript {
1.199     albertel  333:     my ($mode)=@_;
                    334:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  335:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   336:     return <<END;
1.219     albertel  337: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   338:     var editbrowser = null;
1.135     albertel  339:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       340:         var url = '$resurl/?';
1.42      matthew   341:         if (editbrowser == null) {
                    342:             url += 'launch=1&';
                    343:         }
                    344:         url += 'catalogmode=interactive&';
1.199     albertel  345:         url += 'mode=$mode&';
1.611     albertel  346:         url += 'inhibitmenu=yes&';
1.42      matthew   347:         url += 'form=' + formname + '&';
                    348:         if (only != null) {
                    349:             url += 'only=' + only + '&';
1.217     albertel  350:         } else {
                    351:             url += 'only=&';
                    352: 	}
1.42      matthew   353:         if (omit != null) {
                    354:             url += 'omit=' + omit + '&';
1.217     albertel  355:         } else {
                    356:             url += 'omit=&';
                    357: 	}
1.135     albertel  358:         if (titleelement != null) {
                    359:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  360:         } else {
                    361: 	    url += 'titleelement=&';
                    362: 	}
1.42      matthew   363:         url += 'element=' + elementname + '';
                    364:         var title = 'Browser';
1.435     albertel  365:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   366:         options += ',width=700,height=600';
                    367:         editbrowser = open(url,title,options,'1');
                    368:         editbrowser.focus();
                    369:     }
                    370:     var editsearcher;
1.135     albertel  371:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   372:         var url = '/adm/searchcat?';
                    373:         if (editsearcher == null) {
                    374:             url += 'launch=1&';
                    375:         }
                    376:         url += 'catalogmode=interactive&';
1.199     albertel  377:         url += 'mode=$mode&';
1.42      matthew   378:         url += 'form=' + formname + '&';
1.135     albertel  379:         if (titleelement != null) {
                    380:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  381:         } else {
                    382: 	    url += 'titleelement=&';
                    383: 	}
1.42      matthew   384:         url += 'element=' + elementname + '';
                    385:         var title = 'Search';
1.435     albertel  386:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   387:         options += ',width=700,height=600';
                    388:         editsearcher = open(url,title,options,'1');
                    389:         editsearcher.focus();
                    390:     }
1.219     albertel  391: // END LON-CAPA Internal -->
1.42      matthew   392: END
1.170     www       393: }
                    394: 
                    395: sub lastresurl {
1.258     albertel  396:     if ($env{'environment.lastresurl'}) {
                    397: 	return $env{'environment.lastresurl'}
1.170     www       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});
1.646     raeburn   408:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       409:     return 1;
1.42      matthew   410: }
                    411: 
1.74      www       412: sub studentbrowser_javascript {
1.111     www       413:    unless (
1.258     albertel  414:             (($env{'request.course.id'}) && 
1.302     albertel  415:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    416: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    417: 					  '/'.$env{'request.course.sec'})
                    418: 	      ))
1.258     albertel  419:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       420:           ) { return ''; }  
1.74      www       421:    return (<<'ENDSTDBRW');
1.776     bisitz    422: <script type="text/javascript" language="Javascript">
1.824     bisitz    423: // <![CDATA[
1.74      www       424:     var stdeditbrowser;
1.999     www       425:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       426:         var url = '/adm/pickstudent?';
                    427:         var filter;
1.558     albertel  428: 	if (!ignorefilter) {
                    429: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    430: 	}
1.74      www       431:         if (filter != null) {
                    432:            if (filter != '') {
                    433:                url += 'filter='+filter+'&';
                    434: 	   }
                    435:         }
                    436:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       437:                                     '&udomelement='+udom+
                    438:                                     '&clicker='+clicker;
1.111     www       439: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   440:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       441:         var title = 'Student_Browser';
1.74      www       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:     }
1.824     bisitz    447: // ]]>
1.74      www       448: </script>
                    449: ENDSTDBRW
                    450: }
1.42      matthew   451: 
1.1003    www       452: sub resourcebrowser_javascript {
                    453:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       454:    return (<<'ENDRESBRW');
1.1003    www       455: <script type="text/javascript" language="Javascript">
                    456: // <![CDATA[
                    457:     var reseditbrowser;
1.1004    www       458:     function openresbrowser(formname,reslink) {
1.1005    www       459:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       460:         var title = 'Resource_Browser';
                    461:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       462:         options += ',width=700,height=500';
1.1004    www       463:         reseditbrowser = open(url,title,options,'1');
                    464:         reseditbrowser.focus();
1.1003    www       465:     }
                    466: // ]]>
                    467: </script>
1.1004    www       468: ENDRESBRW
1.1003    www       469: }
                    470: 
1.74      www       471: sub selectstudent_link {
1.999     www       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)."'";
1.258     albertel  476:    if ($env{'request.course.id'}) {  
1.302     albertel  477:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    478: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    479: 					'/'.$env{'request.course.sec'})) {
1.111     www       480: 	   return '';
                    481:        }
1.999     www       482:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   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>';
1.74      www       489:    }
1.258     albertel  490:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       491:        $callargs .= ",'',1"; 
1.793     raeburn   492:        return '<span class="LC_nobreak">'.
                    493:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    494:               &mt('Select User').'</a></span>';
1.111     www       495:    }
                    496:    return '';
1.91      www       497: }
                    498: 
1.1004    www       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: 
1.653     raeburn   512: sub authorbrowser_javascript {
                    513:     return <<"ENDAUTHORBRW";
1.776     bisitz    514: <script type="text/javascript" language="JavaScript">
1.824     bisitz    515: // <![CDATA[
1.653     raeburn   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: 
1.824     bisitz    528: // ]]>
1.653     raeburn   529: </script>
                    530: ENDAUTHORBRW
                    531: }
                    532: 
1.91      www       533: sub coursebrowser_javascript {
1.1116    raeburn   534:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    535:         $credits_element) = @_;
1.932     raeburn   536:     my $wintitle = 'Course_Browser';
1.931     raeburn   537:     if ($crstype eq 'Community') {
1.932     raeburn   538:         $wintitle = 'Community_Browser';
1.909     raeburn   539:     }
1.876     raeburn   540:     my $id_functions = &javascript_index_functions();
                    541:     my $output = '
1.776     bisitz    542: <script type="text/javascript" language="JavaScript">
1.824     bisitz    543: // <![CDATA[
1.468     raeburn   544:     var stdeditbrowser;'."\n";
1.876     raeburn   545: 
                    546:     $output .= <<"ENDSTDBRW";
1.909     raeburn   547:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       548:         var url = '/adm/pickcourse?';
1.895     raeburn   549:         var formid = getFormIdByName(formname);
1.876     raeburn   550:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  551:         if (domainfilter != null) {
                    552:            if (domainfilter != '') {
                    553:                url += 'domainfilter='+domainfilter+'&';
                    554: 	   }
                    555:         }
1.91      www       556:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  557: 	                            '&cdomelement='+udom+
                    558:                                     '&cnameelement='+desc;
1.468     raeburn   559:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   560:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   561:                 url += '&roleelement='+extra_element;
                    562:                 if (domainfilter == null || domainfilter == '') {
                    563:                     url += '&domainfilter='+extra_element;
                    564:                 }
1.234     raeburn   565:             }
1.468     raeburn   566:             else {
                    567:                 if (formname == 'portform') {
                    568:                     url += '&setroles='+extra_element;
1.800     raeburn   569:                 } else {
                    570:                     if (formname == 'rules') {
                    571:                         url += '&fixeddom='+extra_element; 
                    572:                     }
1.468     raeburn   573:                 }
                    574:             }     
1.230     raeburn   575:         }
1.909     raeburn   576:         if (type != null && type != '') {
                    577:             url += '&type='+type;
                    578:         }
                    579:         if (type_elem != null && type_elem != '') {
                    580:             url += '&typeelement='+type_elem;
                    581:         }
1.872     raeburn   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:         }
1.293     raeburn   587:         if (multflag !=null && multflag != '') {
                    588:             url += '&multiple='+multflag;
                    589:         }
1.909     raeburn   590:         var title = '$wintitle';
1.91      www       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:     }
1.876     raeburn   596: $id_functions
                    597: ENDSTDBRW
1.1116    raeburn   598:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    599:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    600:                                       $credits_element);
1.876     raeburn   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: }
1.468     raeburn   628: 
1.876     raeburn   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;
1.468     raeburn   640:             }
                    641:         }
                    642:     }
1.876     raeburn   643:     return userdom;
                    644: }
                    645: 
                    646: ENDJS
1.468     raeburn   647: 
1.876     raeburn   648: }
                    649: 
1.1017    raeburn   650: sub javascript_array_indexof {
1.1018    raeburn   651:     return <<ENDJS;
1.1017    raeburn   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]);
1.1088    foxr      669:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   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: 
1.876     raeburn   695: sub userbrowser_javascript {
                    696:     my $id_functions = &javascript_index_functions();
                    697:     return <<"ENDUSERBRW";
                    698: 
1.888     raeburn   699: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   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+
1.881     raeburn   712:                                 '&hideudomelement='+hideudom+
                    713:                                 '&coursedom='+crsdom;
1.888     raeburn   714:     if ((caller != null) && (caller != undefined)) {
                    715:         url += '&caller='+caller;
                    716:     }
1.876     raeburn   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: 
1.888     raeburn   724: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   725:     var formid = getFormIdByName(formname);
                    726:     if (formid > -1) {
1.888     raeburn   727:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   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;
1.888     raeburn   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;
1.876     raeburn   744:                     }
                    745:                 }
1.468     raeburn   746:             }
                    747:         }
                    748:     }
1.876     raeburn   749:     return;
                    750: }
                    751: 
                    752: $id_functions
                    753: ENDUSERBRW
1.468     raeburn   754: }
                    755: 
                    756: sub setsec_javascript {
1.1116    raeburn   757:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   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:     }
1.468     raeburn   779:     my $setsections = qq|
                    780: function setSect(sectionlist) {
1.629     raeburn   781:     var sectionsArray = new Array();
                    782:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    783:         sectionsArray = sectionlist.split(",");
                    784:     }
1.468     raeburn   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:     }
1.91      www       811: }
1.905     raeburn   812: 
                    813: function setRole(crstype) {
1.468     raeburn   814: |;
1.905     raeburn   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:     }
1.1116    raeburn   852:     if ($credits_element) {
                    853:         $setsections .= qq|
                    854: function setCredits(defaultcredits) {
                    855:     document.$formname.$credits_element.value = defaultcredits;
                    856:     return;
                    857: }
                    858: |;
                    859:     }
1.468     raeburn   860:     return $setsections;
                    861: }
                    862: 
1.91      www       863: sub selectcourse_link {
1.909     raeburn   864:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    865:        $typeelement) = @_;
                    866:    my $type = $selecttype;
1.871     raeburn   867:    my $linktext = &mt('Select Course');
                    868:    if ($selecttype eq 'Community') {
1.909     raeburn   869:        $linktext = &mt('Select Community');
1.906     raeburn   870:    } elsif ($selecttype eq 'Course/Community') {
                    871:        $linktext = &mt('Select Course/Community');
1.909     raeburn   872:        $type = '';
1.1019    raeburn   873:    } elsif ($selecttype eq 'Select') {
                    874:        $linktext = &mt('Select');
                    875:        $type = '';
1.871     raeburn   876:    }
1.787     bisitz    877:    return '<span class="LC_nobreak">'
                    878:          ."<a href='"
                    879:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    880:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   881:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   882:          ."'>".$linktext.'</a>'
1.787     bisitz    883:          .'</span>';
1.74      www       884: }
1.42      matthew   885: 
1.653     raeburn   886: sub selectauthor_link {
                    887:    my ($form,$udom)=@_;
                    888:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    889:           &mt('Select Author').'</a>';
                    890: }
                    891: 
1.876     raeburn   892: sub selectuser_link {
1.881     raeburn   893:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   894:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   895:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   896:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   897:            ');">'.$linktext.'</a>';
1.876     raeburn   898: }
                    899: 
1.273     raeburn   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++) {
1.1093    raeburn   905:             if (!field[i].disabled) { 
                    906:                 field[i].checked = true;
                    907:             }
1.273     raeburn   908:         }
                    909:     } else {
1.1093    raeburn   910:         if (!field.disabled) { 
                    911:             field.checked = true;
                    912:         }
1.273     raeburn   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 ;
1.543     albertel  920:         }
                    921:     } else {
1.273     raeburn   922:         field.checked = false ;
                    923:     }
                    924: }
                    925: ENDSCRT
                    926:     return $jscript;
                    927: }
                    928: 
1.656     www       929: sub select_timezone {
1.659     raeburn   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:    }
1.657     raeburn   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";
1.656     www       946:    }
                    947:    $output.="</select>";
                    948:    return $output;
                    949: }
1.273     raeburn   950: 
1.687     raeburn   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'};
1.695     raeburn   969:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   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: 
1.792     raeburn  1002: sub select_language {
                   1003:     my ($name,$selected,$includeempty) = @_;
                   1004:     my %langchoices;
                   1005:     if ($includeempty) {
1.1117    raeburn  1006:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1007:     }
                   1008:     foreach my $id (&languageids()) {
                   1009:         my $code = &supportedlanguagecode($id);
                   1010:         if ($code) {
                   1011:             $langchoices{$code} = &plainlanguagedescription($id);
                   1012:         }
                   1013:     }
1.1117    raeburn  1014:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1015:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1016: }
                   1017: 
1.42      matthew  1018: =pod
1.36      matthew  1019: 
1.1088    foxr     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: 
1.648     raeburn  1047: =item * &linked_select_forms(...)
1.36      matthew  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
1.609     raeburn  1053: order unless a defined order is provided.
1.36      matthew  1054: 
                   1055: linked_select_forms takes the following ordered inputs:
                   1056: 
                   1057: =over 4
                   1058: 
1.112     bowersj2 1059: =item * $formname, the name of the <form> tag
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $firstdefault, the default value for the first menu
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1066: 
1.112     bowersj2 1067: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1068: 
1.112     bowersj2 1069: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1070: 
1.609     raeburn  1071: =item * $menuorder, the order of values in the first menu
                   1072: 
1.1115    raeburn  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: 
1.41      ng       1079: =back 
                   1080: 
1.36      matthew  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 
1.41      ng       1084: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1085: and text for the second menu are given in the hash pointed to by 
                   1086: $menu{$choice1}->{'select2'}.  
                   1087: 
1.112     bowersj2 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"
1.609     raeburn  1095:                            },
                   1096:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1097:                    },
                   1098:                A2 => { text =>"Choice A2" ,
                   1099:                        default => "C2",
                   1100:                        select2 => { 
                   1101:                            C1 => "Choice C1",
                   1102:                            C2 => "Choice C2",
                   1103:                            C3 => "Choice C3"
1.609     raeburn  1104:                            },
                   1105:                        order => ['C2','C1','C3'],
1.112     bowersj2 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"
1.609     raeburn  1117:                            },
                   1118:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1119:                    }
                   1120:                );
1.36      matthew  1121: 
                   1122: =cut
                   1123: 
                   1124: sub linked_select_forms {
                   1125:     my ($formname,
                   1126:         $middletext,
                   1127:         $firstdefault,
                   1128:         $firstselectname,
                   1129:         $secondselectname, 
1.609     raeburn  1130:         $hashref,
                   1131:         $menuorder,
1.1115    raeburn  1132:         $onchangefirst,
                   1133:         $onchangesecond
1.36      matthew  1134:         ) = @_;
                   1135:     my $second = "document.$formname.$secondselectname";
                   1136:     my $first = "document.$formname.$firstselectname";
                   1137:     # output the javascript to do the changing
                   1138:     my $result = '';
1.776     bisitz   1139:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1140:     $result.="// <![CDATA[\n";
1.36      matthew  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";
1.609     raeburn  1148:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1149:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1150:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1151:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1152:         }
1.36      matthew  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]);
1.143     matthew  1179:         $second.options[i].value = values[i];
1.36      matthew  1180:         $second.options[i].text = texts[i];
                   1181:         if (values[i] == select2def) {
                   1182:             $second.options[i].selected = true;
                   1183:         }
                   1184:     }
                   1185: }
1.824     bisitz   1186: // ]]>
1.36      matthew  1187: </script>
                   1188: END
                   1189:     # output the initial values for the selection lists
1.1115    raeburn  1190:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1191:     my @order = sort(keys(%{$hashref}));
                   1192:     if (ref($menuorder) eq 'ARRAY') {
                   1193:         @order = @{$menuorder};
                   1194:     }
                   1195:     foreach my $value (@order) {
1.36      matthew  1196:         $result.="    <option value=\"$value\" ";
1.253     albertel 1197:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1198:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1199:     }
                   1200:     $result .= "</select>\n";
                   1201:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1202:     $result .= $middletext;
1.1115    raeburn  1203:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1204:     if ($onchangesecond) {
                   1205:         $result .= ' onchange="'.$onchangesecond.'"';
                   1206:     }
                   1207:     $result .= ">\n";
1.36      matthew  1208:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  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) {
1.36      matthew  1215:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1216:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1217:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1218:     }
                   1219:     $result .= "</select>\n";
                   1220:     #    return $debug;
                   1221:     return $result;
                   1222: }   #  end of sub linked_select_forms {
                   1223: 
1.45      matthew  1224: =pod
1.44      bowersj2 1225: 
1.973     raeburn  1226: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1227: 
1.112     bowersj2 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
1.973     raeburn  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.
1.44      bowersj2 1249: 
                   1250: =cut
                   1251: 
                   1252: sub help_open_topic {
1.973     raeburn  1253:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1254:     $text = "" if (not defined $text);
1.44      bowersj2 1255:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1256:     $width = 500 if (not defined $width);
1.44      bowersj2 1257:     $height = 400 if (not defined $height);
                   1258:     my $filename = $topic;
                   1259:     $filename =~ s/ /_/g;
                   1260: 
1.48      bowersj2 1261:     my $template = "";
                   1262:     my $link;
1.572     banghart 1263:     
1.159     www      1264:     $topic=~s/\W/\_/g;
1.44      bowersj2 1265: 
1.572     banghart 1266:     if (!$stayOnPage) {
1.1033    www      1267: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      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'))";
1.572     banghart 1270:     } else {
1.48      bowersj2 1271: 	$link = "/adm/help/${filename}.hlp";
                   1272:     }
                   1273: 
                   1274:     # Add the text
1.755     neumanie 1275:     if ($text ne "") {	
1.763     bisitz   1276: 	$template.='<span class="LC_help_open_topic">'
                   1277:                   .'<a target="_top" href="'.$link.'">'
                   1278:                   .$text.'</a>';
1.48      bowersj2 1279:     }
                   1280: 
1.763     bisitz   1281:     # (Always) Add the graphic
1.179     matthew  1282:     my $title = &mt('Online Help');
1.667     raeburn  1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1284:     if ($imgid ne '') {
                   1285:         $imgid = ' id="'.$imgid.'"';
                   1286:     }
1.763     bisitz   1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1288:               .'<img src="'.$helpicon.'" border="0"'
                   1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1291:               .' /></a>';
                   1292:     if ($text ne "") {	
                   1293:         $template.='</span>';
                   1294:     }
1.44      bowersj2 1295:     return $template;
                   1296: 
1.106     bowersj2 1297: }
                   1298: 
                   1299: # This is a quicky function for Latex cheatsheet editing, since it 
                   1300: # appears in at least four places
                   1301: sub helpLatexCheatsheet {
1.1037    www      1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1303:     my $out;
1.106     bowersj2 1304:     my $addOther = '';
1.732     raeburn  1305:     if ($topic) {
1.1037    www      1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1307:     }
                   1308:     $out = '<span>' # Start cheatsheet
                   1309: 	  .$addOther
                   1310:           .'<span>'
1.1037    www      1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1312: 	  .'</span> <span>'
1.1037    www      1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span>';
1.732     raeburn  1315:     unless ($not_author) {
1.763     bisitz   1316:         $out .= ' <span>'
1.1037    www      1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1318: 	       .'</span>';
1.732     raeburn  1319:     }
1.763     bisitz   1320:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1321:     return $out;
1.172     www      1322: }
                   1323: 
1.430     albertel 1324: sub general_help {
                   1325:     my $helptopic='Student_Intro';
                   1326:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1327: 	$helptopic='Authoring_Intro';
1.907     raeburn  1328:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1329: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1330:     } elsif ($env{'request.role'}=~/^dc/) {
                   1331:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 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">
1.824     bisitz   1348: // <![CDATA[
1.430     albertel 1349: banner_link = '$banner_link';
1.824     bisitz   1350: // ]]>
1.430     albertel 1351: </script>
                   1352: ENDOUTPUT
                   1353:     return $output;
                   1354: }
                   1355: 
                   1356: # now just updates the help link and generates a blue icon
1.193     raeburn  1357: sub help_open_menu {
1.430     albertel 1358:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1359: 	= @_;    
1.949     droeschl 1360:     $stayOnPage = 1;
1.430     albertel 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) = @_;
1.436     albertel 1380:     $text = &mt($text);
1.949     droeschl 1381:     my $stay_on_page = 1;
                   1382: 
1.1168    raeburn  1383:     my ($link,$banner_link);
                   1384:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1385:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1386: 	                         : "javascript:helpMenu('open')";
                   1387:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1388:     }
1.201     raeburn  1389:     my $title = &mt('Get help');
1.1168    raeburn  1390:     if ($link) {
                   1391:         return <<"END";
1.436     albertel 1392: $banner_link
1.1159    raeburn  1393: <a href="$link" title="$title">$text</a>
1.436     albertel 1394: END
1.1168    raeburn  1395:     } else {
                   1396:         return '&nbsp;'.$text.'&nbsp;';
                   1397:     }
1.436     albertel 1398: }
                   1399: 
                   1400: sub help_menu_js {
1.1154    raeburn  1401:     my ($httphost) = @_;
1.949     droeschl 1402:     my $stayOnPage = 1;
1.436     albertel 1403:     my $width = 620;
                   1404:     my $height = 600;
1.430     albertel 1405:     my $helptopic=&general_help();
1.1154    raeburn  1406:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1407:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1408:     my $start_page =
                   1409:         &Apache::loncommon::start_page('Help Menu', undef,
                   1410: 				       {'frameset'    => 1,
                   1411: 					'js_ready'    => 1,
1.1154    raeburn  1412:                                         'use_absolute' => $httphost,
1.331     albertel 1413: 					'add_entries' => {
1.1168    raeburn  1414: 					    'border' => '0', 
1.579     raeburn  1415: 					    'rows'   => "110,*",},});
1.331     albertel 1416:     my $end_page =
                   1417:         &Apache::loncommon::end_page({'frameset' => 1,
                   1418: 				      'js_ready' => 1,});
                   1419: 
1.436     albertel 1420:     my $template .= <<"ENDTEMPLATE";
                   1421: <script type="text/javascript">
1.877     bisitz   1422: // <![CDATA[
1.253     albertel 1423: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1424: var banner_link = '';
1.243     raeburn  1425: function helpMenu(target) {
                   1426:     var caller = this;
                   1427:     if (target == 'open') {
                   1428:         var newWindow = null;
                   1429:         try {
1.262     albertel 1430:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1431:         }
                   1432:         catch(error) {
                   1433:             writeHelp(caller);
                   1434:             return;
                   1435:         }
                   1436:         if (newWindow) {
                   1437:             caller = newWindow;
                   1438:         }
1.193     raeburn  1439:     }
1.243     raeburn  1440:     writeHelp(caller);
                   1441:     return;
                   1442: }
                   1443: function writeHelp(caller) {
1.1168    raeburn  1444:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1445:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1446:     caller.document.close();
                   1447:     caller.focus();
1.193     raeburn  1448: }
1.877     bisitz   1449: // END LON-CAPA Internal -->
1.253     albertel 1450: // ]]>
1.436     albertel 1451: </script>
1.193     raeburn  1452: ENDTEMPLATE
                   1453:     return $template;
                   1454: }
                   1455: 
1.172     www      1456: sub help_open_bug {
                   1457:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1458:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1459:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1460:     $text = "" if (not defined $text);
                   1461: 	$stayOnPage=1;
1.184     albertel 1462:     $width = 600 if (not defined $width);
                   1463:     $height = 600 if (not defined $height);
1.172     www      1464: 
                   1465:     $topic=~s/\W+/\+/g;
                   1466:     my $link='';
                   1467:     my $template='';
1.379     albertel 1468:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1469: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1470:     if (!$stayOnPage)
                   1471:     {
                   1472: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1473:     }
                   1474:     else
                   1475:     {
                   1476: 	$link = $url;
                   1477:     }
                   1478:     # Add the text
                   1479:     if ($text ne "")
                   1480:     {
                   1481: 	$template .= 
                   1482:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1483:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1484:     }
                   1485: 
                   1486:     # Add the graphic
1.179     matthew  1487:     my $title = &mt('Report a Bug');
1.215     albertel 1488:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1489:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1490:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1491: ENDTEMPLATE
                   1492:     if ($text ne '') { $template.='</td></tr></table>' };
                   1493:     return $template;
                   1494: 
                   1495: }
                   1496: 
                   1497: sub help_open_faq {
                   1498:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1499:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1500:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1501:     $text = "" if (not defined $text);
                   1502: 	$stayOnPage=1;
                   1503:     $width = 350 if (not defined $width);
                   1504:     $height = 400 if (not defined $height);
                   1505: 
                   1506:     $topic=~s/\W+/\+/g;
                   1507:     my $link='';
                   1508:     my $template='';
                   1509:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1510:     if (!$stayOnPage)
                   1511:     {
                   1512: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1513:     }
                   1514:     else
                   1515:     {
                   1516: 	$link = $url;
                   1517:     }
                   1518: 
                   1519:     # Add the text
                   1520:     if ($text ne "")
                   1521:     {
                   1522: 	$template .= 
1.173     www      1523:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1524:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1525:     }
                   1526: 
                   1527:     # Add the graphic
1.179     matthew  1528:     my $title = &mt('View the FAQ');
1.215     albertel 1529:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1530:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1531:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1532: ENDTEMPLATE
                   1533:     if ($text ne '') { $template.='</td></tr></table>' };
                   1534:     return $template;
                   1535: 
1.44      bowersj2 1536: }
1.37      matthew  1537: 
1.180     matthew  1538: ###############################################################
                   1539: ###############################################################
                   1540: 
1.45      matthew  1541: =pod
                   1542: 
1.648     raeburn  1543: =item * &change_content_javascript():
1.256     matthew  1544: 
                   1545: This and the next function allow you to create small sections of an
                   1546: otherwise static HTML page that you can update on the fly with
                   1547: Javascript, even in Netscape 4.
                   1548: 
                   1549: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1550: must be written to the HTML page once. It will prove the Javascript
                   1551: function "change(name, content)". Calling the change function with the
                   1552: name of the section 
                   1553: you want to update, matching the name passed to C<changable_area>, and
                   1554: the new content you want to put in there, will put the content into
                   1555: that area.
                   1556: 
                   1557: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1558: to contain room for the original contents. You need to "make space"
                   1559: for whatever changes you wish to make, and be B<sure> to check your
                   1560: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1561: it's adequate for updating a one-line status display, but little more.
                   1562: This script will set the space to 100% width, so you only need to
                   1563: worry about height in Netscape 4.
                   1564: 
                   1565: Modern browsers are much less limiting, and if you can commit to the
                   1566: user not using Netscape 4, this feature may be used freely with
                   1567: pretty much any HTML.
                   1568: 
                   1569: =cut
                   1570: 
                   1571: sub change_content_javascript {
                   1572:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1573:     if ($env{'browser.type'} eq 'netscape' &&
                   1574: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1575: 	return (<<NETSCAPE4);
                   1576: 	function change(name, content) {
                   1577: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1578: 	    doc.open();
                   1579: 	    doc.write(content);
                   1580: 	    doc.close();
                   1581: 	}
                   1582: NETSCAPE4
                   1583:     } else {
                   1584: 	# Otherwise, we need to use semi-standards-compliant code
                   1585: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1586: 	# is really scary, and every useful browser supports it
                   1587: 	return (<<DOMBASED);
                   1588: 	function change(name, content) {
                   1589: 	    element = document.getElementById(name);
                   1590: 	    element.innerHTML = content;
                   1591: 	}
                   1592: DOMBASED
                   1593:     }
                   1594: }
                   1595: 
                   1596: =pod
                   1597: 
1.648     raeburn  1598: =item * &changable_area($name,$origContent):
1.256     matthew  1599: 
                   1600: This provides a "changable area" that can be modified on the fly via
                   1601: the Javascript code provided in C<change_content_javascript>. $name is
                   1602: the name you will use to reference the area later; do not repeat the
                   1603: same name on a given HTML page more then once. $origContent is what
                   1604: the area will originally contain, which can be left blank.
                   1605: 
                   1606: =cut
                   1607: 
                   1608: sub changable_area {
                   1609:     my ($name, $origContent) = @_;
                   1610: 
1.258     albertel 1611:     if ($env{'browser.type'} eq 'netscape' &&
                   1612: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1613: 	# If this is netscape 4, we need to use the Layer tag
                   1614: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1615:     } else {
                   1616: 	return "<span id='$name'>$origContent</span>";
                   1617:     }
                   1618: }
                   1619: 
                   1620: =pod
                   1621: 
1.648     raeburn  1622: =item * &viewport_geometry_js 
1.590     raeburn  1623: 
                   1624: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1625: 
                   1626: =cut
                   1627: 
                   1628: 
                   1629: sub viewport_geometry_js { 
                   1630:     return <<"GEOMETRY";
                   1631: var Geometry = {};
                   1632: function init_geometry() {
                   1633:     if (Geometry.init) { return };
                   1634:     Geometry.init=1;
                   1635:     if (window.innerHeight) {
                   1636:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1637:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1638:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1639:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1640:     }
                   1641:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1642:         Geometry.getViewportHeight =
                   1643:             function() { return document.documentElement.clientHeight; };
                   1644:         Geometry.getViewportWidth =
                   1645:             function() { return document.documentElement.clientWidth; };
                   1646: 
                   1647:         Geometry.getHorizontalScroll =
                   1648:             function() { return document.documentElement.scrollLeft; };
                   1649:         Geometry.getVerticalScroll =
                   1650:             function() { return document.documentElement.scrollTop; };
                   1651:     }
                   1652:     else if (document.body.clientHeight) {
                   1653:         Geometry.getViewportHeight =
                   1654:             function() { return document.body.clientHeight; };
                   1655:         Geometry.getViewportWidth =
                   1656:             function() { return document.body.clientWidth; };
                   1657:         Geometry.getHorizontalScroll =
                   1658:             function() { return document.body.scrollLeft; };
                   1659:         Geometry.getVerticalScroll =
                   1660:             function() { return document.body.scrollTop; };
                   1661:     }
                   1662: }
                   1663: 
                   1664: GEOMETRY
                   1665: }
                   1666: 
                   1667: =pod
                   1668: 
1.648     raeburn  1669: =item * &viewport_size_js()
1.590     raeburn  1670: 
                   1671: 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. 
                   1672: 
                   1673: =cut
                   1674: 
                   1675: sub viewport_size_js {
                   1676:     my $geometry = &viewport_geometry_js();
                   1677:     return <<"DIMS";
                   1678: 
                   1679: $geometry
                   1680: 
                   1681: function getViewportDims(width,height) {
                   1682:     init_geometry();
                   1683:     width.value = Geometry.getViewportWidth();
                   1684:     height.value = Geometry.getViewportHeight();
                   1685:     return;
                   1686: }
                   1687: 
                   1688: DIMS
                   1689: }
                   1690: 
                   1691: =pod
                   1692: 
1.648     raeburn  1693: =item * &resize_textarea_js()
1.565     albertel 1694: 
                   1695: emits the needed javascript to resize a textarea to be as big as possible
                   1696: 
                   1697: creates a function resize_textrea that takes two IDs first should be
                   1698: the id of the element to resize, second should be the id of a div that
                   1699: surrounds everything that comes after the textarea, this routine needs
                   1700: to be attached to the <body> for the onload and onresize events.
                   1701: 
1.648     raeburn  1702: =back
1.565     albertel 1703: 
                   1704: =cut
                   1705: 
                   1706: sub resize_textarea_js {
1.590     raeburn  1707:     my $geometry = &viewport_geometry_js();
1.565     albertel 1708:     return <<"RESIZE";
                   1709:     <script type="text/javascript">
1.824     bisitz   1710: // <![CDATA[
1.590     raeburn  1711: $geometry
1.565     albertel 1712: 
1.588     albertel 1713: function getX(element) {
                   1714:     var x = 0;
                   1715:     while (element) {
                   1716: 	x += element.offsetLeft;
                   1717: 	element = element.offsetParent;
                   1718:     }
                   1719:     return x;
                   1720: }
                   1721: function getY(element) {
                   1722:     var y = 0;
                   1723:     while (element) {
                   1724: 	y += element.offsetTop;
                   1725: 	element = element.offsetParent;
                   1726:     }
                   1727:     return y;
                   1728: }
                   1729: 
                   1730: 
1.565     albertel 1731: function resize_textarea(textarea_id,bottom_id) {
                   1732:     init_geometry();
                   1733:     var textarea        = document.getElementById(textarea_id);
                   1734:     //alert(textarea);
                   1735: 
1.588     albertel 1736:     var textarea_top    = getY(textarea);
1.565     albertel 1737:     var textarea_height = textarea.offsetHeight;
                   1738:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1739:     var bottom_top      = getY(bottom);
1.565     albertel 1740:     var bottom_height   = bottom.offsetHeight;
                   1741:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1742:     var fudge           = 23;
1.565     albertel 1743:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1744:     if (new_height < 300) {
                   1745: 	new_height = 300;
                   1746:     }
                   1747:     textarea.style.height=new_height+'px';
                   1748: }
1.824     bisitz   1749: // ]]>
1.565     albertel 1750: </script>
                   1751: RESIZE
                   1752: 
                   1753: }
                   1754: 
                   1755: =pod
                   1756: 
1.256     matthew  1757: =head1 Excel and CSV file utility routines
                   1758: 
                   1759: =cut
                   1760: 
                   1761: ###############################################################
                   1762: ###############################################################
                   1763: 
                   1764: =pod
                   1765: 
1.1162    raeburn  1766: =over 4
                   1767: 
1.648     raeburn  1768: =item * &csv_translate($text) 
1.37      matthew  1769: 
1.185     www      1770: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1771: format.
                   1772: 
                   1773: =cut
                   1774: 
1.180     matthew  1775: ###############################################################
                   1776: ###############################################################
1.37      matthew  1777: sub csv_translate {
                   1778:     my $text = shift;
                   1779:     $text =~ s/\"/\"\"/g;
1.209     albertel 1780:     $text =~ s/\n/ /g;
1.37      matthew  1781:     return $text;
                   1782: }
1.180     matthew  1783: 
                   1784: ###############################################################
                   1785: ###############################################################
                   1786: 
                   1787: =pod
                   1788: 
1.648     raeburn  1789: =item * &define_excel_formats()
1.180     matthew  1790: 
                   1791: Define some commonly used Excel cell formats.
                   1792: 
                   1793: Currently supported formats:
                   1794: 
                   1795: =over 4
                   1796: 
                   1797: =item header
                   1798: 
                   1799: =item bold
                   1800: 
                   1801: =item h1
                   1802: 
                   1803: =item h2
                   1804: 
                   1805: =item h3
                   1806: 
1.256     matthew  1807: =item h4
                   1808: 
                   1809: =item i
                   1810: 
1.180     matthew  1811: =item date
                   1812: 
                   1813: =back
                   1814: 
                   1815: Inputs: $workbook
                   1816: 
                   1817: Returns: $format, a hash reference.
                   1818: 
1.1057    foxr     1819: 
1.180     matthew  1820: =cut
                   1821: 
                   1822: ###############################################################
                   1823: ###############################################################
                   1824: sub define_excel_formats {
                   1825:     my ($workbook) = @_;
                   1826:     my $format;
                   1827:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1828:                                                 bottom    => 1,
                   1829:                                                 align     => 'center');
                   1830:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1831:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1832:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1833:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1834:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1835:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1836:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1837:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1838:     return $format;
                   1839: }
                   1840: 
                   1841: ###############################################################
                   1842: ###############################################################
1.113     bowersj2 1843: 
                   1844: =pod
                   1845: 
1.648     raeburn  1846: =item * &create_workbook()
1.255     matthew  1847: 
                   1848: Create an Excel worksheet.  If it fails, output message on the
                   1849: request object and return undefs.
                   1850: 
                   1851: Inputs: Apache request object
                   1852: 
                   1853: Returns (undef) on failure, 
                   1854:     Excel worksheet object, scalar with filename, and formats 
                   1855:     from &Apache::loncommon::define_excel_formats on success
                   1856: 
                   1857: =cut
                   1858: 
                   1859: ###############################################################
                   1860: ###############################################################
                   1861: sub create_workbook {
                   1862:     my ($r) = @_;
                   1863:         #
                   1864:     # Create the excel spreadsheet
                   1865:     my $filename = '/prtspool/'.
1.258     albertel 1866:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1867:         time.'_'.rand(1000000000).'.xls';
                   1868:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1869:     if (! defined($workbook)) {
                   1870:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1871:         $r->print(
                   1872:             '<p class="LC_error">'
                   1873:            .&mt('Problems occurred in creating the new Excel file.')
                   1874:            .' '.&mt('This error has been logged.')
                   1875:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1876:            .'</p>'
                   1877:         );
1.255     matthew  1878:         return (undef);
                   1879:     }
                   1880:     #
1.1014    foxr     1881:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1882:     #
                   1883:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1884:     return ($workbook,$filename,$format);
                   1885: }
                   1886: 
                   1887: ###############################################################
                   1888: ###############################################################
                   1889: 
                   1890: =pod
                   1891: 
1.648     raeburn  1892: =item * &create_text_file()
1.113     bowersj2 1893: 
1.542     raeburn  1894: Create a file to write to and eventually make available to the user.
1.256     matthew  1895: If file creation fails, outputs an error message on the request object and 
                   1896: return undefs.
1.113     bowersj2 1897: 
1.256     matthew  1898: Inputs: Apache request object, and file suffix
1.113     bowersj2 1899: 
1.256     matthew  1900: Returns (undef) on failure, 
                   1901:     Filehandle and filename on success.
1.113     bowersj2 1902: 
                   1903: =cut
                   1904: 
1.256     matthew  1905: ###############################################################
                   1906: ###############################################################
                   1907: sub create_text_file {
                   1908:     my ($r,$suffix) = @_;
                   1909:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1910:     my $fh;
                   1911:     my $filename = '/prtspool/'.
1.258     albertel 1912:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1913:         time.'_'.rand(1000000000).'.'.$suffix;
                   1914:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1915:     if (! defined($fh)) {
                   1916:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1917:         $r->print(
                   1918:             '<p class="LC_error">'
                   1919:            .&mt('Problems occurred in creating the output file.')
                   1920:            .' '.&mt('This error has been logged.')
                   1921:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1922:            .'</p>'
                   1923:         );
1.113     bowersj2 1924:     }
1.256     matthew  1925:     return ($fh,$filename)
1.113     bowersj2 1926: }
                   1927: 
                   1928: 
1.256     matthew  1929: =pod 
1.113     bowersj2 1930: 
                   1931: =back
                   1932: 
                   1933: =cut
1.37      matthew  1934: 
                   1935: ###############################################################
1.33      matthew  1936: ##        Home server <option> list generating code          ##
                   1937: ###############################################################
1.35      matthew  1938: 
1.169     www      1939: # ------------------------------------------
                   1940: 
                   1941: sub domain_select {
                   1942:     my ($name,$value,$multiple)=@_;
                   1943:     my %domains=map { 
1.514     albertel 1944: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1945:     } &Apache::lonnet::all_domains();
1.169     www      1946:     if ($multiple) {
                   1947: 	$domains{''}=&mt('Any domain');
1.550     albertel 1948: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1949: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1950:     } else {
1.550     albertel 1951: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1952: 	return &select_form($name,$value,\%domains);
1.169     www      1953:     }
                   1954: }
                   1955: 
1.282     albertel 1956: #-------------------------------------------
                   1957: 
                   1958: =pod
                   1959: 
1.519     raeburn  1960: =head1 Routines for form select boxes
                   1961: 
                   1962: =over 4
                   1963: 
1.648     raeburn  1964: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1965: 
                   1966: Returns a string containing a <select> element int multiple mode
                   1967: 
                   1968: 
                   1969: Args:
                   1970:   $name - name of the <select> element
1.506     raeburn  1971:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1972:   $size - number of rows long the select element is
1.283     albertel 1973:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1974:           (shown text should already have been &mt())
1.506     raeburn  1975:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1976: 
1.282     albertel 1977: =cut
                   1978: 
                   1979: #-------------------------------------------
1.169     www      1980: sub multiple_select_form {
1.284     albertel 1981:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1982:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1983:     my $output='';
1.191     matthew  1984:     if (! defined($size)) {
                   1985:         $size = 4;
1.283     albertel 1986:         if (scalar(keys(%$hash))<4) {
                   1987:             $size = scalar(keys(%$hash));
1.191     matthew  1988:         }
                   1989:     }
1.734     bisitz   1990:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1991:     my @order;
1.506     raeburn  1992:     if (ref($order) eq 'ARRAY')  {
                   1993:         @order = @{$order};
                   1994:     } else {
                   1995:         @order = sort(keys(%$hash));
1.501     banghart 1996:     }
                   1997:     if (exists($$hash{'select_form_order'})) {
                   1998:         @order = @{$$hash{'select_form_order'}};
                   1999:     }
                   2000:         
1.284     albertel 2001:     foreach my $key (@order) {
1.356     albertel 2002:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2003:         $output.='selected="selected" ' if ($selected{$key});
                   2004:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2005:     }
                   2006:     $output.="</select>\n";
                   2007:     return $output;
                   2008: }
                   2009: 
1.88      www      2010: #-------------------------------------------
                   2011: 
                   2012: =pod
                   2013: 
1.970     raeburn  2014: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2015: 
                   2016: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2017: allow a user to select options from a ref to a hash containing:
                   2018: option_name => displayed text. An optional $onchange can include
                   2019: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2020: 
1.88      www      2021: See lonrights.pm for an example invocation and use.
                   2022: 
                   2023: =cut
                   2024: 
                   2025: #-------------------------------------------
                   2026: sub select_form {
1.970     raeburn  2027:     my ($def,$name,$hashref,$onchange) = @_;
                   2028:     return unless (ref($hashref) eq 'HASH');
                   2029:     if ($onchange) {
                   2030:         $onchange = ' onchange="'.$onchange.'"';
                   2031:     }
                   2032:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2033:     my @keys;
1.970     raeburn  2034:     if (exists($hashref->{'select_form_order'})) {
                   2035: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2036:     } else {
1.970     raeburn  2037: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2038:     }
1.356     albertel 2039:     foreach my $key (@keys) {
                   2040:         $selectform.=
                   2041: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2042:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2043:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2044:     }
                   2045:     $selectform.="</select>";
                   2046:     return $selectform;
                   2047: }
                   2048: 
1.475     www      2049: # For display filters
                   2050: 
                   2051: sub display_filter {
1.1074    raeburn  2052:     my ($context) = @_;
1.475     www      2053:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2054:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2055:     my $phraseinput = 'hidden';
                   2056:     my $includeinput = 'hidden';
                   2057:     my ($checked,$includetypestext);
                   2058:     if ($env{'form.displayfilter'} eq 'containing') {
                   2059:         $phraseinput = 'text'; 
                   2060:         if ($context eq 'parmslog') {
                   2061:             $includeinput = 'checkbox';
                   2062:             if ($env{'form.includetypes'}) {
                   2063:                 $checked = ' checked="checked"';
                   2064:             }
                   2065:             $includetypestext = &mt('Include parameter types');
                   2066:         }
                   2067:     } else {
                   2068:         $includetypestext = '&nbsp;';
                   2069:     }
                   2070:     my ($additional,$secondid,$thirdid);
                   2071:     if ($context eq 'parmslog') {
                   2072:         $additional = 
                   2073:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2074:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2075:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2076:             '</label>';
                   2077:         $secondid = 'includetypes';
                   2078:         $thirdid = 'includetypestext';
                   2079:     }
                   2080:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2081:                                                     '$secondid','$thirdid')";
                   2082:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2083: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2084: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2085: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2086:            &mt('Filter: [_1]',
1.477     www      2087: 	   &select_form($env{'form.displayfilter'},
                   2088: 			'displayfilter',
1.970     raeburn  2089: 			{'currentfolder' => 'Current folder/page',
1.477     www      2090: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2091: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2092: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2093:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2094:                          '" />'.$additional;
                   2095: }
                   2096: 
                   2097: sub display_filter_js {
                   2098:     my $includetext = &mt('Include parameter types');
                   2099:     return <<"ENDJS";
                   2100:   
                   2101: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2102:     var firstType = 'hidden';
                   2103:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2104:         firstType = 'text';
                   2105:     }
                   2106:     firstObject = document.getElementById(firstid);
                   2107:     if (typeof(firstObject) == 'object') {
                   2108:         if (firstObject.type != firstType) {
                   2109:             changeInputType(firstObject,firstType);
                   2110:         }
                   2111:     }
                   2112:     if (context == 'parmslog') {
                   2113:         var secondType = 'hidden';
                   2114:         if (firstType == 'text') {
                   2115:             secondType = 'checkbox';
                   2116:         }
                   2117:         secondObject = document.getElementById(secondid);  
                   2118:         if (typeof(secondObject) == 'object') {
                   2119:             if (secondObject.type != secondType) {
                   2120:                 changeInputType(secondObject,secondType);
                   2121:             }
                   2122:         }
                   2123:         var textItem = document.getElementById(thirdid);
                   2124:         var currtext = textItem.innerHTML;
                   2125:         var newtext;
                   2126:         if (firstType == 'text') {
                   2127:             newtext = '$includetext';
                   2128:         } else {
                   2129:             newtext = '&nbsp;';
                   2130:         }
                   2131:         if (currtext != newtext) {
                   2132:             textItem.innerHTML = newtext;
                   2133:         }
                   2134:     }
                   2135:     return;
                   2136: }
                   2137: 
                   2138: function changeInputType(oldObject,newType) {
                   2139:     var newObject = document.createElement('input');
                   2140:     newObject.type = newType;
                   2141:     if (oldObject.size) {
                   2142:         newObject.size = oldObject.size;
                   2143:     }
                   2144:     if (oldObject.value) {
                   2145:         newObject.value = oldObject.value;
                   2146:     }
                   2147:     if (oldObject.name) {
                   2148:         newObject.name = oldObject.name;
                   2149:     }
                   2150:     if (oldObject.id) {
                   2151:         newObject.id = oldObject.id;
                   2152:     }
                   2153:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2154:     return;
                   2155: }
                   2156: 
                   2157: ENDJS
1.475     www      2158: }
                   2159: 
1.167     www      2160: sub gradeleveldescription {
                   2161:     my $gradelevel=shift;
                   2162:     my %gradelevels=(0 => 'Not specified',
                   2163: 		     1 => 'Grade 1',
                   2164: 		     2 => 'Grade 2',
                   2165: 		     3 => 'Grade 3',
                   2166: 		     4 => 'Grade 4',
                   2167: 		     5 => 'Grade 5',
                   2168: 		     6 => 'Grade 6',
                   2169: 		     7 => 'Grade 7',
                   2170: 		     8 => 'Grade 8',
                   2171: 		     9 => 'Grade 9',
                   2172: 		     10 => 'Grade 10',
                   2173: 		     11 => 'Grade 11',
                   2174: 		     12 => 'Grade 12',
                   2175: 		     13 => 'Grade 13',
                   2176: 		     14 => '100 Level',
                   2177: 		     15 => '200 Level',
                   2178: 		     16 => '300 Level',
                   2179: 		     17 => '400 Level',
                   2180: 		     18 => 'Graduate Level');
                   2181:     return &mt($gradelevels{$gradelevel});
                   2182: }
                   2183: 
1.163     www      2184: sub select_level_form {
                   2185:     my ($deflevel,$name)=@_;
                   2186:     unless ($deflevel) { $deflevel=0; }
1.167     www      2187:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2188:     for (my $i=0; $i<=18; $i++) {
                   2189:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2190:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2191:                 ">".&gradeleveldescription($i)."</option>\n";
                   2192:     }
                   2193:     $selectform.="</select>";
                   2194:     return $selectform;
1.163     www      2195: }
1.167     www      2196: 
1.35      matthew  2197: #-------------------------------------------
                   2198: 
1.45      matthew  2199: =pod
                   2200: 
1.1121    raeburn  2201: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2202: 
                   2203: Returns a string containing a <select name='$name' size='1'> form to 
                   2204: allow a user to select the domain to preform an operation in.  
                   2205: See loncreateuser.pm for an example invocation and use.
                   2206: 
1.90      www      2207: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2208: selected");
                   2209: 
1.743     raeburn  2210: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2211: 
1.910     raeburn  2212: 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.
                   2213: 
1.1121    raeburn  2214: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2215: 
                   2216: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2217: 
1.35      matthew  2218: =cut
                   2219: 
                   2220: #-------------------------------------------
1.34      matthew  2221: sub select_dom_form {
1.1121    raeburn  2222:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2223:     if ($onchange) {
1.874     raeburn  2224:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2225:     }
1.1121    raeburn  2226:     my (@domains,%exclude);
1.910     raeburn  2227:     if (ref($incdoms) eq 'ARRAY') {
                   2228:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2229:     } else {
                   2230:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2231:     }
1.90      www      2232:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2233:     if (ref($excdoms) eq 'ARRAY') {
                   2234:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2235:     }
1.743     raeburn  2236:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2237:     foreach my $dom (@domains) {
1.1121    raeburn  2238:         next if ($exclude{$dom});
1.356     albertel 2239:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2240:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2241:         if ($showdomdesc) {
                   2242:             if ($dom ne '') {
                   2243:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2244:                 if ($domdesc ne '') {
                   2245:                     $selectdomain .= ' ('.$domdesc.')';
                   2246:                 }
                   2247:             } 
                   2248:         }
                   2249:         $selectdomain .= "</option>\n";
1.34      matthew  2250:     }
                   2251:     $selectdomain.="</select>";
                   2252:     return $selectdomain;
                   2253: }
                   2254: 
1.35      matthew  2255: #-------------------------------------------
                   2256: 
1.45      matthew  2257: =pod
                   2258: 
1.648     raeburn  2259: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2260: 
1.586     raeburn  2261: input: 4 arguments (two required, two optional) - 
                   2262:     $domain - domain of new user
                   2263:     $name - name of form element
                   2264:     $default - Value of 'default' causes a default item to be first 
                   2265:                             option, and selected by default. 
                   2266:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2267:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2268: output: returns 2 items: 
1.586     raeburn  2269: (a) form element which contains either:
                   2270:    (i) <select name="$name">
                   2271:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2272:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2273:        </select>
                   2274:        form item if there are multiple library servers in $domain, or
                   2275:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2276:        if there is only one library server in $domain.
                   2277: 
                   2278: (b) number of library servers found.
                   2279: 
                   2280: See loncreateuser.pm for example of use.
1.35      matthew  2281: 
                   2282: =cut
                   2283: 
                   2284: #-------------------------------------------
1.586     raeburn  2285: sub home_server_form_item {
                   2286:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2287:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2288:     my $result;
                   2289:     my $numlib = keys(%servers);
                   2290:     if ($numlib > 1) {
                   2291:         $result .= '<select name="'.$name.'" />'."\n";
                   2292:         if ($default) {
1.804     bisitz   2293:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2294:                        '</option>'."\n";
                   2295:         }
                   2296:         foreach my $hostid (sort(keys(%servers))) {
                   2297:             $result.= '<option value="'.$hostid.'">'.
                   2298: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2299:         }
                   2300:         $result .= '</select>'."\n";
                   2301:     } elsif ($numlib == 1) {
                   2302:         my $hostid;
                   2303:         foreach my $item (keys(%servers)) {
                   2304:             $hostid = $item;
                   2305:         }
                   2306:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2307:                    $hostid.'" />';
                   2308:                    if (!$hide) {
                   2309:                        $result .= $hostid.' '.$servers{$hostid};
                   2310:                    }
                   2311:                    $result .= "\n";
                   2312:     } elsif ($default) {
                   2313:         $result .= '<input type="hidden" name="'.$name.
                   2314:                    '" value="default" />';
                   2315:                    if (!$hide) {
                   2316:                        $result .= &mt('default');
                   2317:                    }
                   2318:                    $result .= "\n";
1.33      matthew  2319:     }
1.586     raeburn  2320:     return ($result,$numlib);
1.33      matthew  2321: }
1.112     bowersj2 2322: 
                   2323: =pod
                   2324: 
1.534     albertel 2325: =back 
                   2326: 
1.112     bowersj2 2327: =cut
1.87      matthew  2328: 
                   2329: ###############################################################
1.112     bowersj2 2330: ##                  Decoding User Agent                      ##
1.87      matthew  2331: ###############################################################
                   2332: 
                   2333: =pod
                   2334: 
1.112     bowersj2 2335: =head1 Decoding the User Agent
                   2336: 
                   2337: =over 4
                   2338: 
                   2339: =item * &decode_user_agent()
1.87      matthew  2340: 
                   2341: Inputs: $r
                   2342: 
                   2343: Outputs:
                   2344: 
                   2345: =over 4
                   2346: 
1.112     bowersj2 2347: =item * $httpbrowser
1.87      matthew  2348: 
1.112     bowersj2 2349: =item * $clientbrowser
1.87      matthew  2350: 
1.112     bowersj2 2351: =item * $clientversion
1.87      matthew  2352: 
1.112     bowersj2 2353: =item * $clientmathml
1.87      matthew  2354: 
1.112     bowersj2 2355: =item * $clientunicode
1.87      matthew  2356: 
1.112     bowersj2 2357: =item * $clientos
1.87      matthew  2358: 
1.1137    raeburn  2359: =item * $clientmobile
                   2360: 
1.1141    raeburn  2361: =item * $clientinfo
                   2362: 
1.87      matthew  2363: =back
                   2364: 
1.157     matthew  2365: =back 
                   2366: 
1.87      matthew  2367: =cut
                   2368: 
                   2369: ###############################################################
                   2370: ###############################################################
                   2371: sub decode_user_agent {
1.247     albertel 2372:     my ($r)=@_;
1.87      matthew  2373:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2374:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2375:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2376:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2377:     my $clientbrowser='unknown';
                   2378:     my $clientversion='0';
                   2379:     my $clientmathml='';
                   2380:     my $clientunicode='0';
1.1137    raeburn  2381:     my $clientmobile=0;
1.87      matthew  2382:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2383:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2384: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2385: 	    $clientbrowser=$bname;
                   2386:             $httpbrowser=~/$vreg/i;
                   2387: 	    $clientversion=$1;
                   2388:             $clientmathml=($clientversion>=$minv);
                   2389:             $clientunicode=($clientversion>=$univ);
                   2390: 	}
                   2391:     }
                   2392:     my $clientos='unknown';
1.1141    raeburn  2393:     my $clientinfo;
1.87      matthew  2394:     if (($httpbrowser=~/linux/i) ||
                   2395:         ($httpbrowser=~/unix/i) ||
                   2396:         ($httpbrowser=~/ux/i) ||
                   2397:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2398:     if (($httpbrowser=~/vax/i) ||
                   2399:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2400:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2401:     if (($httpbrowser=~/mac/i) ||
                   2402:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2403:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2404:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2405:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2406:         $clientmobile=lc($1);
                   2407:     }
1.1141    raeburn  2408:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2409:         $clientinfo = 'firefox-'.$1;
                   2410:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2411:         $clientinfo = 'chromeframe-'.$1;
                   2412:     }
1.87      matthew  2413:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1141    raeburn  2414:             $clientunicode,$clientos,$clientmobile,$clientinfo);
1.87      matthew  2415: }
                   2416: 
1.32      matthew  2417: ###############################################################
                   2418: ##    Authentication changing form generation subroutines    ##
                   2419: ###############################################################
                   2420: ##
                   2421: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2422: ## hash, and have reasonable default values.
                   2423: ##
                   2424: ##    formname = the name given in the <form> tag.
1.35      matthew  2425: #-------------------------------------------
                   2426: 
1.45      matthew  2427: =pod
                   2428: 
1.112     bowersj2 2429: =head1 Authentication Routines
                   2430: 
                   2431: =over 4
                   2432: 
1.648     raeburn  2433: =item * &authform_xxxxxx()
1.35      matthew  2434: 
                   2435: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2436: handle some of the conveniences required for authentication forms.  
                   2437: This is not an optimal method, but it works.  
                   2438: 
                   2439: =over 4
                   2440: 
1.112     bowersj2 2441: =item * authform_header
1.35      matthew  2442: 
1.112     bowersj2 2443: =item * authform_authorwarning
1.35      matthew  2444: 
1.112     bowersj2 2445: =item * authform_nochange
1.35      matthew  2446: 
1.112     bowersj2 2447: =item * authform_kerberos
1.35      matthew  2448: 
1.112     bowersj2 2449: =item * authform_internal
1.35      matthew  2450: 
1.112     bowersj2 2451: =item * authform_filesystem
1.35      matthew  2452: 
                   2453: =back
                   2454: 
1.648     raeburn  2455: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2456: 
1.35      matthew  2457: =cut
                   2458: 
                   2459: #-------------------------------------------
1.32      matthew  2460: sub authform_header{  
                   2461:     my %in = (
                   2462:         formname => 'cu',
1.80      albertel 2463:         kerb_def_dom => '',
1.32      matthew  2464:         @_,
                   2465:     );
                   2466:     $in{'formname'} = 'document.' . $in{'formname'};
                   2467:     my $result='';
1.80      albertel 2468: 
                   2469: #---------------------------------------------- Code for upper case translation
                   2470:     my $Javascript_toUpperCase;
                   2471:     unless ($in{kerb_def_dom}) {
                   2472:         $Javascript_toUpperCase =<<"END";
                   2473:         switch (choice) {
                   2474:            case 'krb': currentform.elements[choicearg].value =
                   2475:                currentform.elements[choicearg].value.toUpperCase();
                   2476:                break;
                   2477:            default:
                   2478:         }
                   2479: END
                   2480:     } else {
                   2481:         $Javascript_toUpperCase = "";
                   2482:     }
                   2483: 
1.165     raeburn  2484:     my $radioval = "'nochange'";
1.591     raeburn  2485:     if (defined($in{'curr_authtype'})) {
                   2486:         if ($in{'curr_authtype'} ne '') {
                   2487:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2488:         }
1.174     matthew  2489:     }
1.165     raeburn  2490:     my $argfield = 'null';
1.591     raeburn  2491:     if (defined($in{'mode'})) {
1.165     raeburn  2492:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2493:             if (defined($in{'curr_autharg'})) {
                   2494:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2495:                     $argfield = "'$in{'curr_autharg'}'";
                   2496:                 }
                   2497:             }
                   2498:         }
                   2499:     }
                   2500: 
1.32      matthew  2501:     $result.=<<"END";
                   2502: var current = new Object();
1.165     raeburn  2503: current.radiovalue = $radioval;
                   2504: current.argfield = $argfield;
1.32      matthew  2505: 
                   2506: function changed_radio(choice,currentform) {
                   2507:     var choicearg = choice + 'arg';
                   2508:     // If a radio button in changed, we need to change the argfield
                   2509:     if (current.radiovalue != choice) {
                   2510:         current.radiovalue = choice;
                   2511:         if (current.argfield != null) {
                   2512:             currentform.elements[current.argfield].value = '';
                   2513:         }
                   2514:         if (choice == 'nochange') {
                   2515:             current.argfield = null;
                   2516:         } else {
                   2517:             current.argfield = choicearg;
                   2518:             switch(choice) {
                   2519:                 case 'krb': 
                   2520:                     currentform.elements[current.argfield].value = 
                   2521:                         "$in{'kerb_def_dom'}";
                   2522:                 break;
                   2523:               default:
                   2524:                 break;
                   2525:             }
                   2526:         }
                   2527:     }
                   2528:     return;
                   2529: }
1.22      www      2530: 
1.32      matthew  2531: function changed_text(choice,currentform) {
                   2532:     var choicearg = choice + 'arg';
                   2533:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2534:         $Javascript_toUpperCase
1.32      matthew  2535:         // clear old field
                   2536:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2537:             currentform.elements[current.argfield].value = '';
                   2538:         }
                   2539:         current.argfield = choicearg;
                   2540:     }
                   2541:     set_auth_radio_buttons(choice,currentform);
                   2542:     return;
1.20      www      2543: }
1.32      matthew  2544: 
                   2545: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2546:     var numauthchoices = currentform.login.length;
                   2547:     if (typeof numauthchoices  == "undefined") {
                   2548:         return;
                   2549:     } 
1.32      matthew  2550:     var i=0;
1.986     raeburn  2551:     while (i < numauthchoices) {
1.32      matthew  2552:         if (currentform.login[i].value == newvalue) { break; }
                   2553:         i++;
                   2554:     }
1.986     raeburn  2555:     if (i == numauthchoices) {
1.32      matthew  2556:         return;
                   2557:     }
                   2558:     current.radiovalue = newvalue;
                   2559:     currentform.login[i].checked = true;
                   2560:     return;
                   2561: }
                   2562: END
                   2563:     return $result;
                   2564: }
                   2565: 
1.1106    raeburn  2566: sub authform_authorwarning {
1.32      matthew  2567:     my $result='';
1.144     matthew  2568:     $result='<i>'.
                   2569:         &mt('As a general rule, only authors or co-authors should be '.
                   2570:             'filesystem authenticated '.
                   2571:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2572:     return $result;
                   2573: }
                   2574: 
1.1106    raeburn  2575: sub authform_nochange {
1.32      matthew  2576:     my %in = (
                   2577:               formname => 'document.cu',
                   2578:               kerb_def_dom => 'MSU.EDU',
                   2579:               @_,
                   2580:           );
1.1106    raeburn  2581:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2582:     my $result;
1.1104    raeburn  2583:     if (!$authnum) {
1.1105    raeburn  2584:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2585:     } else {
                   2586:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2587:                   '<input type="radio" name="login" value="nochange" '.
                   2588:                   'checked="checked" onclick="'.
1.281     albertel 2589:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2590: 	    '</label>';
1.586     raeburn  2591:     }
1.32      matthew  2592:     return $result;
                   2593: }
                   2594: 
1.591     raeburn  2595: sub authform_kerberos {
1.32      matthew  2596:     my %in = (
                   2597:               formname => 'document.cu',
                   2598:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2599:               kerb_def_auth => 'krb4',
1.32      matthew  2600:               @_,
                   2601:               );
1.586     raeburn  2602:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2603:         $autharg,$jscall);
1.1106    raeburn  2604:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2605:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2606:        $check5 = ' checked="checked"';
1.80      albertel 2607:     } else {
1.772     bisitz   2608:        $check4 = ' checked="checked"';
1.80      albertel 2609:     }
1.165     raeburn  2610:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2611:     if (defined($in{'curr_authtype'})) {
                   2612:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2613:             $krbcheck = ' checked="checked"';
1.623     raeburn  2614:             if (defined($in{'mode'})) {
                   2615:                 if ($in{'mode'} eq 'modifyuser') {
                   2616:                     $krbcheck = '';
                   2617:                 }
                   2618:             }
1.591     raeburn  2619:             if (defined($in{'curr_kerb_ver'})) {
                   2620:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2621:                     $check5 = ' checked="checked"';
1.591     raeburn  2622:                     $check4 = '';
                   2623:                 } else {
1.772     bisitz   2624:                     $check4 = ' checked="checked"';
1.591     raeburn  2625:                     $check5 = '';
                   2626:                 }
1.586     raeburn  2627:             }
1.591     raeburn  2628:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2629:                 $krbarg = $in{'curr_autharg'};
                   2630:             }
1.586     raeburn  2631:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2632:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2633:                     $result = 
                   2634:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2635:         $in{'curr_autharg'},$krbver);
                   2636:                 } else {
                   2637:                     $result =
                   2638:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2639:                 }
                   2640:                 return $result; 
                   2641:             }
                   2642:         }
                   2643:     } else {
                   2644:         if ($authnum == 1) {
1.784     bisitz   2645:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2646:         }
                   2647:     }
1.586     raeburn  2648:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2649:         return;
1.587     raeburn  2650:     } elsif ($authtype eq '') {
1.591     raeburn  2651:         if (defined($in{'mode'})) {
1.587     raeburn  2652:             if ($in{'mode'} eq 'modifycourse') {
                   2653:                 if ($authnum == 1) {
1.1104    raeburn  2654:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2655:                 }
                   2656:             }
                   2657:         }
1.586     raeburn  2658:     }
                   2659:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2660:     if ($authtype eq '') {
                   2661:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2662:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2663:                     $krbcheck.' />';
                   2664:     }
                   2665:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2666:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2667:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2668:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2669:          $in{'curr_authtype'} eq 'krb4')) {
                   2670:         $result .= &mt
1.144     matthew  2671:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2672:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2673:          '<label>'.$authtype,
1.281     albertel 2674:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2675:              'value="'.$krbarg.'" '.
1.144     matthew  2676:              'onchange="'.$jscall.'" />',
1.281     albertel 2677:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2678:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2679: 	 '</label>');
1.586     raeburn  2680:     } elsif ($can_assign{'krb4'}) {
                   2681:         $result .= &mt
                   2682:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2683:          '[_3] Version 4 [_4]',
                   2684:          '<label>'.$authtype,
                   2685:          '</label><input type="text" size="10" name="krbarg" '.
                   2686:              'value="'.$krbarg.'" '.
                   2687:              'onchange="'.$jscall.'" />',
                   2688:          '<label><input type="hidden" name="krbver" value="4" />',
                   2689:          '</label>');
                   2690:     } elsif ($can_assign{'krb5'}) {
                   2691:         $result .= &mt
                   2692:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2693:          '[_3] Version 5 [_4]',
                   2694:          '<label>'.$authtype,
                   2695:          '</label><input type="text" size="10" name="krbarg" '.
                   2696:              'value="'.$krbarg.'" '.
                   2697:              'onchange="'.$jscall.'" />',
                   2698:          '<label><input type="hidden" name="krbver" value="5" />',
                   2699:          '</label>');
                   2700:     }
1.32      matthew  2701:     return $result;
                   2702: }
                   2703: 
1.1106    raeburn  2704: sub authform_internal {
1.586     raeburn  2705:     my %in = (
1.32      matthew  2706:                 formname => 'document.cu',
                   2707:                 kerb_def_dom => 'MSU.EDU',
                   2708:                 @_,
                   2709:                 );
1.586     raeburn  2710:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2711:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2712:     if (defined($in{'curr_authtype'})) {
                   2713:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2714:             if ($can_assign{'int'}) {
1.772     bisitz   2715:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2716:                 if (defined($in{'mode'})) {
                   2717:                     if ($in{'mode'} eq 'modifyuser') {
                   2718:                         $intcheck = '';
                   2719:                     }
                   2720:                 }
1.591     raeburn  2721:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2722:                     $intarg = $in{'curr_autharg'};
                   2723:                 }
                   2724:             } else {
                   2725:                 $result = &mt('Currently internally authenticated.');
                   2726:                 return $result;
1.165     raeburn  2727:             }
                   2728:         }
1.586     raeburn  2729:     } else {
                   2730:         if ($authnum == 1) {
1.784     bisitz   2731:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2732:         }
                   2733:     }
                   2734:     if (!$can_assign{'int'}) {
                   2735:         return;
1.587     raeburn  2736:     } elsif ($authtype eq '') {
1.591     raeburn  2737:         if (defined($in{'mode'})) {
1.587     raeburn  2738:             if ($in{'mode'} eq 'modifycourse') {
                   2739:                 if ($authnum == 1) {
1.1104    raeburn  2740:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2741:                 }
                   2742:             }
                   2743:         }
1.165     raeburn  2744:     }
1.586     raeburn  2745:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2746:     if ($authtype eq '') {
                   2747:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2748:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2749:     }
1.605     bisitz   2750:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2751:                $intarg.'" onchange="'.$jscall.'" />';
                   2752:     $result = &mt
1.144     matthew  2753:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2754:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2755:     $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>';
1.32      matthew  2756:     return $result;
                   2757: }
                   2758: 
1.1104    raeburn  2759: sub authform_local {
1.32      matthew  2760:     my %in = (
                   2761:               formname => 'document.cu',
                   2762:               kerb_def_dom => 'MSU.EDU',
                   2763:               @_,
                   2764:               );
1.586     raeburn  2765:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2766:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2767:     if (defined($in{'curr_authtype'})) {
                   2768:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2769:             if ($can_assign{'loc'}) {
1.772     bisitz   2770:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2771:                 if (defined($in{'mode'})) {
                   2772:                     if ($in{'mode'} eq 'modifyuser') {
                   2773:                         $loccheck = '';
                   2774:                     }
                   2775:                 }
1.591     raeburn  2776:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2777:                     $locarg = $in{'curr_autharg'};
                   2778:                 }
                   2779:             } else {
                   2780:                 $result = &mt('Currently using local (institutional) authentication.');
                   2781:                 return $result;
1.165     raeburn  2782:             }
                   2783:         }
1.586     raeburn  2784:     } else {
                   2785:         if ($authnum == 1) {
1.784     bisitz   2786:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2787:         }
                   2788:     }
                   2789:     if (!$can_assign{'loc'}) {
                   2790:         return;
1.587     raeburn  2791:     } elsif ($authtype eq '') {
1.591     raeburn  2792:         if (defined($in{'mode'})) {
1.587     raeburn  2793:             if ($in{'mode'} eq 'modifycourse') {
                   2794:                 if ($authnum == 1) {
1.1104    raeburn  2795:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2796:                 }
                   2797:             }
                   2798:         }
1.165     raeburn  2799:     }
1.586     raeburn  2800:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2801:     if ($authtype eq '') {
                   2802:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2803:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2804:                     $jscall.'" />';
                   2805:     }
                   2806:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2807:                $locarg.'" onchange="'.$jscall.'" />';
                   2808:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2809:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2810:     return $result;
                   2811: }
                   2812: 
1.1106    raeburn  2813: sub authform_filesystem {
1.32      matthew  2814:     my %in = (
                   2815:               formname => 'document.cu',
                   2816:               kerb_def_dom => 'MSU.EDU',
                   2817:               @_,
                   2818:               );
1.586     raeburn  2819:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2820:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2821:     if (defined($in{'curr_authtype'})) {
                   2822:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2823:             if ($can_assign{'fsys'}) {
1.772     bisitz   2824:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2825:                 if (defined($in{'mode'})) {
                   2826:                     if ($in{'mode'} eq 'modifyuser') {
                   2827:                         $fsyscheck = '';
                   2828:                     }
                   2829:                 }
1.586     raeburn  2830:             } else {
                   2831:                 $result = &mt('Currently Filesystem Authenticated.');
                   2832:                 return $result;
                   2833:             }           
                   2834:         }
                   2835:     } else {
                   2836:         if ($authnum == 1) {
1.784     bisitz   2837:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2838:         }
                   2839:     }
                   2840:     if (!$can_assign{'fsys'}) {
                   2841:         return;
1.587     raeburn  2842:     } elsif ($authtype eq '') {
1.591     raeburn  2843:         if (defined($in{'mode'})) {
1.587     raeburn  2844:             if ($in{'mode'} eq 'modifycourse') {
                   2845:                 if ($authnum == 1) {
1.1104    raeburn  2846:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2847:                 }
                   2848:             }
                   2849:         }
1.586     raeburn  2850:     }
                   2851:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2852:     if ($authtype eq '') {
                   2853:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2854:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2855:                     $jscall.'" />';
                   2856:     }
                   2857:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2858:                ' onchange="'.$jscall.'" />';
                   2859:     $result = &mt
1.144     matthew  2860:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2861:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2862:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2863:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2864:                   'onchange="'.$jscall.'" />');
1.32      matthew  2865:     return $result;
                   2866: }
                   2867: 
1.586     raeburn  2868: sub get_assignable_auth {
                   2869:     my ($dom) = @_;
                   2870:     if ($dom eq '') {
                   2871:         $dom = $env{'request.role.domain'};
                   2872:     }
                   2873:     my %can_assign = (
                   2874:                           krb4 => 1,
                   2875:                           krb5 => 1,
                   2876:                           int  => 1,
                   2877:                           loc  => 1,
                   2878:                      );
                   2879:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2880:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2881:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2882:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2883:             my $context;
                   2884:             if ($env{'request.role'} =~ /^au/) {
                   2885:                 $context = 'author';
                   2886:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2887:                 $context = 'domain';
                   2888:             } elsif ($env{'request.course.id'}) {
                   2889:                 $context = 'course';
                   2890:             }
                   2891:             if ($context) {
                   2892:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2893:                    %can_assign = %{$authhash->{$context}}; 
                   2894:                 }
                   2895:             }
                   2896:         }
                   2897:     }
                   2898:     my $authnum = 0;
                   2899:     foreach my $key (keys(%can_assign)) {
                   2900:         if ($can_assign{$key}) {
                   2901:             $authnum ++;
                   2902:         }
                   2903:     }
                   2904:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2905:         $authnum --;
                   2906:     }
                   2907:     return ($authnum,%can_assign);
                   2908: }
                   2909: 
1.80      albertel 2910: ###############################################################
                   2911: ##    Get Kerberos Defaults for Domain                 ##
                   2912: ###############################################################
                   2913: ##
                   2914: ## Returns default kerberos version and an associated argument
                   2915: ## as listed in file domain.tab. If not listed, provides
                   2916: ## appropriate default domain and kerberos version.
                   2917: ##
                   2918: #-------------------------------------------
                   2919: 
                   2920: =pod
                   2921: 
1.648     raeburn  2922: =item * &get_kerberos_defaults()
1.80      albertel 2923: 
                   2924: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2925: version and domain. If not found, it defaults to version 4 and the 
                   2926: domain of the server.
1.80      albertel 2927: 
1.648     raeburn  2928: =over 4
                   2929: 
1.80      albertel 2930: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2931: 
1.648     raeburn  2932: =back
                   2933: 
                   2934: =back
                   2935: 
1.80      albertel 2936: =cut
                   2937: 
                   2938: #-------------------------------------------
                   2939: sub get_kerberos_defaults {
                   2940:     my $domain=shift;
1.641     raeburn  2941:     my ($krbdef,$krbdefdom);
                   2942:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2943:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2944:         $krbdef = $domdefaults{'auth_def'};
                   2945:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2946:     } else {
1.80      albertel 2947:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2948:         my $krbdefdom=$1;
                   2949:         $krbdefdom=~tr/a-z/A-Z/;
                   2950:         $krbdef = "krb4";
                   2951:     }
                   2952:     return ($krbdef,$krbdefdom);
                   2953: }
1.112     bowersj2 2954: 
1.32      matthew  2955: 
1.46      matthew  2956: ###############################################################
                   2957: ##                Thesaurus Functions                        ##
                   2958: ###############################################################
1.20      www      2959: 
1.46      matthew  2960: =pod
1.20      www      2961: 
1.112     bowersj2 2962: =head1 Thesaurus Functions
                   2963: 
                   2964: =over 4
                   2965: 
1.648     raeburn  2966: =item * &initialize_keywords()
1.46      matthew  2967: 
                   2968: Initializes the package variable %Keywords if it is empty.  Uses the
                   2969: package variable $thesaurus_db_file.
                   2970: 
                   2971: =cut
                   2972: 
                   2973: ###################################################
                   2974: 
                   2975: sub initialize_keywords {
                   2976:     return 1 if (scalar keys(%Keywords));
                   2977:     # If we are here, %Keywords is empty, so fill it up
                   2978:     #   Make sure the file we need exists...
                   2979:     if (! -e $thesaurus_db_file) {
                   2980:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2981:                                  " failed because it does not exist");
                   2982:         return 0;
                   2983:     }
                   2984:     #   Set up the hash as a database
                   2985:     my %thesaurus_db;
                   2986:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2987:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2988:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2989:                                  $thesaurus_db_file);
                   2990:         return 0;
                   2991:     } 
                   2992:     #  Get the average number of appearances of a word.
                   2993:     my $avecount = $thesaurus_db{'average.count'};
                   2994:     #  Put keywords (those that appear > average) into %Keywords
                   2995:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2996:         my ($count,undef) = split /:/,$data;
                   2997:         $Keywords{$word}++ if ($count > $avecount);
                   2998:     }
                   2999:     untie %thesaurus_db;
                   3000:     # Remove special values from %Keywords.
1.356     albertel 3001:     foreach my $value ('total.count','average.count') {
                   3002:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3003:   }
1.46      matthew  3004:     return 1;
                   3005: }
                   3006: 
                   3007: ###################################################
                   3008: 
                   3009: =pod
                   3010: 
1.648     raeburn  3011: =item * &keyword($word)
1.46      matthew  3012: 
                   3013: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3014: than the average number of times in the thesaurus database.  Calls 
                   3015: &initialize_keywords
                   3016: 
                   3017: =cut
                   3018: 
                   3019: ###################################################
1.20      www      3020: 
                   3021: sub keyword {
1.46      matthew  3022:     return if (!&initialize_keywords());
                   3023:     my $word=lc(shift());
                   3024:     $word=~s/\W//g;
                   3025:     return exists($Keywords{$word});
1.20      www      3026: }
1.46      matthew  3027: 
                   3028: ###############################################################
                   3029: 
                   3030: =pod 
1.20      www      3031: 
1.648     raeburn  3032: =item * &get_related_words()
1.46      matthew  3033: 
1.160     matthew  3034: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3035: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3036: will be returned.  The order of the words returned is determined by the
                   3037: database which holds them.
                   3038: 
                   3039: Uses global $thesaurus_db_file.
                   3040: 
1.1057    foxr     3041: 
1.46      matthew  3042: =cut
                   3043: 
                   3044: ###############################################################
                   3045: sub get_related_words {
                   3046:     my $keyword = shift;
                   3047:     my %thesaurus_db;
                   3048:     if (! -e $thesaurus_db_file) {
                   3049:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3050:                                  "failed because the file does not exist");
                   3051:         return ();
                   3052:     }
                   3053:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3054:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3055:         return ();
                   3056:     } 
                   3057:     my @Words=();
1.429     www      3058:     my $count=0;
1.46      matthew  3059:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3060: 	# The first element is the number of times
                   3061: 	# the word appears.  We do not need it now.
1.429     www      3062: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3063: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3064: 	my $threshold=$mostfrequentcount/10;
                   3065:         foreach my $possibleword (@RelatedWords) {
                   3066:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3067:             if ($wordcount>$threshold) {
                   3068: 		push(@Words,$word);
                   3069:                 $count++;
                   3070:                 if ($count>10) { last; }
                   3071: 	    }
1.20      www      3072:         }
                   3073:     }
1.46      matthew  3074:     untie %thesaurus_db;
                   3075:     return @Words;
1.14      harris41 3076: }
1.1090    foxr     3077: ###############################################################
                   3078: #
                   3079: #  Spell checking
                   3080: #
                   3081: 
                   3082: =pod
                   3083: 
1.1142    raeburn  3084: =back
                   3085: 
1.1090    foxr     3086: =head1 Spell checking
                   3087: 
                   3088: =over 4
                   3089: 
                   3090: =item * &check_spelling($wordlist $language)
                   3091: 
                   3092: Takes a string containing words and feeds it to an external
                   3093: spellcheck program via a pipeline. Returns a string containing
                   3094: them mis-spelled words.
                   3095: 
                   3096: Parameters:
                   3097: 
                   3098: =over 4
                   3099: 
                   3100: =item - $wordlist
                   3101: 
                   3102: String that will be fed into the spellcheck program.
                   3103: 
                   3104: =item - $language
                   3105: 
                   3106: Language string that specifies the language for which the spell
                   3107: check will be performed.
                   3108: 
                   3109: =back
                   3110: 
                   3111: =back
                   3112: 
                   3113: Note: This sub assumes that aspell is installed.
                   3114: 
                   3115: 
                   3116: =cut
                   3117: 
1.46      matthew  3118: 
1.1090    foxr     3119: sub check_spelling {
                   3120:     my ($wordlist, $language) = @_;
1.1091    foxr     3121:     my @misspellings;
                   3122:     
                   3123:     # Generate the speller and set the langauge.
                   3124:     # if explicitly selected:
1.1090    foxr     3125: 
1.1091    foxr     3126:     my $speller = Text::Aspell->new;
1.1090    foxr     3127:     if ($language) {
1.1091    foxr     3128: 	$speller->set_option('lang', $language);
1.1090    foxr     3129:     }
                   3130: 
1.1091    foxr     3131:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3132: 
1.1091    foxr     3133:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3134: 
1.1091    foxr     3135:     foreach my $word (@words) {
                   3136: 	if(! $speller->check($word)) {
                   3137: 	    push(@misspellings, $word);
1.1090    foxr     3138: 	}
                   3139:     }
1.1091    foxr     3140:     return join(' ', @misspellings);
                   3141:     
1.1090    foxr     3142: }
                   3143: 
1.61      www      3144: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3145: =pod
                   3146: 
1.112     bowersj2 3147: =head1 User Name Functions
                   3148: 
                   3149: =over 4
                   3150: 
1.648     raeburn  3151: =item * &plainname($uname,$udom,$first)
1.81      albertel 3152: 
1.112     bowersj2 3153: Takes a users logon name and returns it as a string in
1.226     albertel 3154: "first middle last generation" form 
                   3155: if $first is set to 'lastname' then it returns it as
                   3156: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3157: 
                   3158: =cut
1.61      www      3159: 
1.295     www      3160: 
1.81      albertel 3161: ###############################################################
1.61      www      3162: sub plainname {
1.226     albertel 3163:     my ($uname,$udom,$first)=@_;
1.537     albertel 3164:     return if (!defined($uname) || !defined($udom));
1.295     www      3165:     my %names=&getnames($uname,$udom);
1.226     albertel 3166:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3167: 					  $names{'middlename'},
                   3168: 					  $names{'lastname'},
                   3169: 					  $names{'generation'},$first);
                   3170:     $name=~s/^\s+//;
1.62      www      3171:     $name=~s/\s+$//;
                   3172:     $name=~s/\s+/ /g;
1.353     albertel 3173:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3174:     return $name;
1.61      www      3175: }
1.66      www      3176: 
                   3177: # -------------------------------------------------------------------- Nickname
1.81      albertel 3178: =pod
                   3179: 
1.648     raeburn  3180: =item * &nickname($uname,$udom)
1.81      albertel 3181: 
                   3182: Gets a users name and returns it as a string as
                   3183: 
                   3184: "&quot;nickname&quot;"
1.66      www      3185: 
1.81      albertel 3186: if the user has a nickname or
                   3187: 
                   3188: "first middle last generation"
                   3189: 
                   3190: if the user does not
                   3191: 
                   3192: =cut
1.66      www      3193: 
                   3194: sub nickname {
                   3195:     my ($uname,$udom)=@_;
1.537     albertel 3196:     return if (!defined($uname) || !defined($udom));
1.295     www      3197:     my %names=&getnames($uname,$udom);
1.68      albertel 3198:     my $name=$names{'nickname'};
1.66      www      3199:     if ($name) {
                   3200:        $name='&quot;'.$name.'&quot;'; 
                   3201:     } else {
                   3202:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3203: 	     $names{'lastname'}.' '.$names{'generation'};
                   3204:        $name=~s/\s+$//;
                   3205:        $name=~s/\s+/ /g;
                   3206:     }
                   3207:     return $name;
                   3208: }
                   3209: 
1.295     www      3210: sub getnames {
                   3211:     my ($uname,$udom)=@_;
1.537     albertel 3212:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3213:     if ($udom eq 'public' && $uname eq 'public') {
                   3214: 	return ('lastname' => &mt('Public'));
                   3215:     }
1.295     www      3216:     my $id=$uname.':'.$udom;
                   3217:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3218:     if ($cached) {
                   3219: 	return %{$names};
                   3220:     } else {
                   3221: 	my %loadnames=&Apache::lonnet::get('environment',
                   3222:                     ['firstname','middlename','lastname','generation','nickname'],
                   3223: 					 $udom,$uname);
                   3224: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3225: 	return %loadnames;
                   3226:     }
                   3227: }
1.61      www      3228: 
1.542     raeburn  3229: # -------------------------------------------------------------------- getemails
1.648     raeburn  3230: 
1.542     raeburn  3231: =pod
                   3232: 
1.648     raeburn  3233: =item * &getemails($uname,$udom)
1.542     raeburn  3234: 
                   3235: Gets a user's email information and returns it as a hash with keys:
                   3236: notification, critnotification, permanentemail
                   3237: 
                   3238: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3239: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3240:  
1.648     raeburn  3241: 
1.542     raeburn  3242: =cut
                   3243: 
1.648     raeburn  3244: 
1.466     albertel 3245: sub getemails {
                   3246:     my ($uname,$udom)=@_;
                   3247:     if ($udom eq 'public' && $uname eq 'public') {
                   3248: 	return;
                   3249:     }
1.467     www      3250:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3251:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3252:     my $id=$uname.':'.$udom;
                   3253:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3254:     if ($cached) {
                   3255: 	return %{$names};
                   3256:     } else {
                   3257: 	my %loadnames=&Apache::lonnet::get('environment',
                   3258:                     			   ['notification','critnotification',
                   3259: 					    'permanentemail'],
                   3260: 					   $udom,$uname);
                   3261: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3262: 	return %loadnames;
                   3263:     }
                   3264: }
                   3265: 
1.551     albertel 3266: sub flush_email_cache {
                   3267:     my ($uname,$udom)=@_;
                   3268:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3269:     if (!$uname) { $uname=$env{'user.name'};   }
                   3270:     return if ($udom eq 'public' && $uname eq 'public');
                   3271:     my $id=$uname.':'.$udom;
                   3272:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3273: }
                   3274: 
1.728     raeburn  3275: # -------------------------------------------------------------------- getlangs
                   3276: 
                   3277: =pod
                   3278: 
                   3279: =item * &getlangs($uname,$udom)
                   3280: 
                   3281: Gets a user's language preference and returns it as a hash with key:
                   3282: language.
                   3283: 
                   3284: =cut
                   3285: 
                   3286: 
                   3287: sub getlangs {
                   3288:     my ($uname,$udom) = @_;
                   3289:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3290:     if (!$uname) { $uname=$env{'user.name'};   }
                   3291:     my $id=$uname.':'.$udom;
                   3292:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3293:     if ($cached) {
                   3294:         return %{$langs};
                   3295:     } else {
                   3296:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3297:                                            $udom,$uname);
                   3298:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3299:         return %loadlangs;
                   3300:     }
                   3301: }
                   3302: 
                   3303: sub flush_langs_cache {
                   3304:     my ($uname,$udom)=@_;
                   3305:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3306:     if (!$uname) { $uname=$env{'user.name'};   }
                   3307:     return if ($udom eq 'public' && $uname eq 'public');
                   3308:     my $id=$uname.':'.$udom;
                   3309:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3310: }
                   3311: 
1.61      www      3312: # ------------------------------------------------------------------ Screenname
1.81      albertel 3313: 
                   3314: =pod
                   3315: 
1.648     raeburn  3316: =item * &screenname($uname,$udom)
1.81      albertel 3317: 
                   3318: Gets a users screenname and returns it as a string
                   3319: 
                   3320: =cut
1.61      www      3321: 
                   3322: sub screenname {
                   3323:     my ($uname,$udom)=@_;
1.258     albertel 3324:     if ($uname eq $env{'user.name'} &&
                   3325: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3326:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3327:     return $names{'screenname'};
1.62      www      3328: }
                   3329: 
1.212     albertel 3330: 
1.802     bisitz   3331: # ------------------------------------------------------------- Confirm Wrapper
                   3332: =pod
                   3333: 
1.1142    raeburn  3334: =item * &confirmwrapper($message)
1.802     bisitz   3335: 
                   3336: Wrap messages about completion of operation in box
                   3337: 
                   3338: =cut
                   3339: 
                   3340: sub confirmwrapper {
                   3341:     my ($message)=@_;
                   3342:     if ($message) {
                   3343:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3344:                .$message."\n"
                   3345:                .'</div>'."\n";
                   3346:     } else {
                   3347:         return $message;
                   3348:     }
                   3349: }
                   3350: 
1.62      www      3351: # ------------------------------------------------------------- Message Wrapper
                   3352: 
                   3353: sub messagewrapper {
1.369     www      3354:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3355:     return 
1.441     albertel 3356:         '<a href="/adm/email?compose=individual&amp;'.
                   3357:         'recname='.$username.'&amp;recdom='.$domain.
                   3358: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3359:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3360: }
1.802     bisitz   3361: 
1.74      www      3362: # --------------------------------------------------------------- Notes Wrapper
                   3363: 
                   3364: sub noteswrapper {
                   3365:     my ($link,$un,$do)=@_;
                   3366:     return 
1.896     amueller 3367: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3368: }
1.802     bisitz   3369: 
1.62      www      3370: # ------------------------------------------------------------- Aboutme Wrapper
                   3371: 
                   3372: sub aboutmewrapper {
1.1070    raeburn  3373:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3374:     if (!defined($username)  && !defined($domain)) {
                   3375:         return;
                   3376:     }
1.1096    raeburn  3377:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3378: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3379: }
                   3380: 
                   3381: # ------------------------------------------------------------ Syllabus Wrapper
                   3382: 
                   3383: sub syllabuswrapper {
1.707     bisitz   3384:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3385:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3386: }
1.14      harris41 3387: 
1.802     bisitz   3388: # -----------------------------------------------------------------------------
                   3389: 
1.208     matthew  3390: sub track_student_link {
1.887     raeburn  3391:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3392:     my $link ="/adm/trackstudent?";
1.208     matthew  3393:     my $title = 'View recent activity';
                   3394:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3395:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3396:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3397:         $title .= ' of this student';
1.268     albertel 3398:     } 
1.208     matthew  3399:     if (defined($target) && $target !~ /^\s*$/) {
                   3400:         $target = qq{target="$target"};
                   3401:     } else {
                   3402:         $target = '';
                   3403:     }
1.268     albertel 3404:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3405:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3406:     $title = &mt($title);
                   3407:     $linktext = &mt($linktext);
1.448     albertel 3408:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3409: 	&help_open_topic('View_recent_activity');
1.208     matthew  3410: }
                   3411: 
1.781     raeburn  3412: sub slot_reservations_link {
                   3413:     my ($linktext,$sname,$sdom,$target) = @_;
                   3414:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3415:     my $title = 'View slot reservation history';
                   3416:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3417:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3418:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3419:         $title .= ' of this student';
                   3420:     }
                   3421:     if (defined($target) && $target !~ /^\s*$/) {
                   3422:         $target = qq{target="$target"};
                   3423:     } else {
                   3424:         $target = '';
                   3425:     }
                   3426:     $title = &mt($title);
                   3427:     $linktext = &mt($linktext);
                   3428:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3429: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3430: 
                   3431: }
                   3432: 
1.508     www      3433: # ===================================================== Display a student photo
                   3434: 
                   3435: 
1.509     albertel 3436: sub student_image_tag {
1.508     www      3437:     my ($domain,$user)=@_;
                   3438:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3439:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3440: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3441:     } else {
                   3442: 	return '';
                   3443:     }
                   3444: }
                   3445: 
1.112     bowersj2 3446: =pod
                   3447: 
                   3448: =back
                   3449: 
                   3450: =head1 Access .tab File Data
                   3451: 
                   3452: =over 4
                   3453: 
1.648     raeburn  3454: =item * &languageids() 
1.112     bowersj2 3455: 
                   3456: returns list of all language ids
                   3457: 
                   3458: =cut
                   3459: 
1.14      harris41 3460: sub languageids {
1.16      harris41 3461:     return sort(keys(%language));
1.14      harris41 3462: }
                   3463: 
1.112     bowersj2 3464: =pod
                   3465: 
1.648     raeburn  3466: =item * &languagedescription() 
1.112     bowersj2 3467: 
                   3468: returns description of a specified language id
                   3469: 
                   3470: =cut
                   3471: 
1.14      harris41 3472: sub languagedescription {
1.125     www      3473:     my $code=shift;
                   3474:     return  ($supported_language{$code}?'* ':'').
                   3475:             $language{$code}.
1.126     www      3476: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3477: }
                   3478: 
1.1048    foxr     3479: =pod
                   3480: 
                   3481: =item * &plainlanguagedescription
                   3482: 
                   3483: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3484: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3485: 
                   3486: =cut
                   3487: 
1.145     www      3488: sub plainlanguagedescription {
                   3489:     my $code=shift;
                   3490:     return $language{$code};
                   3491: }
                   3492: 
1.1048    foxr     3493: =pod
                   3494: 
                   3495: =item * &supportedlanguagecode
                   3496: 
                   3497: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3498: code.
                   3499: 
                   3500: =cut
                   3501: 
1.145     www      3502: sub supportedlanguagecode {
                   3503:     my $code=shift;
                   3504:     return $supported_language{$code};
1.97      www      3505: }
                   3506: 
1.112     bowersj2 3507: =pod
                   3508: 
1.1048    foxr     3509: =item * &latexlanguage()
                   3510: 
                   3511: Given a language key code returns the correspondnig language to use
                   3512: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3513: is no supported hyphenation for the language code.
                   3514: 
                   3515: =cut
                   3516: 
                   3517: sub latexlanguage {
                   3518:     my $code = shift;
                   3519:     return $latex_language{$code};
                   3520: }
                   3521: 
                   3522: =pod
                   3523: 
                   3524: =item * &latexhyphenation()
                   3525: 
                   3526: Same as above but what's supplied is the language as it might be stored
                   3527: in the metadata.
                   3528: 
                   3529: =cut
                   3530: 
                   3531: sub latexhyphenation {
                   3532:     my $key = shift;
                   3533:     return $latex_language_bykey{$key};
                   3534: }
                   3535: 
                   3536: =pod
                   3537: 
1.648     raeburn  3538: =item * &copyrightids() 
1.112     bowersj2 3539: 
                   3540: returns list of all copyrights
                   3541: 
                   3542: =cut
                   3543: 
                   3544: sub copyrightids {
                   3545:     return sort(keys(%cprtag));
                   3546: }
                   3547: 
                   3548: =pod
                   3549: 
1.648     raeburn  3550: =item * &copyrightdescription() 
1.112     bowersj2 3551: 
                   3552: returns description of a specified copyright id
                   3553: 
                   3554: =cut
                   3555: 
                   3556: sub copyrightdescription {
1.166     www      3557:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3558: }
1.197     matthew  3559: 
                   3560: =pod
                   3561: 
1.648     raeburn  3562: =item * &source_copyrightids() 
1.192     taceyjo1 3563: 
                   3564: returns list of all source copyrights
                   3565: 
                   3566: =cut
                   3567: 
                   3568: sub source_copyrightids {
                   3569:     return sort(keys(%scprtag));
                   3570: }
                   3571: 
                   3572: =pod
                   3573: 
1.648     raeburn  3574: =item * &source_copyrightdescription() 
1.192     taceyjo1 3575: 
                   3576: returns description of a specified source copyright id
                   3577: 
                   3578: =cut
                   3579: 
                   3580: sub source_copyrightdescription {
                   3581:     return &mt($scprtag{shift(@_)});
                   3582: }
1.112     bowersj2 3583: 
                   3584: =pod
                   3585: 
1.648     raeburn  3586: =item * &filecategories() 
1.112     bowersj2 3587: 
                   3588: returns list of all file categories
                   3589: 
                   3590: =cut
                   3591: 
                   3592: sub filecategories {
                   3593:     return sort(keys(%category_extensions));
                   3594: }
                   3595: 
                   3596: =pod
                   3597: 
1.648     raeburn  3598: =item * &filecategorytypes() 
1.112     bowersj2 3599: 
                   3600: returns list of file types belonging to a given file
                   3601: category
                   3602: 
                   3603: =cut
                   3604: 
                   3605: sub filecategorytypes {
1.356     albertel 3606:     my ($cat) = @_;
                   3607:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3608: }
                   3609: 
                   3610: =pod
                   3611: 
1.648     raeburn  3612: =item * &fileembstyle() 
1.112     bowersj2 3613: 
                   3614: returns embedding style for a specified file type
                   3615: 
                   3616: =cut
                   3617: 
                   3618: sub fileembstyle {
                   3619:     return $fe{lc(shift(@_))};
1.169     www      3620: }
                   3621: 
1.351     www      3622: sub filemimetype {
                   3623:     return $fm{lc(shift(@_))};
                   3624: }
                   3625: 
1.169     www      3626: 
                   3627: sub filecategoryselect {
                   3628:     my ($name,$value)=@_;
1.189     matthew  3629:     return &select_form($value,$name,
1.970     raeburn  3630:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3631: }
                   3632: 
                   3633: =pod
                   3634: 
1.648     raeburn  3635: =item * &filedescription() 
1.112     bowersj2 3636: 
                   3637: returns description for a specified file type
                   3638: 
                   3639: =cut
                   3640: 
                   3641: sub filedescription {
1.188     matthew  3642:     my $file_description = $fd{lc(shift())};
                   3643:     $file_description =~ s:([\[\]]):~$1:g;
                   3644:     return &mt($file_description);
1.112     bowersj2 3645: }
                   3646: 
                   3647: =pod
                   3648: 
1.648     raeburn  3649: =item * &filedescriptionex() 
1.112     bowersj2 3650: 
                   3651: returns description for a specified file type with
                   3652: extra formatting
                   3653: 
                   3654: =cut
                   3655: 
                   3656: sub filedescriptionex {
                   3657:     my $ex=shift;
1.188     matthew  3658:     my $file_description = $fd{lc($ex)};
                   3659:     $file_description =~ s:([\[\]]):~$1:g;
                   3660:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3661: }
                   3662: 
                   3663: # End of .tab access
                   3664: =pod
                   3665: 
                   3666: =back
                   3667: 
                   3668: =cut
                   3669: 
                   3670: # ------------------------------------------------------------------ File Types
                   3671: sub fileextensions {
                   3672:     return sort(keys(%fe));
                   3673: }
                   3674: 
1.97      www      3675: # ----------------------------------------------------------- Display Languages
                   3676: # returns a hash with all desired display languages
                   3677: #
                   3678: 
                   3679: sub display_languages {
                   3680:     my %languages=();
1.695     raeburn  3681:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3682: 	$languages{$lang}=1;
1.97      www      3683:     }
                   3684:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3685:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3686: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3687: 	    $languages{$lang}=1;
1.97      www      3688:         }
                   3689:     }
                   3690:     return %languages;
1.14      harris41 3691: }
                   3692: 
1.582     albertel 3693: sub languages {
                   3694:     my ($possible_langs) = @_;
1.695     raeburn  3695:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3696:     if (!ref($possible_langs)) {
                   3697: 	if( wantarray ) {
                   3698: 	    return @preferred_langs;
                   3699: 	} else {
                   3700: 	    return $preferred_langs[0];
                   3701: 	}
                   3702:     }
                   3703:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3704:     my @preferred_possibilities;
                   3705:     foreach my $preferred_lang (@preferred_langs) {
                   3706: 	if (exists($possibilities{$preferred_lang})) {
                   3707: 	    push(@preferred_possibilities, $preferred_lang);
                   3708: 	}
                   3709:     }
                   3710:     if( wantarray ) {
                   3711: 	return @preferred_possibilities;
                   3712:     }
                   3713:     return $preferred_possibilities[0];
                   3714: }
                   3715: 
1.742     raeburn  3716: sub user_lang {
                   3717:     my ($touname,$toudom,$fromcid) = @_;
                   3718:     my @userlangs;
                   3719:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3720:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3721:                     $env{'course.'.$fromcid.'.languages'}));
                   3722:     } else {
                   3723:         my %langhash = &getlangs($touname,$toudom);
                   3724:         if ($langhash{'languages'} ne '') {
                   3725:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3726:         } else {
                   3727:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3728:             if ($domdefs{'lang_def'} ne '') {
                   3729:                 @userlangs = ($domdefs{'lang_def'});
                   3730:             }
                   3731:         }
                   3732:     }
                   3733:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3734:     my $user_lh = Apache::localize->get_handle(@languages);
                   3735:     return $user_lh;
                   3736: }
                   3737: 
                   3738: 
1.112     bowersj2 3739: ###############################################################
                   3740: ##               Student Answer Attempts                     ##
                   3741: ###############################################################
                   3742: 
                   3743: =pod
                   3744: 
                   3745: =head1 Alternate Problem Views
                   3746: 
                   3747: =over 4
                   3748: 
1.648     raeburn  3749: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3750:     $getattempt, $regexp, $gradesub)
                   3751: 
                   3752: Return string with previous attempt on problem. Arguments:
                   3753: 
                   3754: =over 4
                   3755: 
                   3756: =item * $symb: Problem, including path
                   3757: 
                   3758: =item * $username: username of the desired student
                   3759: 
                   3760: =item * $domain: domain of the desired student
1.14      harris41 3761: 
1.112     bowersj2 3762: =item * $course: Course ID
1.14      harris41 3763: 
1.112     bowersj2 3764: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3765:     something
1.14      harris41 3766: 
1.112     bowersj2 3767: =item * $regexp: if string matches this regexp, the string will be
                   3768:     sent to $gradesub
1.14      harris41 3769: 
1.112     bowersj2 3770: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3771: 
1.112     bowersj2 3772: =back
1.14      harris41 3773: 
1.112     bowersj2 3774: The output string is a table containing all desired attempts, if any.
1.16      harris41 3775: 
1.112     bowersj2 3776: =cut
1.1       albertel 3777: 
                   3778: sub get_previous_attempt {
1.43      ng       3779:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3780:   my $prevattempts='';
1.43      ng       3781:   no strict 'refs';
1.1       albertel 3782:   if ($symb) {
1.3       albertel 3783:     my (%returnhash)=
                   3784:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3785:     if ($returnhash{'version'}) {
                   3786:       my %lasthash=();
                   3787:       my $version;
                   3788:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3789:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3790: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3791:         }
1.1       albertel 3792:       }
1.596     albertel 3793:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3794:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3795:       my (%typeparts,%lasthidden);
1.945     raeburn  3796:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3797:       foreach my $key (sort(keys(%lasthash))) {
                   3798: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3799: 	if ($#parts > 0) {
1.31      albertel 3800: 	  my $data=$parts[-1];
1.989     raeburn  3801:           next if ($data eq 'foilorder');
1.31      albertel 3802: 	  pop(@parts);
1.1010    www      3803:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3804:           if ($data eq 'type') {
                   3805:               unless ($showsurv) {
                   3806:                   my $id = join(',',@parts);
                   3807:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3808:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3809:                       $lasthidden{$ign.'.'.$id} = 1;
                   3810:                   }
1.945     raeburn  3811:               }
1.1010    www      3812:           } 
1.31      albertel 3813: 	} else {
1.41      ng       3814: 	  if ($#parts == 0) {
                   3815: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3816: 	  } else {
                   3817: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3818: 	  }
1.31      albertel 3819: 	}
1.16      harris41 3820:       }
1.596     albertel 3821:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3822:       if ($getattempt eq '') {
                   3823: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3824:             my @hidden;
                   3825:             if (%typeparts) {
                   3826:                 foreach my $id (keys(%typeparts)) {
                   3827:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3828:                         push(@hidden,$id);
                   3829:                     }
                   3830:                 }
                   3831:             }
                   3832:             $prevattempts.=&start_data_table_row().
                   3833:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3834:             if (@hidden) {
                   3835:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3836:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3837:                     my $hide;
                   3838:                     foreach my $id (@hidden) {
                   3839:                         if ($key =~ /^\Q$id\E/) {
                   3840:                             $hide = 1;
                   3841:                             last;
                   3842:                         }
                   3843:                     }
                   3844:                     if ($hide) {
                   3845:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3846:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3847:                             my $value = &format_previous_attempt_value($key,
                   3848:                                              $returnhash{$version.':'.$key});
1.1171    kruse    3849:                             $prevattempts.='<td>'.&HTML::Entities::encode($value, '"<>&').'&nbsp;</td>';
1.945     raeburn  3850:                         } else {
                   3851:                             $prevattempts.='<td>&nbsp;</td>';
                   3852:                         }
                   3853:                     } else {
                   3854:                         if ($key =~ /\./) {
                   3855:                             my $value = &format_previous_attempt_value($key,
                   3856:                                               $returnhash{$version.':'.$key});
1.1171    kruse    3857:                             $prevattempts.='<td>'.&HTML::Entities::encode($value, '"<>&').'&nbsp;</td>';
1.945     raeburn  3858:                         } else {
                   3859:                             $prevattempts.='<td>&nbsp;</td>';
                   3860:                         }
                   3861:                     }
                   3862:                 }
                   3863:             } else {
                   3864: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3865:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3866: 		    my $value = &format_previous_attempt_value($key,
                   3867: 			            $returnhash{$version.':'.$key});
1.1171    kruse    3868: 		    $prevattempts.='<td>'.&HTML::Entities::encode($value, '"<>&').'&nbsp;</td>';
1.945     raeburn  3869: 	        }
                   3870:             }
                   3871: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3872: 	 }
1.1       albertel 3873:       }
1.945     raeburn  3874:       my @currhidden = keys(%lasthidden);
1.596     albertel 3875:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3876:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3877:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3878:           if (%typeparts) {
                   3879:               my $hidden;
                   3880:               foreach my $id (@currhidden) {
                   3881:                   if ($key =~ /^\Q$id\E/) {
                   3882:                       $hidden = 1;
                   3883:                       last;
                   3884:                   }
                   3885:               }
                   3886:               if ($hidden) {
                   3887:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3888:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3889:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3890:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3891:                           $value = &$gradesub($value);
                   3892:                       }
1.1171    kruse    3893:                       $prevattempts.='<td>'. &HTML::Entities::encode($value, '"<>&').'&nbsp;</td>';
1.945     raeburn  3894:                   } else {
                   3895:                       $prevattempts.='<td>&nbsp;</td>';
                   3896:                   }
                   3897:               } else {
                   3898:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3899:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3900:                       $value = &$gradesub($value);
                   3901:                   }
1.1171    kruse    3902:                   $prevattempts.='<td>'.&HTML::Entities::encode($value, '"<>&').'&nbsp;</td>';
1.945     raeburn  3903:               }
                   3904:           } else {
                   3905: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3906: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3907:                   $value = &$gradesub($value);
                   3908:               }
1.1171    kruse    3909: 	      $prevattempts.='<td>'.&HTML::Entities::encode($value, '"<>&').'&nbsp;</td>';
1.945     raeburn  3910:           }
1.16      harris41 3911:       }
1.596     albertel 3912:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3913:     } else {
1.596     albertel 3914:       $prevattempts=
                   3915: 	  &start_data_table().&start_data_table_row().
                   3916: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3917: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3918:     }
                   3919:   } else {
1.596     albertel 3920:     $prevattempts=
                   3921: 	  &start_data_table().&start_data_table_row().
                   3922: 	  '<td>'.&mt('No data.').'</td>'.
                   3923: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3924:   }
1.10      albertel 3925: }
                   3926: 
1.581     albertel 3927: sub format_previous_attempt_value {
                   3928:     my ($key,$value) = @_;
1.1011    www      3929:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3930: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3931:     } elsif (ref($value) eq 'ARRAY') {
                   3932: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3933:     } elsif ($key =~ /answerstring$/) {
                   3934:         my %answers = &Apache::lonnet::str2hash($value);
                   3935:         my @anskeys = sort(keys(%answers));
                   3936:         if (@anskeys == 1) {
                   3937:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3938:             if ($answer =~ m{\0}) {
                   3939:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3940:             }
                   3941:             my $tag_internal_answer_name = 'INTERNAL';
                   3942:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3943:                 $value = $answer; 
                   3944:             } else {
                   3945:                 $value = $anskeys[0].'='.$answer;
                   3946:             }
                   3947:         } else {
                   3948:             foreach my $ans (@anskeys) {
                   3949:                 my $answer = $answers{$ans};
1.1001    raeburn  3950:                 if ($answer =~ m{\0}) {
                   3951:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3952:                 }
                   3953:                 $value .=  $ans.'='.$answer.'<br />';;
                   3954:             } 
                   3955:         }
1.581     albertel 3956:     } else {
                   3957: 	$value = &unescape($value);
                   3958:     }
                   3959:     return $value;
                   3960: }
                   3961: 
                   3962: 
1.107     albertel 3963: sub relative_to_absolute {
                   3964:     my ($url,$output)=@_;
                   3965:     my $parser=HTML::TokeParser->new(\$output);
                   3966:     my $token;
                   3967:     my $thisdir=$url;
                   3968:     my @rlinks=();
                   3969:     while ($token=$parser->get_token) {
                   3970: 	if ($token->[0] eq 'S') {
                   3971: 	    if ($token->[1] eq 'a') {
                   3972: 		if ($token->[2]->{'href'}) {
                   3973: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3974: 		}
                   3975: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3976: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3977: 	    } elsif ($token->[1] eq 'base') {
                   3978: 		$thisdir=$token->[2]->{'href'};
                   3979: 	    }
                   3980: 	}
                   3981:     }
                   3982:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3983:     foreach my $link (@rlinks) {
1.726     raeburn  3984: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3985: 		($link=~/^\//) ||
                   3986: 		($link=~/^javascript:/i) ||
                   3987: 		($link=~/^mailto:/i) ||
                   3988: 		($link=~/^\#/)) {
                   3989: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3990: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3991: 	}
                   3992:     }
                   3993: # -------------------------------------------------- Deal with Applet codebases
                   3994:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3995:     return $output;
                   3996: }
                   3997: 
1.112     bowersj2 3998: =pod
                   3999: 
1.648     raeburn  4000: =item * &get_student_view()
1.112     bowersj2 4001: 
                   4002: show a snapshot of what student was looking at
                   4003: 
                   4004: =cut
                   4005: 
1.10      albertel 4006: sub get_student_view {
1.186     albertel 4007:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4008:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4009:   my (%form);
1.10      albertel 4010:   my @elements=('symb','courseid','domain','username');
                   4011:   foreach my $element (@elements) {
1.186     albertel 4012:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4013:   }
1.186     albertel 4014:   if (defined($moreenv)) {
                   4015:       %form=(%form,%{$moreenv});
                   4016:   }
1.236     albertel 4017:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4018:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4019:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4020:   $userview=~s/\<body[^\>]*\>//gi;
                   4021:   $userview=~s/\<\/body\>//gi;
                   4022:   $userview=~s/\<html\>//gi;
                   4023:   $userview=~s/\<\/html\>//gi;
                   4024:   $userview=~s/\<head\>//gi;
                   4025:   $userview=~s/\<\/head\>//gi;
                   4026:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4027:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4028:   if (wantarray) {
                   4029:      return ($userview,$response);
                   4030:   } else {
                   4031:      return $userview;
                   4032:   }
                   4033: }
                   4034: 
                   4035: sub get_student_view_with_retries {
                   4036:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4037: 
                   4038:     my $ok = 0;                 # True if we got a good response.
                   4039:     my $content;
                   4040:     my $response;
                   4041: 
                   4042:     # Try to get the student_view done. within the retries count:
                   4043:     
                   4044:     do {
                   4045:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4046:          $ok      = $response->is_success;
                   4047:          if (!$ok) {
                   4048:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4049:          }
                   4050:          $retries--;
                   4051:     } while (!$ok && ($retries > 0));
                   4052:     
                   4053:     if (!$ok) {
                   4054:        $content = '';          # On error return an empty content.
                   4055:     }
1.651     www      4056:     if (wantarray) {
                   4057:        return ($content, $response);
                   4058:     } else {
                   4059:        return $content;
                   4060:     }
1.11      albertel 4061: }
                   4062: 
1.112     bowersj2 4063: =pod
                   4064: 
1.648     raeburn  4065: =item * &get_student_answers() 
1.112     bowersj2 4066: 
                   4067: show a snapshot of how student was answering problem
                   4068: 
                   4069: =cut
                   4070: 
1.11      albertel 4071: sub get_student_answers {
1.100     sakharuk 4072:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4073:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4074:   my (%moreenv);
1.11      albertel 4075:   my @elements=('symb','courseid','domain','username');
                   4076:   foreach my $element (@elements) {
1.186     albertel 4077:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4078:   }
1.186     albertel 4079:   $moreenv{'grade_target'}='answer';
                   4080:   %moreenv=(%form,%moreenv);
1.497     raeburn  4081:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4082:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4083:   return $userview;
1.1       albertel 4084: }
1.116     albertel 4085: 
                   4086: =pod
                   4087: 
                   4088: =item * &submlink()
                   4089: 
1.242     albertel 4090: Inputs: $text $uname $udom $symb $target
1.116     albertel 4091: 
                   4092: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4093: 
                   4094: =cut
                   4095: 
                   4096: ###############################################
                   4097: sub submlink {
1.242     albertel 4098:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4099:     if (!($uname && $udom)) {
                   4100: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4101: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4102: 	if (!$symb) { $symb=$cursymb; }
                   4103:     }
1.254     matthew  4104:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4105:     $symb=&escape($symb);
1.960     bisitz   4106:     if ($target) { $target=" target=\"$target\""; }
                   4107:     return
                   4108:         '<a href="/adm/grades?command=submission'.
                   4109:         '&amp;symb='.$symb.
                   4110:         '&amp;student='.$uname.
                   4111:         '&amp;userdom='.$udom.'"'.
                   4112:         $target.'>'.$text.'</a>';
1.242     albertel 4113: }
                   4114: ##############################################
                   4115: 
                   4116: =pod
                   4117: 
                   4118: =item * &pgrdlink()
                   4119: 
                   4120: Inputs: $text $uname $udom $symb $target
                   4121: 
                   4122: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4123: 
                   4124: =cut
                   4125: 
                   4126: ###############################################
                   4127: sub pgrdlink {
                   4128:     my $link=&submlink(@_);
                   4129:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4130:     return $link;
                   4131: }
                   4132: ##############################################
                   4133: 
                   4134: =pod
                   4135: 
                   4136: =item * &pprmlink()
                   4137: 
                   4138: Inputs: $text $uname $udom $symb $target
                   4139: 
                   4140: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4141: student and a specific resource
1.242     albertel 4142: 
                   4143: =cut
                   4144: 
                   4145: ###############################################
                   4146: sub pprmlink {
                   4147:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4148:     if (!($uname && $udom)) {
                   4149: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4150: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4151: 	if (!$symb) { $symb=$cursymb; }
                   4152:     }
1.254     matthew  4153:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4154:     $symb=&escape($symb);
1.242     albertel 4155:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4156:     return '<a href="/adm/parmset?command=set&amp;'.
                   4157: 	'symb='.$symb.'&amp;uname='.$uname.
                   4158: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4159: }
                   4160: ##############################################
1.37      matthew  4161: 
1.112     bowersj2 4162: =pod
                   4163: 
                   4164: =back
                   4165: 
                   4166: =cut
                   4167: 
1.37      matthew  4168: ###############################################
1.51      www      4169: 
                   4170: 
                   4171: sub timehash {
1.687     raeburn  4172:     my ($thistime) = @_;
                   4173:     my $timezone = &Apache::lonlocal::gettimezone();
                   4174:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4175:                      ->set_time_zone($timezone);
                   4176:     my $wday = $dt->day_of_week();
                   4177:     if ($wday == 7) { $wday = 0; }
                   4178:     return ( 'second' => $dt->second(),
                   4179:              'minute' => $dt->minute(),
                   4180:              'hour'   => $dt->hour(),
                   4181:              'day'     => $dt->day_of_month(),
                   4182:              'month'   => $dt->month(),
                   4183:              'year'    => $dt->year(),
                   4184:              'weekday' => $wday,
                   4185:              'dayyear' => $dt->day_of_year(),
                   4186:              'dlsav'   => $dt->is_dst() );
1.51      www      4187: }
                   4188: 
1.370     www      4189: sub utc_string {
                   4190:     my ($date)=@_;
1.371     www      4191:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4192: }
                   4193: 
1.51      www      4194: sub maketime {
                   4195:     my %th=@_;
1.687     raeburn  4196:     my ($epoch_time,$timezone,$dt);
                   4197:     $timezone = &Apache::lonlocal::gettimezone();
                   4198:     eval {
                   4199:         $dt = DateTime->new( year   => $th{'year'},
                   4200:                              month  => $th{'month'},
                   4201:                              day    => $th{'day'},
                   4202:                              hour   => $th{'hour'},
                   4203:                              minute => $th{'minute'},
                   4204:                              second => $th{'second'},
                   4205:                              time_zone => $timezone,
                   4206:                          );
                   4207:     };
                   4208:     if (!$@) {
                   4209:         $epoch_time = $dt->epoch;
                   4210:         if ($epoch_time) {
                   4211:             return $epoch_time;
                   4212:         }
                   4213:     }
1.51      www      4214:     return POSIX::mktime(
                   4215:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4216:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4217: }
                   4218: 
                   4219: #########################################
1.51      www      4220: 
                   4221: sub findallcourses {
1.482     raeburn  4222:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4223:     my %roles;
                   4224:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4225:     my %courses;
1.51      www      4226:     my $now=time;
1.482     raeburn  4227:     if (!defined($uname)) {
                   4228:         $uname = $env{'user.name'};
                   4229:     }
                   4230:     if (!defined($udom)) {
                   4231:         $udom = $env{'user.domain'};
                   4232:     }
                   4233:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4234:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4235:         if (!%roles) {
                   4236:             %roles = (
                   4237:                        cc => 1,
1.907     raeburn  4238:                        co => 1,
1.482     raeburn  4239:                        in => 1,
                   4240:                        ep => 1,
                   4241:                        ta => 1,
                   4242:                        cr => 1,
                   4243:                        st => 1,
                   4244:              );
                   4245:         }
                   4246:         foreach my $entry (keys(%roleshash)) {
                   4247:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4248:             if ($trole =~ /^cr/) { 
                   4249:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4250:             } else {
                   4251:                 next if (!exists($roles{$trole}));
                   4252:             }
                   4253:             if ($tend) {
                   4254:                 next if ($tend < $now);
                   4255:             }
                   4256:             if ($tstart) {
                   4257:                 next if ($tstart > $now);
                   4258:             }
1.1058    raeburn  4259:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4260:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4261:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4262:             if ($secpart eq '') {
                   4263:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4264:                 $sec = 'none';
1.1058    raeburn  4265:                 $value .= $cnum.'/';
1.482     raeburn  4266:             } else {
                   4267:                 $cnum = $cnumpart;
                   4268:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4269:                 $value .= $cnum.'/'.$sec;
                   4270:             }
                   4271:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4272:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4273:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4274:                 }
                   4275:             } else {
                   4276:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4277:             }
1.482     raeburn  4278:         }
                   4279:     } else {
                   4280:         foreach my $key (keys(%env)) {
1.483     albertel 4281: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4282:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4283: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4284: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4285: 	        next if (%roles && !exists($roles{$role}));
                   4286: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4287:                 my $active=1;
                   4288:                 if ($starttime) {
                   4289: 		    if ($now<$starttime) { $active=0; }
                   4290:                 }
                   4291:                 if ($endtime) {
                   4292:                     if ($now>$endtime) { $active=0; }
                   4293:                 }
                   4294:                 if ($active) {
1.1058    raeburn  4295:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4296:                     if ($sec eq '') {
                   4297:                         $sec = 'none';
1.1058    raeburn  4298:                     } else {
                   4299:                         $value .= $sec;
                   4300:                     }
                   4301:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4302:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4303:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4304:                         }
                   4305:                     } else {
                   4306:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4307:                     }
1.474     raeburn  4308:                 }
                   4309:             }
1.51      www      4310:         }
                   4311:     }
1.474     raeburn  4312:     return %courses;
1.51      www      4313: }
1.37      matthew  4314: 
1.54      www      4315: ###############################################
1.474     raeburn  4316: 
                   4317: sub blockcheck {
1.1062    raeburn  4318:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4319: 
                   4320:     if (!defined($udom)) {
                   4321:         $udom = $env{'user.domain'};
                   4322:     }
                   4323:     if (!defined($uname)) {
                   4324:         $uname = $env{'user.name'};
                   4325:     }
                   4326: 
                   4327:     # If uname and udom are for a course, check for blocks in the course.
                   4328: 
                   4329:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4330:         my ($startblock,$endblock,$triggerblock) = 
                   4331:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4332:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4333:     }
1.474     raeburn  4334: 
1.502     raeburn  4335:     my $startblock = 0;
                   4336:     my $endblock = 0;
1.1062    raeburn  4337:     my $triggerblock = '';
1.482     raeburn  4338:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4339: 
1.490     raeburn  4340:     # If uname is for a user, and activity is course-specific, i.e.,
                   4341:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4342: 
1.490     raeburn  4343:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4344:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4345:         foreach my $key (keys(%live_courses)) {
                   4346:             if ($key ne $env{'request.course.id'}) {
                   4347:                 delete($live_courses{$key});
                   4348:             }
                   4349:         }
                   4350:     }
                   4351: 
                   4352:     my $otheruser = 0;
                   4353:     my %own_courses;
                   4354:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4355:         # Resource belongs to user other than current user.
                   4356:         $otheruser = 1;
                   4357:         # Gather courses for current user
                   4358:         %own_courses = 
                   4359:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4360:     }
                   4361: 
                   4362:     # Gather active course roles - course coordinator, instructor, 
                   4363:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4364: 
                   4365:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4366:         my ($cdom,$cnum);
                   4367:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4368:             $cdom = $env{'course.'.$course.'.domain'};
                   4369:             $cnum = $env{'course.'.$course.'.num'};
                   4370:         } else {
1.490     raeburn  4371:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4372:         }
                   4373:         my $no_ownblock = 0;
                   4374:         my $no_userblock = 0;
1.533     raeburn  4375:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4376:             # Check if current user has 'evb' priv for this
                   4377:             if (defined($own_courses{$course})) {
                   4378:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4379:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4380:                     if ($sec ne 'none') {
                   4381:                         $checkrole .= '/'.$sec;
                   4382:                     }
                   4383:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4384:                         $no_ownblock = 1;
                   4385:                         last;
                   4386:                     }
                   4387:                 }
                   4388:             }
                   4389:             # if they have 'evb' priv and are currently not playing student
                   4390:             next if (($no_ownblock) &&
                   4391:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4392:         }
1.474     raeburn  4393:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4394:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4395:             if ($sec ne 'none') {
1.482     raeburn  4396:                 $checkrole .= '/'.$sec;
1.474     raeburn  4397:             }
1.490     raeburn  4398:             if ($otheruser) {
                   4399:                 # Resource belongs to user other than current user.
                   4400:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4401:                 my (%allroles,%userroles);
                   4402:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4403:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4404:                         my ($trole,$tdom,$tnum,$tsec);
                   4405:                         if ($entry =~ /^cr/) {
                   4406:                             ($trole,$tdom,$tnum,$tsec) = 
                   4407:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4408:                         } else {
                   4409:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4410:                         }
                   4411:                         my ($spec,$area,$trest);
                   4412:                         $area = '/'.$tdom.'/'.$tnum;
                   4413:                         $trest = $tnum;
                   4414:                         if ($tsec ne '') {
                   4415:                             $area .= '/'.$tsec;
                   4416:                             $trest .= '/'.$tsec;
                   4417:                         }
                   4418:                         $spec = $trole.'.'.$area;
                   4419:                         if ($trole =~ /^cr/) {
                   4420:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4421:                                                               $tdom,$spec,$trest,$area);
                   4422:                         } else {
                   4423:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4424:                                                                 $tdom,$spec,$trest,$area);
                   4425:                         }
                   4426:                     }
                   4427:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4428:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4429:                         if ($1) {
                   4430:                             $no_userblock = 1;
                   4431:                             last;
                   4432:                         }
1.486     raeburn  4433:                     }
                   4434:                 }
1.490     raeburn  4435:             } else {
                   4436:                 # Resource belongs to current user
                   4437:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4438:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4439:                     $no_ownblock = 1;
                   4440:                     last;
                   4441:                 }
1.474     raeburn  4442:             }
                   4443:         }
                   4444:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4445:         next if (($no_ownblock) &&
1.491     albertel 4446:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4447:         next if ($no_userblock);
1.474     raeburn  4448: 
1.866     kalberla 4449:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4450:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4451:         
1.1062    raeburn  4452:         my ($start,$end,$trigger) = 
                   4453:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4454:         if (($start != 0) && 
                   4455:             (($startblock == 0) || ($startblock > $start))) {
                   4456:             $startblock = $start;
1.1062    raeburn  4457:             if ($trigger ne '') {
                   4458:                 $triggerblock = $trigger;
                   4459:             }
1.502     raeburn  4460:         }
                   4461:         if (($end != 0)  &&
                   4462:             (($endblock == 0) || ($endblock < $end))) {
                   4463:             $endblock = $end;
1.1062    raeburn  4464:             if ($trigger ne '') {
                   4465:                 $triggerblock = $trigger;
                   4466:             }
1.502     raeburn  4467:         }
1.490     raeburn  4468:     }
1.1062    raeburn  4469:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4470: }
                   4471: 
                   4472: sub get_blocks {
1.1062    raeburn  4473:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4474:     my $startblock = 0;
                   4475:     my $endblock = 0;
1.1062    raeburn  4476:     my $triggerblock = '';
1.490     raeburn  4477:     my $course = $cdom.'_'.$cnum;
                   4478:     $setters->{$course} = {};
                   4479:     $setters->{$course}{'staff'} = [];
                   4480:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4481:     $setters->{$course}{'triggers'} = [];
                   4482:     my (@blockers,%triggered);
                   4483:     my $now = time;
                   4484:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4485:     if ($activity eq 'docs') {
                   4486:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4487:         foreach my $block (@blockers) {
                   4488:             if ($block =~ /^firstaccess____(.+)$/) {
                   4489:                 my $item = $1;
                   4490:                 my $type = 'map';
                   4491:                 my $timersymb = $item;
                   4492:                 if ($item eq 'course') {
                   4493:                     $type = 'course';
                   4494:                 } elsif ($item =~ /___\d+___/) {
                   4495:                     $type = 'resource';
                   4496:                 } else {
                   4497:                     $timersymb = &Apache::lonnet::symbread($item);
                   4498:                 }
                   4499:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4500:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4501:                 $triggered{$block} = {
                   4502:                                        start => $start,
                   4503:                                        end   => $end,
                   4504:                                        type  => $type,
                   4505:                                      };
                   4506:             }
                   4507:         }
                   4508:     } else {
                   4509:         foreach my $block (keys(%commblocks)) {
                   4510:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4511:                 my ($start,$end) = ($1,$2);
                   4512:                 if ($start <= time && $end >= time) {
                   4513:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4514:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4515:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4516:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4517:                                     push(@blockers,$block);
                   4518:                                 }
                   4519:                             }
                   4520:                         }
                   4521:                     }
                   4522:                 }
                   4523:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4524:                 my $item = $1;
                   4525:                 my $timersymb = $item; 
                   4526:                 my $type = 'map';
                   4527:                 if ($item eq 'course') {
                   4528:                     $type = 'course';
                   4529:                 } elsif ($item =~ /___\d+___/) {
                   4530:                     $type = 'resource';
                   4531:                 } else {
                   4532:                     $timersymb = &Apache::lonnet::symbread($item);
                   4533:                 }
                   4534:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4535:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4536:                 if ($start && $end) {
                   4537:                     if (($start <= time) && ($end >= time)) {
                   4538:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4539:                             push(@blockers,$block);
                   4540:                             $triggered{$block} = {
                   4541:                                                    start => $start,
                   4542:                                                    end   => $end,
                   4543:                                                    type  => $type,
                   4544:                                                  };
                   4545:                         }
                   4546:                     }
1.490     raeburn  4547:                 }
1.1062    raeburn  4548:             }
                   4549:         }
                   4550:     }
                   4551:     foreach my $blocker (@blockers) {
                   4552:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4553:             &parse_block_record($commblocks{$blocker});
                   4554:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4555:         my ($start,$end,$triggertype);
                   4556:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4557:             ($start,$end) = ($1,$2);
                   4558:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4559:             $start = $triggered{$blocker}{'start'};
                   4560:             $end = $triggered{$blocker}{'end'};
                   4561:             $triggertype = $triggered{$blocker}{'type'};
                   4562:         }
                   4563:         if ($start) {
                   4564:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4565:             if ($triggertype) {
                   4566:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4567:             } else {
                   4568:                 push(@{$$setters{$course}{'triggers'}},0);
                   4569:             }
                   4570:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4571:                 $startblock = $start;
                   4572:                 if ($triggertype) {
                   4573:                     $triggerblock = $blocker;
1.474     raeburn  4574:                 }
                   4575:             }
1.1062    raeburn  4576:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4577:                $endblock = $end;
                   4578:                if ($triggertype) {
                   4579:                    $triggerblock = $blocker;
                   4580:                }
                   4581:             }
1.474     raeburn  4582:         }
                   4583:     }
1.1062    raeburn  4584:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4585: }
                   4586: 
                   4587: sub parse_block_record {
                   4588:     my ($record) = @_;
                   4589:     my ($setuname,$setudom,$title,$blocks);
                   4590:     if (ref($record) eq 'HASH') {
                   4591:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4592:         $title = &unescape($record->{'event'});
                   4593:         $blocks = $record->{'blocks'};
                   4594:     } else {
                   4595:         my @data = split(/:/,$record,3);
                   4596:         if (scalar(@data) eq 2) {
                   4597:             $title = $data[1];
                   4598:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4599:         } else {
                   4600:             ($setuname,$setudom,$title) = @data;
                   4601:         }
                   4602:         $blocks = { 'com' => 'on' };
                   4603:     }
                   4604:     return ($setuname,$setudom,$title,$blocks);
                   4605: }
                   4606: 
1.854     kalberla 4607: sub blocking_status {
1.1062    raeburn  4608:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4609:     my %setters;
1.890     droeschl 4610: 
1.1061    raeburn  4611: # check for active blocking
1.1062    raeburn  4612:     my ($startblock,$endblock,$triggerblock) = 
                   4613:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4614:     my $blocked = 0;
                   4615:     if ($startblock && $endblock) {
                   4616:         $blocked = 1;
                   4617:     }
1.890     droeschl 4618: 
1.1061    raeburn  4619: # caller just wants to know whether a block is active
                   4620:     if (!wantarray) { return $blocked; }
                   4621: 
                   4622: # build a link to a popup window containing the details
                   4623:     my $querystring  = "?activity=$activity";
                   4624: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4625:     if ($activity eq 'port') {
                   4626:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4627:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4628:     } elsif ($activity eq 'docs') {
                   4629:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4630:     }
1.1061    raeburn  4631: 
                   4632:     my $output .= <<'END_MYBLOCK';
                   4633: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4634:     var options = "width=" + w + ",height=" + h + ",";
                   4635:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4636:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4637:     var newWin = window.open(url, wdwName, options);
                   4638:     newWin.focus();
                   4639: }
1.890     droeschl 4640: END_MYBLOCK
1.854     kalberla 4641: 
1.1061    raeburn  4642:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4643:   
1.1061    raeburn  4644:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4645:     my $text = &mt('Communication Blocked');
                   4646:     if ($activity eq 'docs') {
                   4647:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4648:     } elsif ($activity eq 'printout') {
                   4649:         $text = &mt('Printing Blocked');
1.1062    raeburn  4650:     }
1.1061    raeburn  4651:     $output .= <<"END_BLOCK";
1.867     kalberla 4652: <div class='LC_comblock'>
1.869     kalberla 4653:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4654:   title='$text'>
                   4655:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4656:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4657:   title='$text'>$text</a>
1.867     kalberla 4658: </div>
                   4659: 
                   4660: END_BLOCK
1.474     raeburn  4661: 
1.1061    raeburn  4662:     return ($blocked, $output);
1.854     kalberla 4663: }
1.490     raeburn  4664: 
1.60      matthew  4665: ###############################################
                   4666: 
1.682     raeburn  4667: sub check_ip_acc {
                   4668:     my ($acc)=@_;
                   4669:     &Apache::lonxml::debug("acc is $acc");
                   4670:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4671:         return 1;
                   4672:     }
                   4673:     my $allowed=0;
                   4674:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4675: 
                   4676:     my $name;
                   4677:     foreach my $pattern (split(',',$acc)) {
                   4678:         $pattern =~ s/^\s*//;
                   4679:         $pattern =~ s/\s*$//;
                   4680:         if ($pattern =~ /\*$/) {
                   4681:             #35.8.*
                   4682:             $pattern=~s/\*//;
                   4683:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4684:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4685:             #35.8.3.[34-56]
                   4686:             my $low=$2;
                   4687:             my $high=$3;
                   4688:             $pattern=$1;
                   4689:             if ($ip =~ /^\Q$pattern\E/) {
                   4690:                 my $last=(split(/\./,$ip))[3];
                   4691:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4692:             }
                   4693:         } elsif ($pattern =~ /^\*/) {
                   4694:             #*.msu.edu
                   4695:             $pattern=~s/\*//;
                   4696:             if (!defined($name)) {
                   4697:                 use Socket;
                   4698:                 my $netaddr=inet_aton($ip);
                   4699:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4700:             }
                   4701:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4702:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4703:             #127.0.0.1
                   4704:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4705:         } else {
                   4706:             #some.name.com
                   4707:             if (!defined($name)) {
                   4708:                 use Socket;
                   4709:                 my $netaddr=inet_aton($ip);
                   4710:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4711:             }
                   4712:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4713:         }
                   4714:         if ($allowed) { last; }
                   4715:     }
                   4716:     return $allowed;
                   4717: }
                   4718: 
                   4719: ###############################################
                   4720: 
1.60      matthew  4721: =pod
                   4722: 
1.112     bowersj2 4723: =head1 Domain Template Functions
                   4724: 
                   4725: =over 4
                   4726: 
                   4727: =item * &determinedomain()
1.60      matthew  4728: 
                   4729: Inputs: $domain (usually will be undef)
                   4730: 
1.63      www      4731: Returns: Determines which domain should be used for designs
1.60      matthew  4732: 
                   4733: =cut
1.54      www      4734: 
1.60      matthew  4735: ###############################################
1.63      www      4736: sub determinedomain {
                   4737:     my $domain=shift;
1.531     albertel 4738:     if (! $domain) {
1.60      matthew  4739:         # Determine domain if we have not been given one
1.893     raeburn  4740:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4741:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4742:         if ($env{'request.role.domain'}) { 
                   4743:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4744:         }
                   4745:     }
1.63      www      4746:     return $domain;
                   4747: }
                   4748: ###############################################
1.517     raeburn  4749: 
1.518     albertel 4750: sub devalidate_domconfig_cache {
                   4751:     my ($udom)=@_;
                   4752:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4753: }
                   4754: 
                   4755: # ---------------------- Get domain configuration for a domain
                   4756: sub get_domainconf {
                   4757:     my ($udom) = @_;
                   4758:     my $cachetime=1800;
                   4759:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4760:     if (defined($cached)) { return %{$result}; }
                   4761: 
                   4762:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4763: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4764:     my (%designhash,%legacy);
1.518     albertel 4765:     if (keys(%domconfig) > 0) {
                   4766:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4767:             if (keys(%{$domconfig{'login'}})) {
                   4768:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4769:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4770:                         if ($key eq 'loginvia') {
                   4771:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4772:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4773:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4774:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4775:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4776:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4777:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4778: 
                   4779:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4780:                                             } else {
1.1013    raeburn  4781:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4782:                                             }
                   4783:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4784:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4785:                                             }
1.946     raeburn  4786:                                         }
                   4787:                                     }
                   4788:                                 }
                   4789:                             }
                   4790:                         } else {
                   4791:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4792:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4793:                                     $domconfig{'login'}{$key}{$img};
                   4794:                             }
1.699     raeburn  4795:                         }
                   4796:                     } else {
                   4797:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4798:                     }
1.632     raeburn  4799:                 }
                   4800:             } else {
                   4801:                 $legacy{'login'} = 1;
1.518     albertel 4802:             }
1.632     raeburn  4803:         } else {
                   4804:             $legacy{'login'} = 1;
1.518     albertel 4805:         }
                   4806:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4807:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4808:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4809:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4810:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4811:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4812:                         }
1.518     albertel 4813:                     }
                   4814:                 }
1.632     raeburn  4815:             } else {
                   4816:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4817:             }
1.632     raeburn  4818:         } else {
                   4819:             $legacy{'rolecolors'} = 1;
1.518     albertel 4820:         }
1.948     raeburn  4821:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4822:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4823:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4824:             }
                   4825:         }
1.632     raeburn  4826:         if (keys(%legacy) > 0) {
                   4827:             my %legacyhash = &get_legacy_domconf($udom);
                   4828:             foreach my $item (keys(%legacyhash)) {
                   4829:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4830:                     if ($legacy{'login'}) { 
                   4831:                         $designhash{$item} = $legacyhash{$item};
                   4832:                     }
                   4833:                 } else {
                   4834:                     if ($legacy{'rolecolors'}) {
                   4835:                         $designhash{$item} = $legacyhash{$item};
                   4836:                     }
1.518     albertel 4837:                 }
                   4838:             }
                   4839:         }
1.632     raeburn  4840:     } else {
                   4841:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4842:     }
                   4843:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4844: 				  $cachetime);
                   4845:     return %designhash;
                   4846: }
                   4847: 
1.632     raeburn  4848: sub get_legacy_domconf {
                   4849:     my ($udom) = @_;
                   4850:     my %legacyhash;
                   4851:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4852:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4853:     if (-e $designfile) {
                   4854:         if ( open (my $fh,"<$designfile") ) {
                   4855:             while (my $line = <$fh>) {
                   4856:                 next if ($line =~ /^\#/);
                   4857:                 chomp($line);
                   4858:                 my ($key,$val)=(split(/\=/,$line));
                   4859:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4860:             }
                   4861:             close($fh);
                   4862:         }
                   4863:     }
1.1026    raeburn  4864:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4865:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4866:     }
                   4867:     return %legacyhash;
                   4868: }
                   4869: 
1.63      www      4870: =pod
                   4871: 
1.112     bowersj2 4872: =item * &domainlogo()
1.63      www      4873: 
                   4874: Inputs: $domain (usually will be undef)
                   4875: 
                   4876: Returns: A link to a domain logo, if the domain logo exists.
                   4877: If the domain logo does not exist, a description of the domain.
                   4878: 
                   4879: =cut
1.112     bowersj2 4880: 
1.63      www      4881: ###############################################
                   4882: sub domainlogo {
1.517     raeburn  4883:     my $domain = &determinedomain(shift);
1.518     albertel 4884:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4885:     # See if there is a logo
                   4886:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4887:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4888:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4889: 	    if ($imgsrc =~ m{^/res/}) {
                   4890: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4891: 		&Apache::lonnet::repcopy($local_name);
                   4892: 	    }
                   4893: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4894:         } 
                   4895:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4896:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4897:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4898:     } else {
1.60      matthew  4899:         return '';
1.59      www      4900:     }
                   4901: }
1.63      www      4902: ##############################################
                   4903: 
                   4904: =pod
                   4905: 
1.112     bowersj2 4906: =item * &designparm()
1.63      www      4907: 
                   4908: Inputs: $which parameter; $domain (usually will be undef)
                   4909: 
                   4910: Returns: value of designparamter $which
                   4911: 
                   4912: =cut
1.112     bowersj2 4913: 
1.397     albertel 4914: 
1.400     albertel 4915: ##############################################
1.397     albertel 4916: sub designparm {
                   4917:     my ($which,$domain)=@_;
                   4918:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4919:         return $env{'environment.color.'.$which};
1.96      www      4920:     }
1.63      www      4921:     $domain=&determinedomain($domain);
1.1016    raeburn  4922:     my %domdesign;
                   4923:     unless ($domain eq 'public') {
                   4924:         %domdesign = &get_domainconf($domain);
                   4925:     }
1.520     raeburn  4926:     my $output;
1.517     raeburn  4927:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4928:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4929:     } else {
1.520     raeburn  4930:         $output = $defaultdesign{$which};
                   4931:     }
                   4932:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4933:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4934:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4935:             if ($output =~ m{^/res/}) {
                   4936:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4937:                 &Apache::lonnet::repcopy($local_name);
                   4938:             }
1.520     raeburn  4939:             $output = &lonhttpdurl($output);
                   4940:         }
1.63      www      4941:     }
1.520     raeburn  4942:     return $output;
1.63      www      4943: }
1.59      www      4944: 
1.822     bisitz   4945: ##############################################
                   4946: =pod
                   4947: 
1.832     bisitz   4948: =item * &authorspace()
                   4949: 
1.1028    raeburn  4950: Inputs: $url (usually will be undef).
1.832     bisitz   4951: 
1.1132    raeburn  4952: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  4953:          directory being viewed (or for which action is being taken). 
                   4954:          If $url is provided, and begins /priv/<domain>/<uname>
                   4955:          the path will be that portion of the $context argument.
                   4956:          Otherwise the path will be for the author space of the current
                   4957:          user when the current role is author, or for that of the 
                   4958:          co-author/assistant co-author space when the current role 
                   4959:          is co-author or assistant co-author.
1.832     bisitz   4960: 
                   4961: =cut
                   4962: 
                   4963: sub authorspace {
1.1028    raeburn  4964:     my ($url) = @_;
                   4965:     if ($url ne '') {
                   4966:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4967:            return $1;
                   4968:         }
                   4969:     }
1.832     bisitz   4970:     my $caname = '';
1.1024    www      4971:     my $cadom = '';
1.1028    raeburn  4972:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4973:         ($cadom,$caname) =
1.832     bisitz   4974:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4975:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4976:         $caname = $env{'user.name'};
1.1024    www      4977:         $cadom = $env{'user.domain'};
1.832     bisitz   4978:     }
1.1028    raeburn  4979:     if (($caname ne '') && ($cadom ne '')) {
                   4980:         return "/priv/$cadom/$caname/";
                   4981:     }
                   4982:     return;
1.832     bisitz   4983: }
                   4984: 
                   4985: ##############################################
                   4986: =pod
                   4987: 
1.822     bisitz   4988: =item * &head_subbox()
                   4989: 
                   4990: Inputs: $content (contains HTML code with page functions, etc.)
                   4991: 
                   4992: Returns: HTML div with $content
                   4993:          To be included in page header
                   4994: 
                   4995: =cut
                   4996: 
                   4997: sub head_subbox {
                   4998:     my ($content)=@_;
                   4999:     my $output =
1.993     raeburn  5000:         '<div class="LC_head_subbox">'
1.822     bisitz   5001:        .$content
                   5002:        .'</div>'
                   5003: }
                   5004: 
                   5005: ##############################################
                   5006: =pod
                   5007: 
                   5008: =item * &CSTR_pageheader()
                   5009: 
1.1026    raeburn  5010: Input: (optional) filename from which breadcrumb trail is built.
                   5011:        In most cases no input as needed, as $env{'request.filename'}
                   5012:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5013: 
                   5014: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5015:          To be included on Authoring Space pages
1.822     bisitz   5016: 
                   5017: =cut
                   5018: 
                   5019: sub CSTR_pageheader {
1.1026    raeburn  5020:     my ($trailfile) = @_;
                   5021:     if ($trailfile eq '') {
                   5022:         $trailfile = $env{'request.filename'};
                   5023:     }
                   5024: 
                   5025: # this is for resources; directories have customtitle, and crumbs
                   5026: # and select recent are created in lonpubdir.pm
                   5027: 
                   5028:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5029:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5030:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5031:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5032:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5033: 
                   5034:     my $parentpath = '';
                   5035:     my $lastitem = '';
                   5036:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5037:         $parentpath = $1;
                   5038:         $lastitem = $2;
                   5039:     } else {
                   5040:         $lastitem = $thisdisfn;
                   5041:     }
1.921     bisitz   5042: 
                   5043:     my $output =
1.822     bisitz   5044:          '<div>'
                   5045:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1132    raeburn  5046:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5047:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5048:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5049:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5050: 
                   5051:     if ($lastitem) {
                   5052:         $output .=
                   5053:              '<span class="LC_filename">'
                   5054:             .$lastitem
                   5055:             .'</span>';
                   5056:     }
                   5057:     $output .=
                   5058:          '<br />'
1.822     bisitz   5059:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5060:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5061:         .'</form>'
                   5062:         .&Apache::lonmenu::constspaceform()
                   5063:         .'</div>';
1.921     bisitz   5064: 
                   5065:     return $output;
1.822     bisitz   5066: }
                   5067: 
1.60      matthew  5068: ###############################################
                   5069: ###############################################
                   5070: 
                   5071: =pod
                   5072: 
1.112     bowersj2 5073: =back
                   5074: 
1.549     albertel 5075: =head1 HTML Helpers
1.112     bowersj2 5076: 
                   5077: =over 4
                   5078: 
                   5079: =item * &bodytag()
1.60      matthew  5080: 
                   5081: Returns a uniform header for LON-CAPA web pages.
                   5082: 
                   5083: Inputs: 
                   5084: 
1.112     bowersj2 5085: =over 4
                   5086: 
                   5087: =item * $title, A title to be displayed on the page.
                   5088: 
                   5089: =item * $function, the current role (can be undef).
                   5090: 
                   5091: =item * $addentries, extra parameters for the <body> tag.
                   5092: 
                   5093: =item * $bodyonly, if defined, only return the <body> tag.
                   5094: 
                   5095: =item * $domain, if defined, force a given domain.
                   5096: 
                   5097: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5098:             text interface only)
1.60      matthew  5099: 
1.814     bisitz   5100: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5101:                      navigational links
1.317     albertel 5102: 
1.338     albertel 5103: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5104: 
1.460     albertel 5105: =item * $args, optional argument valid values are
                   5106:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5107:             inherit_jsmath -> when creating popup window in a page,
                   5108:                               should it have jsmath forced on by the
                   5109:                               current page
1.460     albertel 5110: 
1.1096    raeburn  5111: =item * $advtoolsref, optional argument, ref to an array containing
                   5112:             inlineremote items to be added in "Functions" menu below
                   5113:             breadcrumbs.
                   5114: 
1.112     bowersj2 5115: =back
                   5116: 
1.60      matthew  5117: Returns: A uniform header for LON-CAPA web pages.  
                   5118: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5119: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5120: other decorations will be returned.
                   5121: 
                   5122: =cut
                   5123: 
1.54      www      5124: sub bodytag {
1.831     bisitz   5125:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5126:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5127: 
1.954     raeburn  5128:     my $public;
                   5129:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5130:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5131:         $public = 1;
                   5132:     }
1.460     albertel 5133:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5134:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5135: 
1.183     matthew  5136:     $function = &get_users_function() if (!$function);
1.339     albertel 5137:     my $img =    &designparm($function.'.img',$domain);
                   5138:     my $font =   &designparm($function.'.font',$domain);
                   5139:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5140: 
1.803     bisitz   5141:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5142: 		   'bgcolor' => $pgbg,
1.339     albertel 5143: 		   'text'    => $font,
                   5144:                    'alink'   => &designparm($function.'.alink',$domain),
                   5145: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5146: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5147:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5148: 
1.63      www      5149:  # role and realm
1.378     raeburn  5150:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5151:     if ($role  eq 'ca') {
1.479     albertel 5152:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5153:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5154:     } 
1.55      www      5155: # realm
1.258     albertel 5156:     if ($env{'request.course.id'}) {
1.378     raeburn  5157:         if ($env{'request.role'} !~ /^cr/) {
                   5158:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5159:         }
1.898     raeburn  5160:         if ($env{'request.course.sec'}) {
                   5161:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5162:         }   
1.359     albertel 5163: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5164:     } else {
                   5165:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5166:     }
1.433     albertel 5167: 
1.359     albertel 5168:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5169: 
1.438     albertel 5170:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5171: 
1.101     www      5172: # construct main body tag
1.359     albertel 5173:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5174: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5175: 
1.1131    raeburn  5176:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5177: 
1.1130    raeburn  5178:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5179:         return $bodytag;
1.1130    raeburn  5180:     }
1.359     albertel 5181: 
1.954     raeburn  5182:     if ($public) {
1.433     albertel 5183: 	undef($role);
                   5184:     }
1.359     albertel 5185:     
1.762     bisitz   5186:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5187:     #
                   5188:     # Extra info if you are the DC
                   5189:     my $dc_info = '';
                   5190:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5191:                         $env{'course.'.$env{'request.course.id'}.
                   5192:                                  '.domain'}.'/'})) {
                   5193:         my $cid = $env{'request.course.id'};
1.917     raeburn  5194:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5195:         $dc_info =~ s/\s+$//;
1.359     albertel 5196:     }
                   5197: 
1.898     raeburn  5198:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5199: 
1.903     droeschl 5200:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5201: 
                   5202:         #    if ($env{'request.state'} eq 'construct') {
                   5203:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5204:         #    }
                   5205: 
1.1130    raeburn  5206:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5207:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5208: 
1.1130    raeburn  5209:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.359     albertel 5210: 
1.916     droeschl 5211:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5212:              if ($dc_info) {
                   5213:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5214:              }
1.1130    raeburn  5215:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5216:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5217:             return $bodytag;
                   5218:         }
1.894     droeschl 5219: 
1.927     raeburn  5220:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5221:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5222:         }
1.916     droeschl 5223: 
1.1130    raeburn  5224:         $bodytag .= $right;
1.852     droeschl 5225: 
1.917     raeburn  5226:         if ($dc_info) {
                   5227:             $dc_info = &dc_courseid_toggle($dc_info);
                   5228:         }
                   5229:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5230: 
1.1169    raeburn  5231:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5232:         if ($args->{'no_secondary_menu'}) {
                   5233:             return $bodytag;
                   5234:         }
1.1169    raeburn  5235:         #don't show menus for public users
1.954     raeburn  5236:         if (!$public){
1.1154    raeburn  5237:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5238:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5239:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5240:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5241:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5242:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5243:             } elsif ($forcereg) {
                   5244:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5245:                                                             $args->{'group'});
                   5246:             } else {
                   5247:                 $bodytag .= 
                   5248:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5249:                                                         $forcereg,$args->{'group'},
                   5250:                                                         $args->{'bread_crumbs'},
                   5251:                                                         $advtoolsref);
1.920     raeburn  5252:             }
1.903     droeschl 5253:         }else{
                   5254:             # this is to seperate menu from content when there's no secondary
                   5255:             # menu. Especially needed for public accessible ressources.
                   5256:             $bodytag .= '<hr style="clear:both" />';
                   5257:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5258:         }
1.903     droeschl 5259: 
1.235     raeburn  5260:         return $bodytag;
1.182     matthew  5261: }
                   5262: 
1.917     raeburn  5263: sub dc_courseid_toggle {
                   5264:     my ($dc_info) = @_;
1.980     raeburn  5265:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5266:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5267:            &mt('(More ...)').'</a></span>'.
                   5268:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5269: }
                   5270: 
1.330     albertel 5271: sub make_attr_string {
                   5272:     my ($register,$attr_ref) = @_;
                   5273: 
                   5274:     if ($attr_ref && !ref($attr_ref)) {
                   5275: 	die("addentries Must be a hash ref ".
                   5276: 	    join(':',caller(1))." ".
                   5277: 	    join(':',caller(0))." ");
                   5278:     }
                   5279: 
                   5280:     if ($register) {
1.339     albertel 5281: 	my ($on_load,$on_unload);
                   5282: 	foreach my $key (keys(%{$attr_ref})) {
                   5283: 	    if      (lc($key) eq 'onload') {
                   5284: 		$on_load.=$attr_ref->{$key}.';';
                   5285: 		delete($attr_ref->{$key});
                   5286: 
                   5287: 	    } elsif (lc($key) eq 'onunload') {
                   5288: 		$on_unload.=$attr_ref->{$key}.';';
                   5289: 		delete($attr_ref->{$key});
                   5290: 	    }
                   5291: 	}
1.953     droeschl 5292: 	$attr_ref->{'onload'}  = $on_load;
                   5293: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5294:     }
1.339     albertel 5295: 
1.330     albertel 5296:     my $attr_string;
1.1159    raeburn  5297:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5298: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5299:     }
                   5300:     return $attr_string;
                   5301: }
                   5302: 
                   5303: 
1.182     matthew  5304: ###############################################
1.251     albertel 5305: ###############################################
                   5306: 
                   5307: =pod
                   5308: 
                   5309: =item * &endbodytag()
                   5310: 
                   5311: Returns a uniform footer for LON-CAPA web pages.
                   5312: 
1.635     raeburn  5313: Inputs: 1 - optional reference to an args hash
                   5314: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5315: a 'Continue' link is not displayed if the page contains an
                   5316: internal redirect in the <head></head> section,
                   5317: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5318: 
                   5319: =cut
                   5320: 
                   5321: sub endbodytag {
1.635     raeburn  5322:     my ($args) = @_;
1.1080    raeburn  5323:     my $endbodytag;
                   5324:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5325:         $endbodytag='</body>';
                   5326:     }
1.269     albertel 5327:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5328:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5329:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5330: 	    $endbodytag=
                   5331: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5332: 	        &mt('Continue').'</a>'.
                   5333: 	        $endbodytag;
                   5334:         }
1.315     albertel 5335:     }
1.251     albertel 5336:     return $endbodytag;
                   5337: }
                   5338: 
1.352     albertel 5339: =pod
                   5340: 
                   5341: =item * &standard_css()
                   5342: 
                   5343: Returns a style sheet
                   5344: 
                   5345: Inputs: (all optional)
                   5346:             domain         -> force to color decorate a page for a specific
                   5347:                                domain
                   5348:             function       -> force usage of a specific rolish color scheme
                   5349:             bgcolor        -> override the default page bgcolor
                   5350: 
                   5351: =cut
                   5352: 
1.343     albertel 5353: sub standard_css {
1.345     albertel 5354:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5355:     $function  = &get_users_function() if (!$function);
                   5356:     my $img    = &designparm($function.'.img',   $domain);
                   5357:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5358:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5359:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5360: #second colour for later usage
1.345     albertel 5361:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5362:     my $pgbg_or_bgcolor =
                   5363: 	         $bgcolor ||
1.352     albertel 5364: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5365:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5366:     my $alink  = &designparm($function.'.alink', $domain);
                   5367:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5368:     my $link   = &designparm($function.'.link',  $domain);
                   5369: 
1.602     albertel 5370:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5371:     my $mono                 = 'monospace';
1.850     bisitz   5372:     my $data_table_head      = $sidebg;
                   5373:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5374:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5375:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5376:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5377:     my $mail_new             = '#FFBB77';
                   5378:     my $mail_new_hover       = '#DD9955';
                   5379:     my $mail_read            = '#BBBB77';
                   5380:     my $mail_read_hover      = '#999944';
                   5381:     my $mail_replied         = '#AAAA88';
                   5382:     my $mail_replied_hover   = '#888855';
                   5383:     my $mail_other           = '#99BBBB';
                   5384:     my $mail_other_hover     = '#669999';
1.391     albertel 5385:     my $table_header         = '#DDDDDD';
1.489     raeburn  5386:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5387:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5388:     my $button_hover         = '#BF2317';
1.392     albertel 5389: 
1.608     albertel 5390:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5391:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5392:                                              : '0 3px 0 4px';
1.448     albertel 5393: 
1.523     albertel 5394: 
1.343     albertel 5395:     return <<END;
1.947     droeschl 5396: 
                   5397: /* needed for iframe to allow 100% height in FF */
                   5398: body, html { 
                   5399:     margin: 0;
                   5400:     padding: 0 0.5%;
                   5401:     height: 99%; /* to avoid scrollbars */
                   5402: }
                   5403: 
1.795     www      5404: body {
1.911     bisitz   5405:   font-family: $sans;
                   5406:   line-height:130%;
                   5407:   font-size:0.83em;
                   5408:   color:$font;
1.795     www      5409: }
                   5410: 
1.959     onken    5411: a:focus,
                   5412: a:focus img {
1.795     www      5413:   color: red;
                   5414: }
1.698     harmsja  5415: 
1.911     bisitz   5416: form, .inline {
                   5417:   display: inline;
1.795     www      5418: }
1.721     harmsja  5419: 
1.795     www      5420: .LC_right {
1.911     bisitz   5421:   text-align:right;
1.795     www      5422: }
                   5423: 
                   5424: .LC_middle {
1.911     bisitz   5425:   vertical-align:middle;
1.795     www      5426: }
1.721     harmsja  5427: 
1.1130    raeburn  5428: .LC_floatleft {
                   5429:   float: left;
                   5430: }
                   5431: 
                   5432: .LC_floatright {
                   5433:   float: right;
                   5434: }
                   5435: 
1.911     bisitz   5436: .LC_400Box {
                   5437:   width:400px;
                   5438: }
1.721     harmsja  5439: 
1.947     droeschl 5440: .LC_iframecontainer {
                   5441:     width: 98%;
                   5442:     margin: 0;
                   5443:     position: fixed;
                   5444:     top: 8.5em;
                   5445:     bottom: 0;
                   5446: }
                   5447: 
                   5448: .LC_iframecontainer iframe{
                   5449:     border: none;
                   5450:     width: 100%;
                   5451:     height: 100%;
                   5452: }
                   5453: 
1.778     bisitz   5454: .LC_filename {
                   5455:   font-family: $mono;
                   5456:   white-space:pre;
1.921     bisitz   5457:   font-size: 120%;
1.778     bisitz   5458: }
                   5459: 
                   5460: .LC_fileicon {
                   5461:   border: none;
                   5462:   height: 1.3em;
                   5463:   vertical-align: text-bottom;
                   5464:   margin-right: 0.3em;
                   5465:   text-decoration:none;
                   5466: }
                   5467: 
1.1008    www      5468: .LC_setting {
                   5469:   text-decoration:underline;
                   5470: }
                   5471: 
1.350     albertel 5472: .LC_error {
                   5473:   color: red;
                   5474: }
1.795     www      5475: 
1.1097    bisitz   5476: .LC_warning {
                   5477:   color: darkorange;
                   5478: }
                   5479: 
1.457     albertel 5480: .LC_diff_removed {
1.733     bisitz   5481:   color: red;
1.394     albertel 5482: }
1.532     albertel 5483: 
                   5484: .LC_info,
1.457     albertel 5485: .LC_success,
                   5486: .LC_diff_added {
1.350     albertel 5487:   color: green;
                   5488: }
1.795     www      5489: 
1.802     bisitz   5490: div.LC_confirm_box {
                   5491:   background-color: #FAFAFA;
                   5492:   border: 1px solid $lg_border_color;
                   5493:   margin-right: 0;
                   5494:   padding: 5px;
                   5495: }
                   5496: 
                   5497: div.LC_confirm_box .LC_error img,
                   5498: div.LC_confirm_box .LC_success img {
                   5499:   vertical-align: middle;
                   5500: }
                   5501: 
1.440     albertel 5502: .LC_icon {
1.771     droeschl 5503:   border: none;
1.790     droeschl 5504:   vertical-align: middle;
1.771     droeschl 5505: }
                   5506: 
1.543     albertel 5507: .LC_docs_spacer {
                   5508:   width: 25px;
                   5509:   height: 1px;
1.771     droeschl 5510:   border: none;
1.543     albertel 5511: }
1.346     albertel 5512: 
1.532     albertel 5513: .LC_internal_info {
1.735     bisitz   5514:   color: #999999;
1.532     albertel 5515: }
                   5516: 
1.794     www      5517: .LC_discussion {
1.1050    www      5518:   background: $data_table_dark;
1.911     bisitz   5519:   border: 1px solid black;
                   5520:   margin: 2px;
1.794     www      5521: }
                   5522: 
                   5523: .LC_disc_action_left {
1.1050    www      5524:   background: $sidebg;
1.911     bisitz   5525:   text-align: left;
1.1050    www      5526:   padding: 4px;
                   5527:   margin: 2px;
1.794     www      5528: }
                   5529: 
                   5530: .LC_disc_action_right {
1.1050    www      5531:   background: $sidebg;
1.911     bisitz   5532:   text-align: right;
1.1050    www      5533:   padding: 4px;
                   5534:   margin: 2px;
1.794     www      5535: }
                   5536: 
                   5537: .LC_disc_new_item {
1.911     bisitz   5538:   background: white;
                   5539:   border: 2px solid red;
1.1050    www      5540:   margin: 4px;
                   5541:   padding: 4px;
1.794     www      5542: }
                   5543: 
                   5544: .LC_disc_old_item {
1.911     bisitz   5545:   background: white;
1.1050    www      5546:   margin: 4px;
                   5547:   padding: 4px;
1.794     www      5548: }
                   5549: 
1.458     albertel 5550: table.LC_pastsubmission {
                   5551:   border: 1px solid black;
                   5552:   margin: 2px;
                   5553: }
                   5554: 
1.924     bisitz   5555: table#LC_menubuttons {
1.345     albertel 5556:   width: 100%;
                   5557:   background: $pgbg;
1.392     albertel 5558:   border: 2px;
1.402     albertel 5559:   border-collapse: separate;
1.803     bisitz   5560:   padding: 0;
1.345     albertel 5561: }
1.392     albertel 5562: 
1.801     tempelho 5563: table#LC_title_bar a {
                   5564:   color: $fontmenu;
                   5565: }
1.836     bisitz   5566: 
1.807     droeschl 5567: table#LC_title_bar {
1.819     tempelho 5568:   clear: both;
1.836     bisitz   5569:   display: none;
1.807     droeschl 5570: }
                   5571: 
1.795     www      5572: table#LC_title_bar,
1.933     droeschl 5573: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5574: table#LC_title_bar.LC_with_remote {
1.359     albertel 5575:   width: 100%;
1.392     albertel 5576:   border-color: $pgbg;
                   5577:   border-style: solid;
                   5578:   border-width: $border;
1.379     albertel 5579:   background: $pgbg;
1.801     tempelho 5580:   color: $fontmenu;
1.392     albertel 5581:   border-collapse: collapse;
1.803     bisitz   5582:   padding: 0;
1.819     tempelho 5583:   margin: 0;
1.359     albertel 5584: }
1.795     www      5585: 
1.933     droeschl 5586: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5587:     margin: 0;
                   5588:     padding: 0;
1.933     droeschl 5589:     position: relative;
                   5590:     list-style: none;
1.913     droeschl 5591: }
1.933     droeschl 5592: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5593:     display: inline;
                   5594: }
1.933     droeschl 5595: 
                   5596: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5597:     padding: 0;
1.933     droeschl 5598:     margin: 0;
                   5599:     float: left;
1.913     droeschl 5600: }
1.933     droeschl 5601: .LC_breadcrumb_tools_tools {
                   5602:     padding: 0;
                   5603:     margin: 0;
1.913     droeschl 5604:     float: right;
                   5605: }
                   5606: 
1.359     albertel 5607: table#LC_title_bar td {
                   5608:   background: $tabbg;
                   5609: }
1.795     www      5610: 
1.911     bisitz   5611: table#LC_menubuttons img {
1.803     bisitz   5612:   border: none;
1.346     albertel 5613: }
1.795     www      5614: 
1.842     droeschl 5615: .LC_breadcrumbs_component {
1.911     bisitz   5616:   float: right;
                   5617:   margin: 0 1em;
1.357     albertel 5618: }
1.842     droeschl 5619: .LC_breadcrumbs_component img {
1.911     bisitz   5620:   vertical-align: middle;
1.777     tempelho 5621: }
1.795     www      5622: 
1.383     albertel 5623: td.LC_table_cell_checkbox {
                   5624:   text-align: center;
                   5625: }
1.795     www      5626: 
                   5627: .LC_fontsize_small {
1.911     bisitz   5628:   font-size: 70%;
1.705     tempelho 5629: }
                   5630: 
1.844     bisitz   5631: #LC_breadcrumbs {
1.911     bisitz   5632:   clear:both;
                   5633:   background: $sidebg;
                   5634:   border-bottom: 1px solid $lg_border_color;
                   5635:   line-height: 2.5em;
1.933     droeschl 5636:   overflow: hidden;
1.911     bisitz   5637:   margin: 0;
                   5638:   padding: 0;
1.995     raeburn  5639:   text-align: left;
1.819     tempelho 5640: }
1.862     bisitz   5641: 
1.1098    bisitz   5642: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5643:   clear:both;
                   5644:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5645:   border: 1px solid $sidebg;
1.1098    bisitz   5646:   margin: 0 0 10px 0;
1.966     bisitz   5647:   padding: 3px;
1.995     raeburn  5648:   text-align: left;
1.822     bisitz   5649: }
                   5650: 
1.795     www      5651: .LC_fontsize_medium {
1.911     bisitz   5652:   font-size: 85%;
1.705     tempelho 5653: }
                   5654: 
1.795     www      5655: .LC_fontsize_large {
1.911     bisitz   5656:   font-size: 120%;
1.705     tempelho 5657: }
                   5658: 
1.346     albertel 5659: .LC_menubuttons_inline_text {
                   5660:   color: $font;
1.698     harmsja  5661:   font-size: 90%;
1.701     harmsja  5662:   padding-left:3px;
1.346     albertel 5663: }
                   5664: 
1.934     droeschl 5665: .LC_menubuttons_inline_text img{
                   5666:   vertical-align: middle;
                   5667: }
                   5668: 
1.1051    www      5669: li.LC_menubuttons_inline_text img {
1.951     onken    5670:   cursor:pointer;
1.1002    droeschl 5671:   text-decoration: none;
1.951     onken    5672: }
                   5673: 
1.526     www      5674: .LC_menubuttons_link {
                   5675:   text-decoration: none;
                   5676: }
1.795     www      5677: 
1.522     albertel 5678: .LC_menubuttons_category {
1.521     www      5679:   color: $font;
1.526     www      5680:   background: $pgbg;
1.521     www      5681:   font-size: larger;
                   5682:   font-weight: bold;
                   5683: }
                   5684: 
1.346     albertel 5685: td.LC_menubuttons_text {
1.911     bisitz   5686:   color: $font;
1.346     albertel 5687: }
1.706     harmsja  5688: 
1.346     albertel 5689: .LC_current_location {
                   5690:   background: $tabbg;
                   5691: }
1.795     www      5692: 
1.938     bisitz   5693: table.LC_data_table {
1.347     albertel 5694:   border: 1px solid #000000;
1.402     albertel 5695:   border-collapse: separate;
1.426     albertel 5696:   border-spacing: 1px;
1.610     albertel 5697:   background: $pgbg;
1.347     albertel 5698: }
1.795     www      5699: 
1.422     albertel 5700: .LC_data_table_dense {
                   5701:   font-size: small;
                   5702: }
1.795     www      5703: 
1.507     raeburn  5704: table.LC_nested_outer {
                   5705:   border: 1px solid #000000;
1.589     raeburn  5706:   border-collapse: collapse;
1.803     bisitz   5707:   border-spacing: 0;
1.507     raeburn  5708:   width: 100%;
                   5709: }
1.795     www      5710: 
1.879     raeburn  5711: table.LC_innerpickbox,
1.507     raeburn  5712: table.LC_nested {
1.803     bisitz   5713:   border: none;
1.589     raeburn  5714:   border-collapse: collapse;
1.803     bisitz   5715:   border-spacing: 0;
1.507     raeburn  5716:   width: 100%;
                   5717: }
1.795     www      5718: 
1.911     bisitz   5719: table.LC_data_table tr th,
                   5720: table.LC_calendar tr th,
1.879     raeburn  5721: table.LC_prior_tries tr th,
                   5722: table.LC_innerpickbox tr th {
1.349     albertel 5723:   font-weight: bold;
                   5724:   background-color: $data_table_head;
1.801     tempelho 5725:   color:$fontmenu;
1.701     harmsja  5726:   font-size:90%;
1.347     albertel 5727: }
1.795     www      5728: 
1.879     raeburn  5729: table.LC_innerpickbox tr th,
                   5730: table.LC_innerpickbox tr td {
                   5731:   vertical-align: top;
                   5732: }
                   5733: 
1.711     raeburn  5734: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5735:   background-color: #CCCCCC;
1.711     raeburn  5736:   font-weight: bold;
                   5737:   text-align: left;
                   5738: }
1.795     www      5739: 
1.912     bisitz   5740: table.LC_data_table tr.LC_odd_row > td {
                   5741:   background-color: $data_table_light;
                   5742:   padding: 2px;
                   5743:   vertical-align: top;
                   5744: }
                   5745: 
1.809     bisitz   5746: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5747:   background-color: $data_table_light;
1.912     bisitz   5748:   vertical-align: top;
                   5749: }
                   5750: 
                   5751: table.LC_data_table tr.LC_even_row > td {
                   5752:   background-color: $data_table_dark;
1.425     albertel 5753:   padding: 2px;
1.900     bisitz   5754:   vertical-align: top;
1.347     albertel 5755: }
1.795     www      5756: 
1.809     bisitz   5757: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5758:   background-color: $data_table_dark;
1.900     bisitz   5759:   vertical-align: top;
1.347     albertel 5760: }
1.795     www      5761: 
1.425     albertel 5762: table.LC_data_table tr.LC_data_table_highlight td {
                   5763:   background-color: $data_table_darker;
                   5764: }
1.795     www      5765: 
1.639     raeburn  5766: table.LC_data_table tr td.LC_leftcol_header {
                   5767:   background-color: $data_table_head;
                   5768:   font-weight: bold;
                   5769: }
1.795     www      5770: 
1.451     albertel 5771: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5772: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5773:   font-weight: bold;
                   5774:   font-style: italic;
                   5775:   text-align: center;
                   5776:   padding: 8px;
1.347     albertel 5777: }
1.795     www      5778: 
1.1114    raeburn  5779: table.LC_data_table tr.LC_empty_row td,
                   5780: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5781:   background-color: $sidebg;
                   5782: }
                   5783: 
                   5784: table.LC_nested tr.LC_empty_row td {
                   5785:   background-color: #FFFFFF;
                   5786: }
                   5787: 
1.890     droeschl 5788: table.LC_caption {
                   5789: }
                   5790: 
1.507     raeburn  5791: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5792:   padding: 4ex
                   5793: }
1.795     www      5794: 
1.507     raeburn  5795: table.LC_nested_outer tr th {
                   5796:   font-weight: bold;
1.801     tempelho 5797:   color:$fontmenu;
1.507     raeburn  5798:   background-color: $data_table_head;
1.701     harmsja  5799:   font-size: small;
1.507     raeburn  5800:   border-bottom: 1px solid #000000;
                   5801: }
1.795     www      5802: 
1.507     raeburn  5803: table.LC_nested_outer tr td.LC_subheader {
                   5804:   background-color: $data_table_head;
                   5805:   font-weight: bold;
                   5806:   font-size: small;
                   5807:   border-bottom: 1px solid #000000;
                   5808:   text-align: right;
1.451     albertel 5809: }
1.795     www      5810: 
1.507     raeburn  5811: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5812:   background-color: #CCCCCC;
1.451     albertel 5813:   font-weight: bold;
                   5814:   font-size: small;
1.507     raeburn  5815:   text-align: center;
                   5816: }
1.795     www      5817: 
1.589     raeburn  5818: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5819: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5820:   text-align: left;
1.451     albertel 5821: }
1.795     www      5822: 
1.507     raeburn  5823: table.LC_nested td {
1.735     bisitz   5824:   background-color: #FFFFFF;
1.451     albertel 5825:   font-size: small;
1.507     raeburn  5826: }
1.795     www      5827: 
1.507     raeburn  5828: table.LC_nested_outer tr th.LC_right_item,
                   5829: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5830: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5831: table.LC_nested tr td.LC_right_item {
1.451     albertel 5832:   text-align: right;
                   5833: }
                   5834: 
1.507     raeburn  5835: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5836:   background-color: #EEEEEE;
1.451     albertel 5837: }
                   5838: 
1.473     raeburn  5839: table.LC_createuser {
                   5840: }
                   5841: 
                   5842: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5843:   font-size: small;
1.473     raeburn  5844: }
                   5845: 
                   5846: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5847:   background-color: #CCCCCC;
1.473     raeburn  5848:   font-weight: bold;
                   5849:   text-align: center;
                   5850: }
                   5851: 
1.349     albertel 5852: table.LC_calendar {
                   5853:   border: 1px solid #000000;
                   5854:   border-collapse: collapse;
1.917     raeburn  5855:   width: 98%;
1.349     albertel 5856: }
1.795     www      5857: 
1.349     albertel 5858: table.LC_calendar_pickdate {
                   5859:   font-size: xx-small;
                   5860: }
1.795     www      5861: 
1.349     albertel 5862: table.LC_calendar tr td {
                   5863:   border: 1px solid #000000;
                   5864:   vertical-align: top;
1.917     raeburn  5865:   width: 14%;
1.349     albertel 5866: }
1.795     www      5867: 
1.349     albertel 5868: table.LC_calendar tr td.LC_calendar_day_empty {
                   5869:   background-color: $data_table_dark;
                   5870: }
1.795     www      5871: 
1.779     bisitz   5872: table.LC_calendar tr td.LC_calendar_day_current {
                   5873:   background-color: $data_table_highlight;
1.777     tempelho 5874: }
1.795     www      5875: 
1.938     bisitz   5876: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5877:   background-color: $mail_new;
                   5878: }
1.795     www      5879: 
1.938     bisitz   5880: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5881:   background-color: $mail_new_hover;
                   5882: }
1.795     www      5883: 
1.938     bisitz   5884: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5885:   background-color: $mail_read;
                   5886: }
1.795     www      5887: 
1.938     bisitz   5888: /*
                   5889: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5890:   background-color: $mail_read_hover;
                   5891: }
1.938     bisitz   5892: */
1.795     www      5893: 
1.938     bisitz   5894: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5895:   background-color: $mail_replied;
                   5896: }
1.795     www      5897: 
1.938     bisitz   5898: /*
                   5899: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5900:   background-color: $mail_replied_hover;
                   5901: }
1.938     bisitz   5902: */
1.795     www      5903: 
1.938     bisitz   5904: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5905:   background-color: $mail_other;
                   5906: }
1.795     www      5907: 
1.938     bisitz   5908: /*
                   5909: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5910:   background-color: $mail_other_hover;
                   5911: }
1.938     bisitz   5912: */
1.494     raeburn  5913: 
1.777     tempelho 5914: table.LC_data_table tr > td.LC_browser_file,
                   5915: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5916:   background: #AAEE77;
1.389     albertel 5917: }
1.795     www      5918: 
1.777     tempelho 5919: table.LC_data_table tr > td.LC_browser_file_locked,
                   5920: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5921:   background: #FFAA99;
1.387     albertel 5922: }
1.795     www      5923: 
1.777     tempelho 5924: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5925:   background: #888888;
1.779     bisitz   5926: }
1.795     www      5927: 
1.777     tempelho 5928: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5929: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5930:   background: #F8F866;
1.777     tempelho 5931: }
1.795     www      5932: 
1.696     bisitz   5933: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5934:   background: #E0E8FF;
1.387     albertel 5935: }
1.696     bisitz   5936: 
1.707     bisitz   5937: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5938:   /* background: #77FF77; */
1.707     bisitz   5939: }
1.795     www      5940: 
1.707     bisitz   5941: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5942:   border-right: 8px solid #FFFF77;
1.707     bisitz   5943: }
1.795     www      5944: 
1.707     bisitz   5945: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5946:   border-right: 8px solid #FFAA77;
1.707     bisitz   5947: }
1.795     www      5948: 
1.707     bisitz   5949: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5950:   border-right: 8px solid #FF7777;
1.707     bisitz   5951: }
1.795     www      5952: 
1.707     bisitz   5953: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5954:   border-right: 8px solid #AAFF77;
1.707     bisitz   5955: }
1.795     www      5956: 
1.707     bisitz   5957: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5958:   border-right: 8px solid #11CC55;
1.707     bisitz   5959: }
                   5960: 
1.388     albertel 5961: span.LC_current_location {
1.701     harmsja  5962:   font-size:larger;
1.388     albertel 5963:   background: $pgbg;
                   5964: }
1.387     albertel 5965: 
1.1029    www      5966: span.LC_current_nav_location {
                   5967:   font-weight:bold;
                   5968:   background: $sidebg;
                   5969: }
                   5970: 
1.395     albertel 5971: span.LC_parm_menu_item {
                   5972:   font-size: larger;
                   5973: }
1.795     www      5974: 
1.395     albertel 5975: span.LC_parm_scope_all {
                   5976:   color: red;
                   5977: }
1.795     www      5978: 
1.395     albertel 5979: span.LC_parm_scope_folder {
                   5980:   color: green;
                   5981: }
1.795     www      5982: 
1.395     albertel 5983: span.LC_parm_scope_resource {
                   5984:   color: orange;
                   5985: }
1.795     www      5986: 
1.395     albertel 5987: span.LC_parm_part {
                   5988:   color: blue;
                   5989: }
1.795     www      5990: 
1.911     bisitz   5991: span.LC_parm_folder,
                   5992: span.LC_parm_symb {
1.395     albertel 5993:   font-size: x-small;
                   5994:   font-family: $mono;
                   5995:   color: #AAAAAA;
                   5996: }
                   5997: 
1.977     bisitz   5998: ul.LC_parm_parmlist li {
                   5999:   display: inline-block;
                   6000:   padding: 0.3em 0.8em;
                   6001:   vertical-align: top;
                   6002:   width: 150px;
                   6003:   border-top:1px solid $lg_border_color;
                   6004: }
                   6005: 
1.795     www      6006: td.LC_parm_overview_level_menu,
                   6007: td.LC_parm_overview_map_menu,
                   6008: td.LC_parm_overview_parm_selectors,
                   6009: td.LC_parm_overview_restrictions  {
1.396     albertel 6010:   border: 1px solid black;
                   6011:   border-collapse: collapse;
                   6012: }
1.795     www      6013: 
1.396     albertel 6014: table.LC_parm_overview_restrictions td {
                   6015:   border-width: 1px 4px 1px 4px;
                   6016:   border-style: solid;
                   6017:   border-color: $pgbg;
                   6018:   text-align: center;
                   6019: }
1.795     www      6020: 
1.396     albertel 6021: table.LC_parm_overview_restrictions th {
                   6022:   background: $tabbg;
                   6023:   border-width: 1px 4px 1px 4px;
                   6024:   border-style: solid;
                   6025:   border-color: $pgbg;
                   6026: }
1.795     www      6027: 
1.398     albertel 6028: table#LC_helpmenu {
1.803     bisitz   6029:   border: none;
1.398     albertel 6030:   height: 55px;
1.803     bisitz   6031:   border-spacing: 0;
1.398     albertel 6032: }
                   6033: 
                   6034: table#LC_helpmenu fieldset legend {
                   6035:   font-size: larger;
                   6036: }
1.795     www      6037: 
1.397     albertel 6038: table#LC_helpmenu_links {
                   6039:   width: 100%;
                   6040:   border: 1px solid black;
                   6041:   background: $pgbg;
1.803     bisitz   6042:   padding: 0;
1.397     albertel 6043:   border-spacing: 1px;
                   6044: }
1.795     www      6045: 
1.397     albertel 6046: table#LC_helpmenu_links tr td {
                   6047:   padding: 1px;
                   6048:   background: $tabbg;
1.399     albertel 6049:   text-align: center;
                   6050:   font-weight: bold;
1.397     albertel 6051: }
1.396     albertel 6052: 
1.795     www      6053: table#LC_helpmenu_links a:link,
                   6054: table#LC_helpmenu_links a:visited,
1.397     albertel 6055: table#LC_helpmenu_links a:active {
                   6056:   text-decoration: none;
                   6057:   color: $font;
                   6058: }
1.795     www      6059: 
1.397     albertel 6060: table#LC_helpmenu_links a:hover {
                   6061:   text-decoration: underline;
                   6062:   color: $vlink;
                   6063: }
1.396     albertel 6064: 
1.417     albertel 6065: .LC_chrt_popup_exists {
                   6066:   border: 1px solid #339933;
                   6067:   margin: -1px;
                   6068: }
1.795     www      6069: 
1.417     albertel 6070: .LC_chrt_popup_up {
                   6071:   border: 1px solid yellow;
                   6072:   margin: -1px;
                   6073: }
1.795     www      6074: 
1.417     albertel 6075: .LC_chrt_popup {
                   6076:   border: 1px solid #8888FF;
                   6077:   background: #CCCCFF;
                   6078: }
1.795     www      6079: 
1.421     albertel 6080: table.LC_pick_box {
                   6081:   border-collapse: separate;
                   6082:   background: white;
                   6083:   border: 1px solid black;
                   6084:   border-spacing: 1px;
                   6085: }
1.795     www      6086: 
1.421     albertel 6087: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6088:   background: $sidebg;
1.421     albertel 6089:   font-weight: bold;
1.900     bisitz   6090:   text-align: left;
1.740     bisitz   6091:   vertical-align: top;
1.421     albertel 6092:   width: 184px;
                   6093:   padding: 8px;
                   6094: }
1.795     www      6095: 
1.579     raeburn  6096: table.LC_pick_box td.LC_pick_box_value {
                   6097:   text-align: left;
                   6098:   padding: 8px;
                   6099: }
1.795     www      6100: 
1.579     raeburn  6101: table.LC_pick_box td.LC_pick_box_select {
                   6102:   text-align: left;
                   6103:   padding: 8px;
                   6104: }
1.795     www      6105: 
1.424     albertel 6106: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6107:   padding: 0;
1.421     albertel 6108:   height: 1px;
                   6109:   background: black;
                   6110: }
1.795     www      6111: 
1.421     albertel 6112: table.LC_pick_box td.LC_pick_box_submit {
                   6113:   text-align: right;
                   6114: }
1.795     www      6115: 
1.579     raeburn  6116: table.LC_pick_box td.LC_evenrow_value {
                   6117:   text-align: left;
                   6118:   padding: 8px;
                   6119:   background-color: $data_table_light;
                   6120: }
1.795     www      6121: 
1.579     raeburn  6122: table.LC_pick_box td.LC_oddrow_value {
                   6123:   text-align: left;
                   6124:   padding: 8px;
                   6125:   background-color: $data_table_light;
                   6126: }
1.795     www      6127: 
1.579     raeburn  6128: span.LC_helpform_receipt_cat {
                   6129:   font-weight: bold;
                   6130: }
1.795     www      6131: 
1.424     albertel 6132: table.LC_group_priv_box {
                   6133:   background: white;
                   6134:   border: 1px solid black;
                   6135:   border-spacing: 1px;
                   6136: }
1.795     www      6137: 
1.424     albertel 6138: table.LC_group_priv_box td.LC_pick_box_title {
                   6139:   background: $tabbg;
                   6140:   font-weight: bold;
                   6141:   text-align: right;
                   6142:   width: 184px;
                   6143: }
1.795     www      6144: 
1.424     albertel 6145: table.LC_group_priv_box td.LC_groups_fixed {
                   6146:   background: $data_table_light;
                   6147:   text-align: center;
                   6148: }
1.795     www      6149: 
1.424     albertel 6150: table.LC_group_priv_box td.LC_groups_optional {
                   6151:   background: $data_table_dark;
                   6152:   text-align: center;
                   6153: }
1.795     www      6154: 
1.424     albertel 6155: table.LC_group_priv_box td.LC_groups_functionality {
                   6156:   background: $data_table_darker;
                   6157:   text-align: center;
                   6158:   font-weight: bold;
                   6159: }
1.795     www      6160: 
1.424     albertel 6161: table.LC_group_priv td {
                   6162:   text-align: left;
1.803     bisitz   6163:   padding: 0;
1.424     albertel 6164: }
                   6165: 
                   6166: .LC_navbuttons {
                   6167:   margin: 2ex 0ex 2ex 0ex;
                   6168: }
1.795     www      6169: 
1.423     albertel 6170: .LC_topic_bar {
                   6171:   font-weight: bold;
                   6172:   background: $tabbg;
1.918     wenzelju 6173:   margin: 1em 0em 1em 2em;
1.805     bisitz   6174:   padding: 3px;
1.918     wenzelju 6175:   font-size: 1.2em;
1.423     albertel 6176: }
1.795     www      6177: 
1.423     albertel 6178: .LC_topic_bar span {
1.918     wenzelju 6179:   left: 0.5em;
                   6180:   position: absolute;
1.423     albertel 6181:   vertical-align: middle;
1.918     wenzelju 6182:   font-size: 1.2em;
1.423     albertel 6183: }
1.795     www      6184: 
1.423     albertel 6185: table.LC_course_group_status {
                   6186:   margin: 20px;
                   6187: }
1.795     www      6188: 
1.423     albertel 6189: table.LC_status_selector td {
                   6190:   vertical-align: top;
                   6191:   text-align: center;
1.424     albertel 6192:   padding: 4px;
                   6193: }
1.795     www      6194: 
1.599     albertel 6195: div.LC_feedback_link {
1.616     albertel 6196:   clear: both;
1.829     kalberla 6197:   background: $sidebg;
1.779     bisitz   6198:   width: 100%;
1.829     kalberla 6199:   padding-bottom: 10px;
                   6200:   border: 1px $tabbg solid;
1.833     kalberla 6201:   height: 22px;
                   6202:   line-height: 22px;
                   6203:   padding-top: 5px;
                   6204: }
                   6205: 
                   6206: div.LC_feedback_link img {
                   6207:   height: 22px;
1.867     kalberla 6208:   vertical-align:middle;
1.829     kalberla 6209: }
                   6210: 
1.911     bisitz   6211: div.LC_feedback_link a {
1.829     kalberla 6212:   text-decoration: none;
1.489     raeburn  6213: }
1.795     www      6214: 
1.867     kalberla 6215: div.LC_comblock {
1.911     bisitz   6216:   display:inline;
1.867     kalberla 6217:   color:$font;
                   6218:   font-size:90%;
                   6219: }
                   6220: 
                   6221: div.LC_feedback_link div.LC_comblock {
                   6222:   padding-left:5px;
                   6223: }
                   6224: 
                   6225: div.LC_feedback_link div.LC_comblock a {
                   6226:   color:$font;
                   6227: }
                   6228: 
1.489     raeburn  6229: span.LC_feedback_link {
1.858     bisitz   6230:   /* background: $feedback_link_bg; */
1.599     albertel 6231:   font-size: larger;
                   6232: }
1.795     www      6233: 
1.599     albertel 6234: span.LC_message_link {
1.858     bisitz   6235:   /* background: $feedback_link_bg; */
1.599     albertel 6236:   font-size: larger;
                   6237:   position: absolute;
                   6238:   right: 1em;
1.489     raeburn  6239: }
1.421     albertel 6240: 
1.515     albertel 6241: table.LC_prior_tries {
1.524     albertel 6242:   border: 1px solid #000000;
                   6243:   border-collapse: separate;
                   6244:   border-spacing: 1px;
1.515     albertel 6245: }
1.523     albertel 6246: 
1.515     albertel 6247: table.LC_prior_tries td {
1.524     albertel 6248:   padding: 2px;
1.515     albertel 6249: }
1.523     albertel 6250: 
                   6251: .LC_answer_correct {
1.795     www      6252:   background: lightgreen;
                   6253:   color: darkgreen;
                   6254:   padding: 6px;
1.523     albertel 6255: }
1.795     www      6256: 
1.523     albertel 6257: .LC_answer_charged_try {
1.797     www      6258:   background: #FFAAAA;
1.795     www      6259:   color: darkred;
                   6260:   padding: 6px;
1.523     albertel 6261: }
1.795     www      6262: 
1.779     bisitz   6263: .LC_answer_not_charged_try,
1.523     albertel 6264: .LC_answer_no_grade,
                   6265: .LC_answer_late {
1.795     www      6266:   background: lightyellow;
1.523     albertel 6267:   color: black;
1.795     www      6268:   padding: 6px;
1.523     albertel 6269: }
1.795     www      6270: 
1.523     albertel 6271: .LC_answer_previous {
1.795     www      6272:   background: lightblue;
                   6273:   color: darkblue;
                   6274:   padding: 6px;
1.523     albertel 6275: }
1.795     www      6276: 
1.779     bisitz   6277: .LC_answer_no_message {
1.777     tempelho 6278:   background: #FFFFFF;
                   6279:   color: black;
1.795     www      6280:   padding: 6px;
1.779     bisitz   6281: }
1.795     www      6282: 
1.779     bisitz   6283: .LC_answer_unknown {
                   6284:   background: orange;
                   6285:   color: black;
1.795     www      6286:   padding: 6px;
1.777     tempelho 6287: }
1.795     www      6288: 
1.529     albertel 6289: span.LC_prior_numerical,
                   6290: span.LC_prior_string,
                   6291: span.LC_prior_custom,
                   6292: span.LC_prior_reaction,
                   6293: span.LC_prior_math {
1.925     bisitz   6294:   font-family: $mono;
1.523     albertel 6295:   white-space: pre;
                   6296: }
                   6297: 
1.525     albertel 6298: span.LC_prior_string {
1.925     bisitz   6299:   font-family: $mono;
1.525     albertel 6300:   white-space: pre;
                   6301: }
                   6302: 
1.523     albertel 6303: table.LC_prior_option {
                   6304:   width: 100%;
                   6305:   border-collapse: collapse;
                   6306: }
1.795     www      6307: 
1.911     bisitz   6308: table.LC_prior_rank,
1.795     www      6309: table.LC_prior_match {
1.528     albertel 6310:   border-collapse: collapse;
                   6311: }
1.795     www      6312: 
1.528     albertel 6313: table.LC_prior_option tr td,
                   6314: table.LC_prior_rank tr td,
                   6315: table.LC_prior_match tr td {
1.524     albertel 6316:   border: 1px solid #000000;
1.515     albertel 6317: }
                   6318: 
1.855     bisitz   6319: .LC_nobreak {
1.544     albertel 6320:   white-space: nowrap;
1.519     raeburn  6321: }
                   6322: 
1.576     raeburn  6323: span.LC_cusr_emph {
                   6324:   font-style: italic;
                   6325: }
                   6326: 
1.633     raeburn  6327: span.LC_cusr_subheading {
                   6328:   font-weight: normal;
                   6329:   font-size: 85%;
                   6330: }
                   6331: 
1.861     bisitz   6332: div.LC_docs_entry_move {
1.859     bisitz   6333:   border: 1px solid #BBBBBB;
1.545     albertel 6334:   background: #DDDDDD;
1.861     bisitz   6335:   width: 22px;
1.859     bisitz   6336:   padding: 1px;
                   6337:   margin: 0;
1.545     albertel 6338: }
                   6339: 
1.861     bisitz   6340: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6341: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6342:   font-size: x-small;
                   6343: }
1.795     www      6344: 
1.861     bisitz   6345: .LC_docs_entry_parameter {
                   6346:   white-space: nowrap;
                   6347: }
                   6348: 
1.544     albertel 6349: .LC_docs_copy {
1.545     albertel 6350:   color: #000099;
1.544     albertel 6351: }
1.795     www      6352: 
1.544     albertel 6353: .LC_docs_cut {
1.545     albertel 6354:   color: #550044;
1.544     albertel 6355: }
1.795     www      6356: 
1.544     albertel 6357: .LC_docs_rename {
1.545     albertel 6358:   color: #009900;
1.544     albertel 6359: }
1.795     www      6360: 
1.544     albertel 6361: .LC_docs_remove {
1.545     albertel 6362:   color: #990000;
                   6363: }
                   6364: 
1.547     albertel 6365: .LC_docs_reinit_warn,
                   6366: .LC_docs_ext_edit {
                   6367:   font-size: x-small;
                   6368: }
                   6369: 
1.545     albertel 6370: table.LC_docs_adddocs td,
                   6371: table.LC_docs_adddocs th {
                   6372:   border: 1px solid #BBBBBB;
                   6373:   padding: 4px;
                   6374:   background: #DDDDDD;
1.543     albertel 6375: }
                   6376: 
1.584     albertel 6377: table.LC_sty_begin {
                   6378:   background: #BBFFBB;
                   6379: }
1.795     www      6380: 
1.584     albertel 6381: table.LC_sty_end {
                   6382:   background: #FFBBBB;
                   6383: }
                   6384: 
1.589     raeburn  6385: table.LC_double_column {
1.803     bisitz   6386:   border-width: 0;
1.589     raeburn  6387:   border-collapse: collapse;
                   6388:   width: 100%;
                   6389:   padding: 2px;
                   6390: }
                   6391: 
                   6392: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6393:   top: 2px;
1.589     raeburn  6394:   left: 2px;
                   6395:   width: 47%;
                   6396:   vertical-align: top;
                   6397: }
                   6398: 
                   6399: table.LC_double_column tr td.LC_right_col {
                   6400:   top: 2px;
1.779     bisitz   6401:   right: 2px;
1.589     raeburn  6402:   width: 47%;
                   6403:   vertical-align: top;
                   6404: }
                   6405: 
1.591     raeburn  6406: div.LC_left_float {
                   6407:   float: left;
                   6408:   padding-right: 5%;
1.597     albertel 6409:   padding-bottom: 4px;
1.591     raeburn  6410: }
                   6411: 
                   6412: div.LC_clear_float_header {
1.597     albertel 6413:   padding-bottom: 2px;
1.591     raeburn  6414: }
                   6415: 
                   6416: div.LC_clear_float_footer {
1.597     albertel 6417:   padding-top: 10px;
1.591     raeburn  6418:   clear: both;
                   6419: }
                   6420: 
1.597     albertel 6421: div.LC_grade_show_user {
1.941     bisitz   6422: /*  border-left: 5px solid $sidebg; */
                   6423:   border-top: 5px solid #000000;
                   6424:   margin: 50px 0 0 0;
1.936     bisitz   6425:   padding: 15px 0 5px 10px;
1.597     albertel 6426: }
1.795     www      6427: 
1.936     bisitz   6428: div.LC_grade_show_user_odd_row {
1.941     bisitz   6429: /*  border-left: 5px solid #000000; */
                   6430: }
                   6431: 
                   6432: div.LC_grade_show_user div.LC_Box {
                   6433:   margin-right: 50px;
1.597     albertel 6434: }
                   6435: 
                   6436: div.LC_grade_submissions,
                   6437: div.LC_grade_message_center,
1.936     bisitz   6438: div.LC_grade_info_links {
1.597     albertel 6439:   margin: 5px;
                   6440:   width: 99%;
                   6441:   background: #FFFFFF;
                   6442: }
1.795     www      6443: 
1.597     albertel 6444: div.LC_grade_submissions_header,
1.936     bisitz   6445: div.LC_grade_message_center_header {
1.705     tempelho 6446:   font-weight: bold;
                   6447:   font-size: large;
1.597     albertel 6448: }
1.795     www      6449: 
1.597     albertel 6450: div.LC_grade_submissions_body,
1.936     bisitz   6451: div.LC_grade_message_center_body {
1.597     albertel 6452:   border: 1px solid black;
                   6453:   width: 99%;
                   6454:   background: #FFFFFF;
                   6455: }
1.795     www      6456: 
1.613     albertel 6457: table.LC_scantron_action {
                   6458:   width: 100%;
                   6459: }
1.795     www      6460: 
1.613     albertel 6461: table.LC_scantron_action tr th {
1.698     harmsja  6462:   font-weight:bold;
                   6463:   font-style:normal;
1.613     albertel 6464: }
1.795     www      6465: 
1.779     bisitz   6466: .LC_edit_problem_header,
1.614     albertel 6467: div.LC_edit_problem_footer {
1.705     tempelho 6468:   font-weight: normal;
                   6469:   font-size:  medium;
1.602     albertel 6470:   margin: 2px;
1.1060    bisitz   6471:   background-color: $sidebg;
1.600     albertel 6472: }
1.795     www      6473: 
1.600     albertel 6474: div.LC_edit_problem_header,
1.602     albertel 6475: div.LC_edit_problem_header div,
1.614     albertel 6476: div.LC_edit_problem_footer,
                   6477: div.LC_edit_problem_footer div,
1.602     albertel 6478: div.LC_edit_problem_editxml_header,
                   6479: div.LC_edit_problem_editxml_header div {
1.600     albertel 6480:   margin-top: 5px;
                   6481: }
1.795     www      6482: 
1.600     albertel 6483: div.LC_edit_problem_header_title {
1.705     tempelho 6484:   font-weight: bold;
                   6485:   font-size: larger;
1.602     albertel 6486:   background: $tabbg;
                   6487:   padding: 3px;
1.1060    bisitz   6488:   margin: 0 0 5px 0;
1.602     albertel 6489: }
1.795     www      6490: 
1.602     albertel 6491: table.LC_edit_problem_header_title {
                   6492:   width: 100%;
1.600     albertel 6493:   background: $tabbg;
1.602     albertel 6494: }
                   6495: 
                   6496: div.LC_edit_problem_discards {
                   6497:   float: left;
                   6498:   padding-bottom: 5px;
                   6499: }
1.795     www      6500: 
1.602     albertel 6501: div.LC_edit_problem_saves {
                   6502:   float: right;
                   6503:   padding-bottom: 5px;
1.600     albertel 6504: }
1.795     www      6505: 
1.1124    bisitz   6506: .LC_edit_opt {
                   6507:   padding-left: 1em;
                   6508:   white-space: nowrap;
                   6509: }
                   6510: 
1.1152    golterma 6511: .LC_edit_problem_latexhelper{
                   6512:     text-align: right;
                   6513: }
                   6514: 
                   6515: #LC_edit_problem_colorful div{
                   6516:     margin-left: 40px;
                   6517: }
                   6518: 
1.911     bisitz   6519: img.stift {
1.803     bisitz   6520:   border-width: 0;
                   6521:   vertical-align: middle;
1.677     riegler  6522: }
1.680     riegler  6523: 
1.923     bisitz   6524: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6525:   vertical-align: top;
1.777     tempelho 6526: }
1.795     www      6527: 
1.716     raeburn  6528: div.LC_createcourse {
1.911     bisitz   6529:   margin: 10px 10px 10px 10px;
1.716     raeburn  6530: }
                   6531: 
1.917     raeburn  6532: .LC_dccid {
1.1130    raeburn  6533:   float: right;
1.917     raeburn  6534:   margin: 0.2em 0 0 0;
                   6535:   padding: 0;
                   6536:   font-size: 90%;
                   6537:   display:none;
                   6538: }
                   6539: 
1.897     wenzelju 6540: ol.LC_primary_menu a:hover,
1.721     harmsja  6541: ol#LC_MenuBreadcrumbs a:hover,
                   6542: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6543: ul#LC_secondary_menu a:hover,
1.721     harmsja  6544: .LC_FormSectionClearButton input:hover
1.795     www      6545: ul.LC_TabContent   li:hover a {
1.952     onken    6546:   color:$button_hover;
1.911     bisitz   6547:   text-decoration:none;
1.693     droeschl 6548: }
                   6549: 
1.779     bisitz   6550: h1 {
1.911     bisitz   6551:   padding: 0;
                   6552:   line-height:130%;
1.693     droeschl 6553: }
1.698     harmsja  6554: 
1.911     bisitz   6555: h2,
                   6556: h3,
                   6557: h4,
                   6558: h5,
                   6559: h6 {
                   6560:   margin: 5px 0 5px 0;
                   6561:   padding: 0;
                   6562:   line-height:130%;
1.693     droeschl 6563: }
1.795     www      6564: 
                   6565: .LC_hcell {
1.911     bisitz   6566:   padding:3px 15px 3px 15px;
                   6567:   margin: 0;
                   6568:   background-color:$tabbg;
                   6569:   color:$fontmenu;
                   6570:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6571: }
1.795     www      6572: 
1.840     bisitz   6573: .LC_Box > .LC_hcell {
1.911     bisitz   6574:   margin: 0 -10px 10px -10px;
1.835     bisitz   6575: }
                   6576: 
1.721     harmsja  6577: .LC_noBorder {
1.911     bisitz   6578:   border: 0;
1.698     harmsja  6579: }
1.693     droeschl 6580: 
1.721     harmsja  6581: .LC_FormSectionClearButton input {
1.911     bisitz   6582:   background-color:transparent;
                   6583:   border: none;
                   6584:   cursor:pointer;
                   6585:   text-decoration:underline;
1.693     droeschl 6586: }
1.763     bisitz   6587: 
                   6588: .LC_help_open_topic {
1.911     bisitz   6589:   color: #FFFFFF;
                   6590:   background-color: #EEEEFF;
                   6591:   margin: 1px;
                   6592:   padding: 4px;
                   6593:   border: 1px solid #000033;
                   6594:   white-space: nowrap;
                   6595:   /* vertical-align: middle; */
1.759     neumanie 6596: }
1.693     droeschl 6597: 
1.911     bisitz   6598: dl,
                   6599: ul,
                   6600: div,
                   6601: fieldset {
                   6602:   margin: 10px 10px 10px 0;
                   6603:   /* overflow: hidden; */
1.693     droeschl 6604: }
1.795     www      6605: 
1.838     bisitz   6606: fieldset > legend {
1.911     bisitz   6607:   font-weight: bold;
                   6608:   padding: 0 5px 0 5px;
1.838     bisitz   6609: }
                   6610: 
1.813     bisitz   6611: #LC_nav_bar {
1.911     bisitz   6612:   float: left;
1.995     raeburn  6613:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6614:   margin: 0 0 2px 0;
1.807     droeschl 6615: }
                   6616: 
1.916     droeschl 6617: #LC_realm {
                   6618:   margin: 0.2em 0 0 0;
                   6619:   padding: 0;
                   6620:   font-weight: bold;
                   6621:   text-align: center;
1.995     raeburn  6622:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6623: }
                   6624: 
1.911     bisitz   6625: #LC_nav_bar em {
                   6626:   font-weight: bold;
                   6627:   font-style: normal;
1.807     droeschl 6628: }
                   6629: 
1.897     wenzelju 6630: ol.LC_primary_menu {
1.934     droeschl 6631:   margin: 0;
1.1076    raeburn  6632:   padding: 0;
1.995     raeburn  6633:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6634: }
                   6635: 
1.852     droeschl 6636: ol#LC_PathBreadcrumbs {
1.911     bisitz   6637:   margin: 0;
1.693     droeschl 6638: }
                   6639: 
1.897     wenzelju 6640: ol.LC_primary_menu li {
1.1076    raeburn  6641:   color: RGB(80, 80, 80);
                   6642:   vertical-align: middle;
                   6643:   text-align: left;
                   6644:   list-style: none;
                   6645:   float: left;
                   6646: }
                   6647: 
                   6648: ol.LC_primary_menu li a {
                   6649:   display: block;
                   6650:   margin: 0;
                   6651:   padding: 0 5px 0 10px;
                   6652:   text-decoration: none;
                   6653: }
                   6654: 
                   6655: ol.LC_primary_menu li ul {
                   6656:   display: none;
                   6657:   width: 10em;
                   6658:   background-color: $data_table_light;
                   6659: }
                   6660: 
                   6661: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6662:   display: block;
                   6663:   position: absolute;
                   6664:   margin: 0;
                   6665:   padding: 0;
1.1078    raeburn  6666:   z-index: 2;
1.1076    raeburn  6667: }
                   6668: 
                   6669: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6670:   font-size: 90%;
1.911     bisitz   6671:   vertical-align: top;
1.1076    raeburn  6672:   float: none;
1.1079    raeburn  6673:   border-left: 1px solid black;
                   6674:   border-right: 1px solid black;
1.1076    raeburn  6675: }
                   6676: 
                   6677: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1078    raeburn  6678:   background-color:$data_table_light;
1.1076    raeburn  6679: }
                   6680: 
                   6681: ol.LC_primary_menu li li a:hover {
                   6682:    color:$button_hover;
                   6683:    background-color:$data_table_dark;
1.693     droeschl 6684: }
                   6685: 
1.897     wenzelju 6686: ol.LC_primary_menu li img {
1.911     bisitz   6687:   vertical-align: bottom;
1.934     droeschl 6688:   height: 1.1em;
1.1077    raeburn  6689:   margin: 0.2em 0 0 0;
1.693     droeschl 6690: }
                   6691: 
1.897     wenzelju 6692: ol.LC_primary_menu a {
1.911     bisitz   6693:   color: RGB(80, 80, 80);
                   6694:   text-decoration: none;
1.693     droeschl 6695: }
1.795     www      6696: 
1.949     droeschl 6697: ol.LC_primary_menu a.LC_new_message {
                   6698:   font-weight:bold;
                   6699:   color: darkred;
                   6700: }
                   6701: 
1.975     raeburn  6702: ol.LC_docs_parameters {
                   6703:   margin-left: 0;
                   6704:   padding: 0;
                   6705:   list-style: none;
                   6706: }
                   6707: 
                   6708: ol.LC_docs_parameters li {
                   6709:   margin: 0;
                   6710:   padding-right: 20px;
                   6711:   display: inline;
                   6712: }
                   6713: 
1.976     raeburn  6714: ol.LC_docs_parameters li:before {
                   6715:   content: "\\002022 \\0020";
                   6716: }
                   6717: 
                   6718: li.LC_docs_parameters_title {
                   6719:   font-weight: bold;
                   6720: }
                   6721: 
                   6722: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6723:   content: "";
                   6724: }
                   6725: 
1.897     wenzelju 6726: ul#LC_secondary_menu {
1.1107    raeburn  6727:   clear: right;
1.911     bisitz   6728:   color: $fontmenu;
                   6729:   background: $tabbg;
                   6730:   list-style: none;
                   6731:   padding: 0;
                   6732:   margin: 0;
                   6733:   width: 100%;
1.995     raeburn  6734:   text-align: left;
1.1107    raeburn  6735:   float: left;
1.808     droeschl 6736: }
                   6737: 
1.897     wenzelju 6738: ul#LC_secondary_menu li {
1.911     bisitz   6739:   font-weight: bold;
                   6740:   line-height: 1.8em;
1.1107    raeburn  6741:   border-right: 1px solid black;
                   6742:   float: left;
                   6743: }
                   6744: 
                   6745: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6746:   background-color: $data_table_light;
                   6747: }
                   6748: 
                   6749: ul#LC_secondary_menu li a {
1.911     bisitz   6750:   padding: 0 0.8em;
1.1107    raeburn  6751: }
                   6752: 
                   6753: ul#LC_secondary_menu li ul {
                   6754:   display: none;
                   6755: }
                   6756: 
                   6757: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6758:   display: block;
                   6759:   position: absolute;
                   6760:   margin: 0;
                   6761:   padding: 0;
                   6762:   list-style:none;
                   6763:   float: none;
                   6764:   background-color: $data_table_light;
                   6765:   z-index: 2;
                   6766:   margin-left: -1px;
                   6767: }
                   6768: 
                   6769: ul#LC_secondary_menu li ul li {
                   6770:   font-size: 90%;
                   6771:   vertical-align: top;
                   6772:   border-left: 1px solid black;
1.911     bisitz   6773:   border-right: 1px solid black;
1.1119    raeburn  6774:   background-color: $data_table_light;
1.1107    raeburn  6775:   list-style:none;
                   6776:   float: none;
                   6777: }
                   6778: 
                   6779: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6780:   background-color: $data_table_dark;
1.807     droeschl 6781: }
                   6782: 
1.847     tempelho 6783: ul.LC_TabContent {
1.911     bisitz   6784:   display:block;
                   6785:   background: $sidebg;
                   6786:   border-bottom: solid 1px $lg_border_color;
                   6787:   list-style:none;
1.1020    raeburn  6788:   margin: -1px -10px 0 -10px;
1.911     bisitz   6789:   padding: 0;
1.693     droeschl 6790: }
                   6791: 
1.795     www      6792: ul.LC_TabContent li,
                   6793: ul.LC_TabContentBigger li {
1.911     bisitz   6794:   float:left;
1.741     harmsja  6795: }
1.795     www      6796: 
1.897     wenzelju 6797: ul#LC_secondary_menu li a {
1.911     bisitz   6798:   color: $fontmenu;
                   6799:   text-decoration: none;
1.693     droeschl 6800: }
1.795     www      6801: 
1.721     harmsja  6802: ul.LC_TabContent {
1.952     onken    6803:   min-height:20px;
1.721     harmsja  6804: }
1.795     www      6805: 
                   6806: ul.LC_TabContent li {
1.911     bisitz   6807:   vertical-align:middle;
1.959     onken    6808:   padding: 0 16px 0 10px;
1.911     bisitz   6809:   background-color:$tabbg;
                   6810:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6811:   border-left: solid 1px $font;
1.721     harmsja  6812: }
1.795     www      6813: 
1.847     tempelho 6814: ul.LC_TabContent .right {
1.911     bisitz   6815:   float:right;
1.847     tempelho 6816: }
                   6817: 
1.911     bisitz   6818: ul.LC_TabContent li a,
                   6819: ul.LC_TabContent li {
                   6820:   color:rgb(47,47,47);
                   6821:   text-decoration:none;
                   6822:   font-size:95%;
                   6823:   font-weight:bold;
1.952     onken    6824:   min-height:20px;
                   6825: }
                   6826: 
1.959     onken    6827: ul.LC_TabContent li a:hover,
                   6828: ul.LC_TabContent li a:focus {
1.952     onken    6829:   color: $button_hover;
1.959     onken    6830:   background:none;
                   6831:   outline:none;
1.952     onken    6832: }
                   6833: 
                   6834: ul.LC_TabContent li:hover {
                   6835:   color: $button_hover;
                   6836:   cursor:pointer;
1.721     harmsja  6837: }
1.795     www      6838: 
1.911     bisitz   6839: ul.LC_TabContent li.active {
1.952     onken    6840:   color: $font;
1.911     bisitz   6841:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6842:   border-bottom:solid 1px #FFFFFF;
                   6843:   cursor: default;
1.744     ehlerst  6844: }
1.795     www      6845: 
1.959     onken    6846: ul.LC_TabContent li.active a {
                   6847:   color:$font;
                   6848:   background:#FFFFFF;
                   6849:   outline: none;
                   6850: }
1.1047    raeburn  6851: 
                   6852: ul.LC_TabContent li.goback {
                   6853:   float: left;
                   6854:   border-left: none;
                   6855: }
                   6856: 
1.870     tempelho 6857: #maincoursedoc {
1.911     bisitz   6858:   clear:both;
1.870     tempelho 6859: }
                   6860: 
                   6861: ul.LC_TabContentBigger {
1.911     bisitz   6862:   display:block;
                   6863:   list-style:none;
                   6864:   padding: 0;
1.870     tempelho 6865: }
                   6866: 
1.795     www      6867: ul.LC_TabContentBigger li {
1.911     bisitz   6868:   vertical-align:bottom;
                   6869:   height: 30px;
                   6870:   font-size:110%;
                   6871:   font-weight:bold;
                   6872:   color: #737373;
1.841     tempelho 6873: }
                   6874: 
1.957     onken    6875: ul.LC_TabContentBigger li.active {
                   6876:   position: relative;
                   6877:   top: 1px;
                   6878: }
                   6879: 
1.870     tempelho 6880: ul.LC_TabContentBigger li a {
1.911     bisitz   6881:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6882:   height: 30px;
                   6883:   line-height: 30px;
                   6884:   text-align: center;
                   6885:   display: block;
                   6886:   text-decoration: none;
1.958     onken    6887:   outline: none;  
1.741     harmsja  6888: }
1.795     www      6889: 
1.870     tempelho 6890: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6891:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6892:   color:$font;
1.744     ehlerst  6893: }
1.795     www      6894: 
1.870     tempelho 6895: ul.LC_TabContentBigger li b {
1.911     bisitz   6896:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6897:   display: block;
                   6898:   float: left;
                   6899:   padding: 0 30px;
1.957     onken    6900:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6901: }
                   6902: 
1.956     onken    6903: ul.LC_TabContentBigger li:hover b {
                   6904:   color:$button_hover;
                   6905: }
                   6906: 
1.870     tempelho 6907: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6908:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6909:   color:$font;
1.957     onken    6910:   border: 0;
1.741     harmsja  6911: }
1.693     droeschl 6912: 
1.870     tempelho 6913: 
1.862     bisitz   6914: ul.LC_CourseBreadcrumbs {
                   6915:   background: $sidebg;
1.1020    raeburn  6916:   height: 2em;
1.862     bisitz   6917:   padding-left: 10px;
1.1020    raeburn  6918:   margin: 0;
1.862     bisitz   6919:   list-style-position: inside;
                   6920: }
                   6921: 
1.911     bisitz   6922: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6923: ol#LC_PathBreadcrumbs {
1.911     bisitz   6924:   padding-left: 10px;
                   6925:   margin: 0;
1.933     droeschl 6926:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6927: }
                   6928: 
1.911     bisitz   6929: ol#LC_MenuBreadcrumbs li,
                   6930: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6931: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6932:   display: inline;
1.933     droeschl 6933:   white-space: normal;  
1.693     droeschl 6934: }
                   6935: 
1.823     bisitz   6936: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6937: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6938:   text-decoration: none;
                   6939:   font-size:90%;
1.693     droeschl 6940: }
1.795     www      6941: 
1.969     droeschl 6942: ol#LC_MenuBreadcrumbs h1 {
                   6943:   display: inline;
                   6944:   font-size: 90%;
                   6945:   line-height: 2.5em;
                   6946:   margin: 0;
                   6947:   padding: 0;
                   6948: }
                   6949: 
1.795     www      6950: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6951:   text-decoration:none;
                   6952:   font-size:100%;
                   6953:   font-weight:bold;
1.693     droeschl 6954: }
1.795     www      6955: 
1.840     bisitz   6956: .LC_Box {
1.911     bisitz   6957:   border: solid 1px $lg_border_color;
                   6958:   padding: 0 10px 10px 10px;
1.746     neumanie 6959: }
1.795     www      6960: 
1.1020    raeburn  6961: .LC_DocsBox {
                   6962:   border: solid 1px $lg_border_color;
                   6963:   padding: 0 0 10px 10px;
                   6964: }
                   6965: 
1.795     www      6966: .LC_AboutMe_Image {
1.911     bisitz   6967:   float:left;
                   6968:   margin-right:10px;
1.747     neumanie 6969: }
1.795     www      6970: 
                   6971: .LC_Clear_AboutMe_Image {
1.911     bisitz   6972:   clear:left;
1.747     neumanie 6973: }
1.795     www      6974: 
1.721     harmsja  6975: dl.LC_ListStyleClean dt {
1.911     bisitz   6976:   padding-right: 5px;
                   6977:   display: table-header-group;
1.693     droeschl 6978: }
                   6979: 
1.721     harmsja  6980: dl.LC_ListStyleClean dd {
1.911     bisitz   6981:   display: table-row;
1.693     droeschl 6982: }
                   6983: 
1.721     harmsja  6984: .LC_ListStyleClean,
                   6985: .LC_ListStyleSimple,
                   6986: .LC_ListStyleNormal,
1.795     www      6987: .LC_ListStyleSpecial {
1.911     bisitz   6988:   /* display:block; */
                   6989:   list-style-position: inside;
                   6990:   list-style-type: none;
                   6991:   overflow: hidden;
                   6992:   padding: 0;
1.693     droeschl 6993: }
                   6994: 
1.721     harmsja  6995: .LC_ListStyleSimple li,
                   6996: .LC_ListStyleSimple dd,
                   6997: .LC_ListStyleNormal li,
                   6998: .LC_ListStyleNormal dd,
                   6999: .LC_ListStyleSpecial li,
1.795     www      7000: .LC_ListStyleSpecial dd {
1.911     bisitz   7001:   margin: 0;
                   7002:   padding: 5px 5px 5px 10px;
                   7003:   clear: both;
1.693     droeschl 7004: }
                   7005: 
1.721     harmsja  7006: .LC_ListStyleClean li,
                   7007: .LC_ListStyleClean dd {
1.911     bisitz   7008:   padding-top: 0;
                   7009:   padding-bottom: 0;
1.693     droeschl 7010: }
                   7011: 
1.721     harmsja  7012: .LC_ListStyleSimple dd,
1.795     www      7013: .LC_ListStyleSimple li {
1.911     bisitz   7014:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7015: }
                   7016: 
1.721     harmsja  7017: .LC_ListStyleSpecial li,
                   7018: .LC_ListStyleSpecial dd {
1.911     bisitz   7019:   list-style-type: none;
                   7020:   background-color: RGB(220, 220, 220);
                   7021:   margin-bottom: 4px;
1.693     droeschl 7022: }
                   7023: 
1.721     harmsja  7024: table.LC_SimpleTable {
1.911     bisitz   7025:   margin:5px;
                   7026:   border:solid 1px $lg_border_color;
1.795     www      7027: }
1.693     droeschl 7028: 
1.721     harmsja  7029: table.LC_SimpleTable tr {
1.911     bisitz   7030:   padding: 0;
                   7031:   border:solid 1px $lg_border_color;
1.693     droeschl 7032: }
1.795     www      7033: 
                   7034: table.LC_SimpleTable thead {
1.911     bisitz   7035:   background:rgb(220,220,220);
1.693     droeschl 7036: }
                   7037: 
1.721     harmsja  7038: div.LC_columnSection {
1.911     bisitz   7039:   display: block;
                   7040:   clear: both;
                   7041:   overflow: hidden;
                   7042:   margin: 0;
1.693     droeschl 7043: }
                   7044: 
1.721     harmsja  7045: div.LC_columnSection>* {
1.911     bisitz   7046:   float: left;
                   7047:   margin: 10px 20px 10px 0;
                   7048:   overflow:hidden;
1.693     droeschl 7049: }
1.721     harmsja  7050: 
1.795     www      7051: table em {
1.911     bisitz   7052:   font-weight: bold;
                   7053:   font-style: normal;
1.748     schulted 7054: }
1.795     www      7055: 
1.779     bisitz   7056: table.LC_tableBrowseRes,
1.795     www      7057: table.LC_tableOfContent {
1.911     bisitz   7058:   border:none;
                   7059:   border-spacing: 1px;
                   7060:   padding: 3px;
                   7061:   background-color: #FFFFFF;
                   7062:   font-size: 90%;
1.753     droeschl 7063: }
1.789     droeschl 7064: 
1.911     bisitz   7065: table.LC_tableOfContent {
                   7066:   border-collapse: collapse;
1.789     droeschl 7067: }
                   7068: 
1.771     droeschl 7069: table.LC_tableBrowseRes a,
1.768     schulted 7070: table.LC_tableOfContent a {
1.911     bisitz   7071:   background-color: transparent;
                   7072:   text-decoration: none;
1.753     droeschl 7073: }
                   7074: 
1.795     www      7075: table.LC_tableOfContent img {
1.911     bisitz   7076:   border: none;
                   7077:   height: 1.3em;
                   7078:   vertical-align: text-bottom;
                   7079:   margin-right: 0.3em;
1.753     droeschl 7080: }
1.757     schulted 7081: 
1.795     www      7082: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7083:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7084: }
                   7085: 
1.795     www      7086: a#LC_content_toolbar_everything {
1.911     bisitz   7087:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7088: }
                   7089: 
1.795     www      7090: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7091:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7092: }
                   7093: 
1.795     www      7094: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7095:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7096: }
                   7097: 
1.795     www      7098: a#LC_content_toolbar_changefolder {
1.911     bisitz   7099:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7100: }
                   7101: 
1.795     www      7102: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7103:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7104: }
                   7105: 
1.1043    raeburn  7106: a#LC_content_toolbar_edittoplevel {
                   7107:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7108: }
                   7109: 
1.795     www      7110: ul#LC_toolbar li a:hover {
1.911     bisitz   7111:   background-position: bottom center;
1.757     schulted 7112: }
                   7113: 
1.795     www      7114: ul#LC_toolbar {
1.911     bisitz   7115:   padding: 0;
                   7116:   margin: 2px;
                   7117:   list-style:none;
                   7118:   position:relative;
                   7119:   background-color:white;
1.1082    raeburn  7120:   overflow: auto;
1.757     schulted 7121: }
                   7122: 
1.795     www      7123: ul#LC_toolbar li {
1.911     bisitz   7124:   border:1px solid white;
                   7125:   padding: 0;
                   7126:   margin: 0;
                   7127:   float: left;
                   7128:   display:inline;
                   7129:   vertical-align:middle;
1.1082    raeburn  7130:   white-space: nowrap;
1.911     bisitz   7131: }
1.757     schulted 7132: 
1.783     amueller 7133: 
1.795     www      7134: a.LC_toolbarItem {
1.911     bisitz   7135:   display:block;
                   7136:   padding: 0;
                   7137:   margin: 0;
                   7138:   height: 32px;
                   7139:   width: 32px;
                   7140:   color:white;
                   7141:   border: none;
                   7142:   background-repeat:no-repeat;
                   7143:   background-color:transparent;
1.757     schulted 7144: }
                   7145: 
1.915     droeschl 7146: ul.LC_funclist {
                   7147:     margin: 0;
                   7148:     padding: 0.5em 1em 0.5em 0;
                   7149: }
                   7150: 
1.933     droeschl 7151: ul.LC_funclist > li:first-child {
                   7152:     font-weight:bold; 
                   7153:     margin-left:0.8em;
                   7154: }
                   7155: 
1.915     droeschl 7156: ul.LC_funclist + ul.LC_funclist {
                   7157:     /* 
                   7158:        left border as a seperator if we have more than
                   7159:        one list 
                   7160:     */
                   7161:     border-left: 1px solid $sidebg;
                   7162:     /* 
                   7163:        this hides the left border behind the border of the 
                   7164:        outer box if element is wrapped to the next 'line' 
                   7165:     */
                   7166:     margin-left: -1px;
                   7167: }
                   7168: 
1.843     bisitz   7169: ul.LC_funclist li {
1.915     droeschl 7170:   display: inline;
1.782     bisitz   7171:   white-space: nowrap;
1.915     droeschl 7172:   margin: 0 0 0 25px;
                   7173:   line-height: 150%;
1.782     bisitz   7174: }
                   7175: 
1.974     wenzelju 7176: .LC_hidden {
                   7177:   display: none;
                   7178: }
                   7179: 
1.1030    www      7180: .LCmodal-overlay {
                   7181: 		position:fixed;
                   7182: 		top:0;
                   7183: 		right:0;
                   7184: 		bottom:0;
                   7185: 		left:0;
                   7186: 		height:100%;
                   7187: 		width:100%;
                   7188: 		margin:0;
                   7189: 		padding:0;
                   7190: 		background:#999;
                   7191: 		opacity:.75;
                   7192: 		filter: alpha(opacity=75);
                   7193: 		-moz-opacity: 0.75;
                   7194: 		z-index:101;
                   7195: }
                   7196: 
                   7197: * html .LCmodal-overlay {   
                   7198: 		position: absolute;
                   7199: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7200: }
                   7201: 
                   7202: .LCmodal-window {
                   7203: 		position:fixed;
                   7204: 		top:50%;
                   7205: 		left:50%;
                   7206: 		margin:0;
                   7207: 		padding:0;
                   7208: 		z-index:102;
                   7209: 	}
                   7210: 
                   7211: * html .LCmodal-window {
                   7212: 		position:absolute;
                   7213: }
                   7214: 
                   7215: .LCclose-window {
                   7216: 		position:absolute;
                   7217: 		width:32px;
                   7218: 		height:32px;
                   7219: 		right:8px;
                   7220: 		top:8px;
                   7221: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7222: 		text-indent:-99999px;
                   7223: 		overflow:hidden;
                   7224: 		cursor:pointer;
                   7225: }
                   7226: 
1.1100    raeburn  7227: /*
                   7228:   styles used by TTH when "Default set of options to pass to tth/m
                   7229:   when converting TeX" in course settings has been set
                   7230: 
                   7231:   option passed: -t
                   7232: 
                   7233: */
                   7234: 
                   7235: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7236: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7237: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7238: td div.norm {line-height:normal;}
                   7239: 
                   7240: /*
                   7241:   option passed -y3
                   7242: */
                   7243: 
                   7244: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7245: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7246: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7247: 
1.343     albertel 7248: END
                   7249: }
                   7250: 
1.306     albertel 7251: =pod
                   7252: 
                   7253: =item * &headtag()
                   7254: 
                   7255: Returns a uniform footer for LON-CAPA web pages.
                   7256: 
1.307     albertel 7257: Inputs: $title - optional title for the head
                   7258:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7259:         $args - optional arguments
1.319     albertel 7260:             force_register - if is true call registerurl so the remote is 
                   7261:                              informed
1.415     albertel 7262:             redirect       -> array ref of
                   7263:                                    1- seconds before redirect occurs
                   7264:                                    2- url to redirect to
                   7265:                                    3- whether the side effect should occur
1.315     albertel 7266:                            (side effect of setting 
                   7267:                                $env{'internal.head.redirect'} to the url 
                   7268:                                redirected too)
1.352     albertel 7269:             domain         -> force to color decorate a page for a specific
                   7270:                                domain
                   7271:             function       -> force usage of a specific rolish color scheme
                   7272:             bgcolor        -> override the default page bgcolor
1.460     albertel 7273:             no_auto_mt_title
                   7274:                            -> prevent &mt()ing the title arg
1.464     albertel 7275: 
1.306     albertel 7276: =cut
                   7277: 
                   7278: sub headtag {
1.313     albertel 7279:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7280:     
1.363     albertel 7281:     my $function = $args->{'function'} || &get_users_function();
                   7282:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7283:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7284:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7285:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7286: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7287: 		   #time(),
1.418     albertel 7288: 		   $env{'environment.color.timestamp'},
1.363     albertel 7289: 		   $function,$domain,$bgcolor);
                   7290: 
1.369     www      7291:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7292: 
1.308     albertel 7293:     my $result =
                   7294: 	'<head>'.
1.1160    raeburn  7295: 	&font_settings($args);
1.319     albertel 7296: 
1.1064    raeburn  7297:     my $inhibitprint = &print_suppression();
                   7298: 
1.461     albertel 7299:     if (!$args->{'frameset'}) {
                   7300: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7301:     }
1.962     droeschl 7302:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7303:         $result .= Apache::lonxml::display_title();
1.319     albertel 7304:     }
1.436     albertel 7305:     if (!$args->{'no_nav_bar'} 
                   7306: 	&& !$args->{'only_body'}
                   7307: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7308: 	$result .= &help_menu_js($httphost);
1.1032    www      7309:         $result.=&modal_window();
1.1038    www      7310:         $result.=&togglebox_script();
1.1034    www      7311:         $result.=&wishlist_window();
1.1041    www      7312:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7313:     } else {
                   7314:         if ($args->{'add_modal'}) {
                   7315:            $result.=&modal_window();
                   7316:         }
                   7317:         if ($args->{'add_wishlist'}) {
                   7318:            $result.=&wishlist_window();
                   7319:         }
1.1038    www      7320:         if ($args->{'add_togglebox'}) {
                   7321:            $result.=&togglebox_script();
                   7322:         }
1.1041    www      7323:         if ($args->{'add_progressbar'}) {
                   7324:            $result.=&LCprogressbarUpdate_script();
                   7325:         }
1.436     albertel 7326:     }
1.314     albertel 7327:     if (ref($args->{'redirect'})) {
1.414     albertel 7328: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7329: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7330: 	if (!$inhibit_continue) {
                   7331: 	    $env{'internal.head.redirect'} = $url;
                   7332: 	}
1.313     albertel 7333: 	$result.=<<ADDMETA
                   7334: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7335: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7336: ADDMETA
                   7337:     }
1.306     albertel 7338:     if (!defined($title)) {
                   7339: 	$title = 'The LearningOnline Network with CAPA';
                   7340:     }
1.460     albertel 7341:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7342:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7343: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7344:     if (!$args->{'frameset'}) {
                   7345:         $result .= ' /';
                   7346:     }
                   7347:     $result .= '>' 
1.1064    raeburn  7348:         .$inhibitprint
1.414     albertel 7349: 	.$head_extra;
1.1137    raeburn  7350:     if ($env{'browser.mobile'}) {
                   7351:         $result .= '
                   7352: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7353: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7354:     }
1.962     droeschl 7355:     return $result.'</head>';
1.306     albertel 7356: }
                   7357: 
                   7358: =pod
                   7359: 
1.340     albertel 7360: =item * &font_settings()
                   7361: 
                   7362: Returns neccessary <meta> to set the proper encoding
                   7363: 
1.1160    raeburn  7364: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7365: 
                   7366: =cut
                   7367: 
                   7368: sub font_settings {
1.1160    raeburn  7369:     my ($args) = @_;
1.340     albertel 7370:     my $headerstring='';
1.1160    raeburn  7371:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7372:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7373:         $headerstring.=
                   7374:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7375:         if (!$args->{'frameset'}) {
                   7376: 	    $headerstring.= ' /';
                   7377:         }
                   7378: 	$headerstring .= '>'."\n";
1.340     albertel 7379:     }
                   7380:     return $headerstring;
                   7381: }
                   7382: 
1.341     albertel 7383: =pod
                   7384: 
1.1064    raeburn  7385: =item * &print_suppression()
                   7386: 
                   7387: In course context returns css which causes the body to be blank when media="print",
                   7388: if printout generation is unavailable for the current resource.
                   7389: 
                   7390: This could be because:
                   7391: 
                   7392: (a) printstartdate is in the future
                   7393: 
                   7394: (b) printenddate is in the past
                   7395: 
                   7396: (c) there is an active exam block with "printout"
                   7397: functionality blocked
                   7398: 
                   7399: Users with pav, pfo or evb privileges are exempt.
                   7400: 
                   7401: Inputs: none
                   7402: 
                   7403: =cut
                   7404: 
                   7405: 
                   7406: sub print_suppression {
                   7407:     my $noprint;
                   7408:     if ($env{'request.course.id'}) {
                   7409:         my $scope = $env{'request.course.id'};
                   7410:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7411:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7412:             return;
                   7413:         }
                   7414:         if ($env{'request.course.sec'} ne '') {
                   7415:             $scope .= "/$env{'request.course.sec'}";
                   7416:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7417:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7418:                 return;
1.1064    raeburn  7419:             }
                   7420:         }
                   7421:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7422:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7423:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7424:         if ($blocked) {
                   7425:             my $checkrole = "cm./$cdom/$cnum";
                   7426:             if ($env{'request.course.sec'} ne '') {
                   7427:                 $checkrole .= "/$env{'request.course.sec'}";
                   7428:             }
                   7429:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7430:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7431:                 $noprint = 1;
                   7432:             }
                   7433:         }
                   7434:         unless ($noprint) {
                   7435:             my $symb = &Apache::lonnet::symbread();
                   7436:             if ($symb ne '') {
                   7437:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7438:                 if (ref($navmap)) {
                   7439:                     my $res = $navmap->getBySymb($symb);
                   7440:                     if (ref($res)) {
                   7441:                         if (!$res->resprintable()) {
                   7442:                             $noprint = 1;
                   7443:                         }
                   7444:                     }
                   7445:                 }
                   7446:             }
                   7447:         }
                   7448:         if ($noprint) {
                   7449:             return <<"ENDSTYLE";
                   7450: <style type="text/css" media="print">
                   7451:     body { display:none }
                   7452: </style>
                   7453: ENDSTYLE
                   7454:         }
                   7455:     }
                   7456:     return;
                   7457: }
                   7458: 
                   7459: =pod
                   7460: 
1.341     albertel 7461: =item * &xml_begin()
                   7462: 
                   7463: Returns the needed doctype and <html>
                   7464: 
                   7465: Inputs: none
                   7466: 
                   7467: =cut
                   7468: 
                   7469: sub xml_begin {
1.1168    raeburn  7470:     my ($is_frameset) = @_;
1.341     albertel 7471:     my $output='';
                   7472: 
                   7473:     if ($env{'browser.mathml'}) {
                   7474: 	$output='<?xml version="1.0"?>'
                   7475:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7476: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7477:             
                   7478: #	    .'<!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">] >'
                   7479: 	    .'<!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">'
                   7480:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7481: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  7482:     } elsif ($is_frameset) {
                   7483:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7484:                 '<html>'."\n";
1.341     albertel 7485:     } else {
1.1168    raeburn  7486: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7487:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7488:     }
                   7489:     return $output;
                   7490: }
1.340     albertel 7491: 
                   7492: =pod
                   7493: 
1.306     albertel 7494: =item * &start_page()
                   7495: 
                   7496: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7497: 
1.648     raeburn  7498: Inputs:
                   7499: 
                   7500: =over 4
                   7501: 
                   7502: $title - optional title for the page
                   7503: 
                   7504: $head_extra - optional extra HTML to incude inside the <head>
                   7505: 
                   7506: $args - additional optional args supported are:
                   7507: 
                   7508: =over 8
                   7509: 
                   7510:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7511:                                     arg on
1.814     bisitz   7512:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7513:              add_entries    -> additional attributes to add to the  <body>
                   7514:              domain         -> force to color decorate a page for a 
1.317     albertel 7515:                                     specific domain
1.648     raeburn  7516:              function       -> force usage of a specific rolish color
1.317     albertel 7517:                                     scheme
1.648     raeburn  7518:              redirect       -> see &headtag()
                   7519:              bgcolor        -> override the default page bg color
                   7520:              js_ready       -> return a string ready for being used in 
1.317     albertel 7521:                                     a javascript writeln
1.648     raeburn  7522:              html_encode    -> return a string ready for being used in 
1.320     albertel 7523:                                     a html attribute
1.648     raeburn  7524:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7525:                                     $forcereg arg
1.648     raeburn  7526:              frameset       -> if true will start with a <frameset>
1.330     albertel 7527:                                     rather than <body>
1.648     raeburn  7528:              skip_phases    -> hash ref of 
1.338     albertel 7529:                                     head -> skip the <html><head> generation
                   7530:                                     body -> skip all <body> generation
1.648     raeburn  7531:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7532:              inherit_jsmath -> when creating popup window in a page,
                   7533:                                     should it have jsmath forced on by the
                   7534:                                     current page
1.867     kalberla 7535:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7536:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7537:              group          -> includes the current group, if page is for a 
                   7538:                                specific group  
1.361     albertel 7539: 
1.648     raeburn  7540: =back
1.460     albertel 7541: 
1.648     raeburn  7542: =back
1.562     albertel 7543: 
1.306     albertel 7544: =cut
                   7545: 
                   7546: sub start_page {
1.309     albertel 7547:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7548:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7549: 
1.315     albertel 7550:     $env{'internal.start_page'}++;
1.1096    raeburn  7551:     my ($result,@advtools);
1.964     droeschl 7552: 
1.338     albertel 7553:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  7554:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 7555:     }
                   7556:     
                   7557:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7558: 	if ($args->{'frameset'}) {
                   7559: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7560: 						$args->{'add_entries'});
                   7561: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7562:         } else {
                   7563:             $result .=
                   7564:                 &bodytag($title, 
                   7565:                          $args->{'function'},       $args->{'add_entries'},
                   7566:                          $args->{'only_body'},      $args->{'domain'},
                   7567:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  7568:                          $args->{'bgcolor'},        $args,
                   7569:                          \@advtools);
1.831     bisitz   7570:         }
1.330     albertel 7571:     }
1.338     albertel 7572: 
1.315     albertel 7573:     if ($args->{'js_ready'}) {
1.713     kaisler  7574: 		$result = &js_ready($result);
1.315     albertel 7575:     }
1.320     albertel 7576:     if ($args->{'html_encode'}) {
1.713     kaisler  7577: 		$result = &html_encode($result);
                   7578:     }
                   7579: 
1.813     bisitz   7580:     # Preparation for new and consistent functionlist at top of screen
                   7581:     # if ($args->{'functionlist'}) {
                   7582:     #            $result .= &build_functionlist();
                   7583:     #}
                   7584: 
1.964     droeschl 7585:     # Don't add anything more if only_body wanted or in const space
                   7586:     return $result if    $args->{'only_body'} 
                   7587:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7588: 
                   7589:     #Breadcrumbs
1.758     kaisler  7590:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7591: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7592: 		#if any br links exists, add them to the breadcrumbs
                   7593: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7594: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7595: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7596: 			}
                   7597: 		}
1.1096    raeburn  7598:                 # if @advtools array contains items add then to the breadcrumbs
                   7599:                 if (@advtools > 0) {
                   7600:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7601:                 }
1.758     kaisler  7602: 
                   7603: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7604: 		if(exists($args->{'bread_crumbs_component'})){
                   7605: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7606: 		}else{
                   7607: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7608: 		}
1.320     albertel 7609:     }
1.315     albertel 7610:     return $result;
1.306     albertel 7611: }
                   7612: 
                   7613: sub end_page {
1.315     albertel 7614:     my ($args) = @_;
                   7615:     $env{'internal.end_page'}++;
1.330     albertel 7616:     my $result;
1.335     albertel 7617:     if ($args->{'discussion'}) {
                   7618: 	my ($target,$parser);
                   7619: 	if (ref($args->{'discussion'})) {
                   7620: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7621: 				$args->{'discussion'}{'parser'});
                   7622: 	}
                   7623: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7624:     }
1.330     albertel 7625:     if ($args->{'frameset'}) {
                   7626: 	$result .= '</frameset>';
                   7627:     } else {
1.635     raeburn  7628: 	$result .= &endbodytag($args);
1.330     albertel 7629:     }
1.1080    raeburn  7630:     unless ($args->{'notbody'}) {
                   7631:         $result .= "\n</html>";
                   7632:     }
1.330     albertel 7633: 
1.315     albertel 7634:     if ($args->{'js_ready'}) {
1.317     albertel 7635: 	$result = &js_ready($result);
1.315     albertel 7636:     }
1.335     albertel 7637: 
1.320     albertel 7638:     if ($args->{'html_encode'}) {
                   7639: 	$result = &html_encode($result);
                   7640:     }
1.335     albertel 7641: 
1.315     albertel 7642:     return $result;
                   7643: }
                   7644: 
1.1034    www      7645: sub wishlist_window {
                   7646:     return(<<'ENDWISHLIST');
1.1046    raeburn  7647: <script type="text/javascript">
1.1034    www      7648: // <![CDATA[
                   7649: // <!-- BEGIN LON-CAPA Internal
                   7650: function set_wishlistlink(title, path) {
                   7651:     if (!title) {
                   7652:         title = document.title;
                   7653:         title = title.replace(/^LON-CAPA /,'');
                   7654:     }
                   7655:     if (!path) {
                   7656:         path = location.pathname;
                   7657:     }
                   7658:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7659:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7660: }
                   7661: // END LON-CAPA Internal -->
                   7662: // ]]>
                   7663: </script>
                   7664: ENDWISHLIST
                   7665: }
                   7666: 
1.1030    www      7667: sub modal_window {
                   7668:     return(<<'ENDMODAL');
1.1046    raeburn  7669: <script type="text/javascript">
1.1030    www      7670: // <![CDATA[
                   7671: // <!-- BEGIN LON-CAPA Internal
                   7672: var modalWindow = {
                   7673: 	parent:"body",
                   7674: 	windowId:null,
                   7675: 	content:null,
                   7676: 	width:null,
                   7677: 	height:null,
                   7678: 	close:function()
                   7679: 	{
                   7680: 	        $(".LCmodal-window").remove();
                   7681: 	        $(".LCmodal-overlay").remove();
                   7682: 	},
                   7683: 	open:function()
                   7684: 	{
                   7685: 		var modal = "";
                   7686: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7687: 		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;\">";
                   7688: 		modal += this.content;
                   7689: 		modal += "</div>";	
                   7690: 
                   7691: 		$(this.parent).append(modal);
                   7692: 
                   7693: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7694: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7695: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7696: 	}
                   7697: };
1.1140    raeburn  7698: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      7699: 	{
                   7700: 		modalWindow.windowId = "myModal";
                   7701: 		modalWindow.width = width;
                   7702: 		modalWindow.height = height;
1.1140    raeburn  7703: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
1.1030    www      7704: 		modalWindow.open();
                   7705: 	};	
                   7706: // END LON-CAPA Internal -->
                   7707: // ]]>
                   7708: </script>
                   7709: ENDMODAL
                   7710: }
                   7711: 
                   7712: sub modal_link {
1.1140    raeburn  7713:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      7714:     unless ($width) { $width=480; }
                   7715:     unless ($height) { $height=400; }
1.1031    www      7716:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  7717:     unless ($transparency) { $transparency='true'; }
                   7718: 
1.1074    raeburn  7719:     my $target_attr;
                   7720:     if (defined($target)) {
                   7721:         $target_attr = 'target="'.$target.'"';
                   7722:     }
                   7723:     return <<"ENDLINK";
1.1140    raeburn  7724: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  7725:            $linktext</a>
                   7726: ENDLINK
1.1030    www      7727: }
                   7728: 
1.1032    www      7729: sub modal_adhoc_script {
                   7730:     my ($funcname,$width,$height,$content)=@_;
                   7731:     return (<<ENDADHOC);
1.1046    raeburn  7732: <script type="text/javascript">
1.1032    www      7733: // <![CDATA[
                   7734:         var $funcname = function()
                   7735:         {
                   7736:                 modalWindow.windowId = "myModal";
                   7737:                 modalWindow.width = $width;
                   7738:                 modalWindow.height = $height;
                   7739:                 modalWindow.content = '$content';
                   7740:                 modalWindow.open();
                   7741:         };  
                   7742: // ]]>
                   7743: </script>
                   7744: ENDADHOC
                   7745: }
                   7746: 
1.1041    www      7747: sub modal_adhoc_inner {
                   7748:     my ($funcname,$width,$height,$content)=@_;
                   7749:     my $innerwidth=$width-20;
                   7750:     $content=&js_ready(
1.1140    raeburn  7751:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   7752:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   7753:                  $content.
1.1041    www      7754:                  &end_scrollbox().
1.1140    raeburn  7755:                  &end_page()
1.1041    www      7756:              );
                   7757:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7758: }
                   7759: 
                   7760: sub modal_adhoc_window {
                   7761:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7762:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7763:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7764: }
                   7765: 
                   7766: sub modal_adhoc_launch {
                   7767:     my ($funcname,$width,$height,$content)=@_;
                   7768:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7769: <script type="text/javascript">
                   7770: // <![CDATA[
                   7771: $funcname();
                   7772: // ]]>
                   7773: </script>
                   7774: ENDLAUNCH
                   7775: }
                   7776: 
                   7777: sub modal_adhoc_close {
                   7778:     return (<<ENDCLOSE);
                   7779: <script type="text/javascript">
                   7780: // <![CDATA[
                   7781: modalWindow.close();
                   7782: // ]]>
                   7783: </script>
                   7784: ENDCLOSE
                   7785: }
                   7786: 
1.1038    www      7787: sub togglebox_script {
                   7788:    return(<<ENDTOGGLE);
                   7789: <script type="text/javascript"> 
                   7790: // <![CDATA[
                   7791: function LCtoggleDisplay(id,hidetext,showtext) {
                   7792:    link = document.getElementById(id + "link").childNodes[0];
                   7793:    with (document.getElementById(id).style) {
                   7794:       if (display == "none" ) {
                   7795:           display = "inline";
                   7796:           link.nodeValue = hidetext;
                   7797:         } else {
                   7798:           display = "none";
                   7799:           link.nodeValue = showtext;
                   7800:        }
                   7801:    }
                   7802: }
                   7803: // ]]>
                   7804: </script>
                   7805: ENDTOGGLE
                   7806: }
                   7807: 
1.1039    www      7808: sub start_togglebox {
                   7809:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7810:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7811:     unless ($showtext) { $showtext=&mt('show'); }
                   7812:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7813:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7814:     return &start_data_table().
                   7815:            &start_data_table_header_row().
                   7816:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7817:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7818:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7819:            &end_data_table_header_row().
                   7820:            '<tr id="'.$id.'" style="display:none""><td>';
                   7821: }
                   7822: 
                   7823: sub end_togglebox {
                   7824:     return '</td></tr>'.&end_data_table();
                   7825: }
                   7826: 
1.1041    www      7827: sub LCprogressbar_script {
1.1045    www      7828:    my ($id)=@_;
1.1041    www      7829:    return(<<ENDPROGRESS);
                   7830: <script type="text/javascript">
                   7831: // <![CDATA[
1.1045    www      7832: \$('#progressbar$id').progressbar({
1.1041    www      7833:   value: 0,
                   7834:   change: function(event, ui) {
                   7835:     var newVal = \$(this).progressbar('option', 'value');
                   7836:     \$('.pblabel', this).text(LCprogressTxt);
                   7837:   }
                   7838: });
                   7839: // ]]>
                   7840: </script>
                   7841: ENDPROGRESS
                   7842: }
                   7843: 
                   7844: sub LCprogressbarUpdate_script {
                   7845:    return(<<ENDPROGRESSUPDATE);
                   7846: <style type="text/css">
                   7847: .ui-progressbar { position:relative; }
                   7848: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7849: </style>
                   7850: <script type="text/javascript">
                   7851: // <![CDATA[
1.1045    www      7852: var LCprogressTxt='---';
                   7853: 
                   7854: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7855:    LCprogressTxt=progresstext;
1.1045    www      7856:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7857: }
                   7858: // ]]>
                   7859: </script>
                   7860: ENDPROGRESSUPDATE
                   7861: }
                   7862: 
1.1042    www      7863: my $LClastpercent;
1.1045    www      7864: my $LCidcnt;
                   7865: my $LCcurrentid;
1.1042    www      7866: 
1.1041    www      7867: sub LCprogressbar {
1.1042    www      7868:     my ($r)=(@_);
                   7869:     $LClastpercent=0;
1.1045    www      7870:     $LCidcnt++;
                   7871:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7872:     my $starting=&mt('Starting');
                   7873:     my $content=(<<ENDPROGBAR);
1.1045    www      7874:   <div id="progressbar$LCcurrentid">
1.1041    www      7875:     <span class="pblabel">$starting</span>
                   7876:   </div>
                   7877: ENDPROGBAR
1.1045    www      7878:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7879: }
                   7880: 
                   7881: sub LCprogressbarUpdate {
1.1042    www      7882:     my ($r,$val,$text)=@_;
                   7883:     unless ($val) { 
                   7884:        if ($LClastpercent) {
                   7885:            $val=$LClastpercent;
                   7886:        } else {
                   7887:            $val=0;
                   7888:        }
                   7889:     }
1.1041    www      7890:     if ($val<0) { $val=0; }
                   7891:     if ($val>100) { $val=0; }
1.1042    www      7892:     $LClastpercent=$val;
1.1041    www      7893:     unless ($text) { $text=$val.'%'; }
                   7894:     $text=&js_ready($text);
1.1044    www      7895:     &r_print($r,<<ENDUPDATE);
1.1041    www      7896: <script type="text/javascript">
                   7897: // <![CDATA[
1.1045    www      7898: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7899: // ]]>
                   7900: </script>
                   7901: ENDUPDATE
1.1035    www      7902: }
                   7903: 
1.1042    www      7904: sub LCprogressbarClose {
                   7905:     my ($r)=@_;
                   7906:     $LClastpercent=0;
1.1044    www      7907:     &r_print($r,<<ENDCLOSE);
1.1042    www      7908: <script type="text/javascript">
                   7909: // <![CDATA[
1.1045    www      7910: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7911: // ]]>
                   7912: </script>
                   7913: ENDCLOSE
1.1044    www      7914: }
                   7915: 
                   7916: sub r_print {
                   7917:     my ($r,$to_print)=@_;
                   7918:     if ($r) {
                   7919:       $r->print($to_print);
                   7920:       $r->rflush();
                   7921:     } else {
                   7922:       print($to_print);
                   7923:     }
1.1042    www      7924: }
                   7925: 
1.320     albertel 7926: sub html_encode {
                   7927:     my ($result) = @_;
                   7928: 
1.322     albertel 7929:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7930:     
                   7931:     return $result;
                   7932: }
1.1044    www      7933: 
1.317     albertel 7934: sub js_ready {
                   7935:     my ($result) = @_;
                   7936: 
1.323     albertel 7937:     $result =~ s/[\n\r]/ /xmsg;
                   7938:     $result =~ s/\\/\\\\/xmsg;
                   7939:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7940:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7941:     
                   7942:     return $result;
                   7943: }
                   7944: 
1.315     albertel 7945: sub validate_page {
                   7946:     if (  exists($env{'internal.start_page'})
1.316     albertel 7947: 	  &&     $env{'internal.start_page'} > 1) {
                   7948: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7949: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7950: 				 $ENV{'request.filename'});
1.315     albertel 7951:     }
                   7952:     if (  exists($env{'internal.end_page'})
1.316     albertel 7953: 	  &&     $env{'internal.end_page'} > 1) {
                   7954: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7955: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7956: 				 $env{'request.filename'});
1.315     albertel 7957:     }
                   7958:     if (     exists($env{'internal.start_page'})
                   7959: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7960: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7961: 				 $env{'request.filename'});
1.315     albertel 7962:     }
                   7963:     if (   ! exists($env{'internal.start_page'})
                   7964: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7965: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7966: 				 $env{'request.filename'});
1.315     albertel 7967:     }
1.306     albertel 7968: }
1.315     albertel 7969: 
1.996     www      7970: 
                   7971: sub start_scrollbox {
1.1140    raeburn  7972:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  7973:     unless ($outerwidth) { $outerwidth='520px'; }
                   7974:     unless ($width) { $width='500px'; }
                   7975:     unless ($height) { $height='200px'; }
1.1075    raeburn  7976:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7977:     if ($id ne '') {
1.1140    raeburn  7978:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  7979:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  7980:     }
1.1075    raeburn  7981:     if ($bgcolor ne '') {
                   7982:         $tdcol = "background-color: $bgcolor;";
                   7983:     }
1.1137    raeburn  7984:     my $nicescroll_js;
                   7985:     if ($env{'browser.mobile'}) {
1.1140    raeburn  7986:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   7987:     }
                   7988:     return <<"END";
                   7989: $nicescroll_js
                   7990: 
                   7991: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   7992: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   7993: END
                   7994: }
                   7995: 
                   7996: sub end_scrollbox {
                   7997:     return '</div></td></tr></table>';
                   7998: }
                   7999: 
                   8000: sub nicescroll_javascript {
                   8001:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8002:     my %options;
                   8003:     if (ref($cursor) eq 'HASH') {
                   8004:         %options = %{$cursor};
                   8005:     }
                   8006:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8007:         $options{'railalign'} = 'left';
                   8008:     }
                   8009:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8010:         my $function  = &get_users_function();
                   8011:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8012:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8013:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8014:         }
1.1140    raeburn  8015:     }
                   8016:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8017:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8018:             $options{'cursoropacity'}='1.0';
                   8019:         }
1.1140    raeburn  8020:     } else {
                   8021:         $options{'cursoropacity'}='1.0';
                   8022:     }
                   8023:     if ($options{'cursorfixedheight'} eq 'none') {
                   8024:         delete($options{'cursorfixedheight'});
                   8025:     } else {
                   8026:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8027:     }
                   8028:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8029:         delete($options{'railoffset'});
                   8030:     }
                   8031:     my @niceoptions;
                   8032:     while (my($key,$value) = each(%options)) {
                   8033:         if ($value =~ /^\{.+\}$/) {
                   8034:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8035:         } else {
1.1140    raeburn  8036:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8037:         }
1.1140    raeburn  8038:     }
                   8039:     my $nicescroll_js = '
1.1137    raeburn  8040: $(document).ready(
1.1140    raeburn  8041:       function() {
                   8042:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8043:       }
1.1137    raeburn  8044: );
                   8045: ';
1.1140    raeburn  8046:     if ($framecheck) {
                   8047:         $nicescroll_js .= '
                   8048: function expand_div(caller) {
                   8049:     if (top === self) {
                   8050:         document.getElementById("'.$id.'").style.width = "auto";
                   8051:         document.getElementById("'.$id.'").style.height = "auto";
                   8052:     } else {
                   8053:         try {
                   8054:             if (parent.frames) {
                   8055:                 if (parent.frames.length > 1) {
                   8056:                     var framesrc = parent.frames[1].location.href;
                   8057:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8058:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8059:                         document.getElementById("'.$id.'").style.width = "auto";
                   8060:                         document.getElementById("'.$id.'").style.height = "auto";
                   8061:                     }
                   8062:                 }
                   8063:             }
                   8064:         } catch (e) {
                   8065:             return;
                   8066:         }
1.1137    raeburn  8067:     }
1.1140    raeburn  8068:     return;
1.996     www      8069: }
1.1140    raeburn  8070: ';
                   8071:     }
                   8072:     if ($needjsready) {
                   8073:         $nicescroll_js = '
                   8074: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8075:     } else {
                   8076:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8077:     }
                   8078:     return $nicescroll_js;
1.996     www      8079: }
                   8080: 
1.318     albertel 8081: sub simple_error_page {
1.1150    bisitz   8082:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8083:     if (ref($args) eq 'HASH') {
                   8084:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8085:     } else {
                   8086:         $msg = &mt($msg);
                   8087:     }
1.1150    bisitz   8088: 
1.318     albertel 8089:     my $page =
                   8090: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8091: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8092: 	&Apache::loncommon::end_page();
                   8093:     if (ref($r)) {
                   8094: 	$r->print($page);
1.327     albertel 8095: 	return;
1.318     albertel 8096:     }
                   8097:     return $page;
                   8098: }
1.347     albertel 8099: 
                   8100: {
1.610     albertel 8101:     my @row_count;
1.961     onken    8102: 
                   8103:     sub start_data_table_count {
                   8104:         unshift(@row_count, 0);
                   8105:         return;
                   8106:     }
                   8107: 
                   8108:     sub end_data_table_count {
                   8109:         shift(@row_count);
                   8110:         return;
                   8111:     }
                   8112: 
1.347     albertel 8113:     sub start_data_table {
1.1018    raeburn  8114: 	my ($add_class,$id) = @_;
1.422     albertel 8115: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8116:         my $table_id;
                   8117:         if (defined($id)) {
                   8118:             $table_id = ' id="'.$id.'"';
                   8119:         }
1.961     onken    8120: 	&start_data_table_count();
1.1018    raeburn  8121: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8122:     }
                   8123: 
                   8124:     sub end_data_table {
1.961     onken    8125: 	&end_data_table_count();
1.389     albertel 8126: 	return '</table>'."\n";;
1.347     albertel 8127:     }
                   8128: 
                   8129:     sub start_data_table_row {
1.974     wenzelju 8130: 	my ($add_class, $id) = @_;
1.610     albertel 8131: 	$row_count[0]++;
                   8132: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8133: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8134:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8135:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8136:     }
1.471     banghart 8137:     
                   8138:     sub continue_data_table_row {
1.974     wenzelju 8139: 	my ($add_class, $id) = @_;
1.610     albertel 8140: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8141: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8142:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8143:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8144:     }
1.347     albertel 8145: 
                   8146:     sub end_data_table_row {
1.389     albertel 8147: 	return '</tr>'."\n";;
1.347     albertel 8148:     }
1.367     www      8149: 
1.421     albertel 8150:     sub start_data_table_empty_row {
1.707     bisitz   8151: #	$row_count[0]++;
1.421     albertel 8152: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8153:     }
                   8154: 
                   8155:     sub end_data_table_empty_row {
                   8156: 	return '</tr>'."\n";;
                   8157:     }
                   8158: 
1.367     www      8159:     sub start_data_table_header_row {
1.389     albertel 8160: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8161:     }
                   8162: 
                   8163:     sub end_data_table_header_row {
1.389     albertel 8164: 	return '</tr>'."\n";;
1.367     www      8165:     }
1.890     droeschl 8166: 
                   8167:     sub data_table_caption {
                   8168:         my $caption = shift;
                   8169:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8170:     }
1.347     albertel 8171: }
                   8172: 
1.548     albertel 8173: =pod
                   8174: 
                   8175: =item * &inhibit_menu_check($arg)
                   8176: 
                   8177: Checks for a inhibitmenu state and generates output to preserve it
                   8178: 
                   8179: Inputs:         $arg - can be any of
                   8180:                      - undef - in which case the return value is a string 
                   8181:                                to add  into arguments list of a uri
                   8182:                      - 'input' - in which case the return value is a HTML
                   8183:                                  <form> <input> field of type hidden to
                   8184:                                  preserve the value
                   8185:                      - a url - in which case the return value is the url with
                   8186:                                the neccesary cgi args added to preserve the
                   8187:                                inhibitmenu state
                   8188:                      - a ref to a url - no return value, but the string is
                   8189:                                         updated to include the neccessary cgi
                   8190:                                         args to preserve the inhibitmenu state
                   8191: 
                   8192: =cut
                   8193: 
                   8194: sub inhibit_menu_check {
                   8195:     my ($arg) = @_;
                   8196:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8197:     if ($arg eq 'input') {
                   8198: 	if ($env{'form.inhibitmenu'}) {
                   8199: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8200: 	} else {
                   8201: 	    return
                   8202: 	}
                   8203:     }
                   8204:     if ($env{'form.inhibitmenu'}) {
                   8205: 	if (ref($arg)) {
                   8206: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8207: 	} elsif ($arg eq '') {
                   8208: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8209: 	} else {
                   8210: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8211: 	}
                   8212:     }
                   8213:     if (!ref($arg)) {
                   8214: 	return $arg;
                   8215:     }
                   8216: }
                   8217: 
1.251     albertel 8218: ###############################################
1.182     matthew  8219: 
                   8220: =pod
                   8221: 
1.549     albertel 8222: =back
                   8223: 
                   8224: =head1 User Information Routines
                   8225: 
                   8226: =over 4
                   8227: 
1.405     albertel 8228: =item * &get_users_function()
1.182     matthew  8229: 
                   8230: Used by &bodytag to determine the current users primary role.
                   8231: Returns either 'student','coordinator','admin', or 'author'.
                   8232: 
                   8233: =cut
                   8234: 
                   8235: ###############################################
                   8236: sub get_users_function {
1.815     tempelho 8237:     my $function = 'norole';
1.818     tempelho 8238:     if ($env{'request.role'}=~/^(st)/) {
                   8239:         $function='student';
                   8240:     }
1.907     raeburn  8241:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8242:         $function='coordinator';
                   8243:     }
1.258     albertel 8244:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8245:         $function='admin';
                   8246:     }
1.826     bisitz   8247:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8248:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8249:         $function='author';
                   8250:     }
                   8251:     return $function;
1.54      www      8252: }
1.99      www      8253: 
                   8254: ###############################################
                   8255: 
1.233     raeburn  8256: =pod
                   8257: 
1.821     raeburn  8258: =item * &show_course()
                   8259: 
                   8260: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8261: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8262: 
                   8263: Inputs:
                   8264: None
                   8265: 
                   8266: Outputs:
                   8267: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8268: 
                   8269: =cut
                   8270: 
                   8271: ###############################################
                   8272: sub show_course {
                   8273:     my $course = !$env{'user.adv'};
                   8274:     if (!$env{'user.adv'}) {
                   8275:         foreach my $env (keys(%env)) {
                   8276:             next if ($env !~ m/^user\.priv\./);
                   8277:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8278:                 $course = 0;
                   8279:                 last;
                   8280:             }
                   8281:         }
                   8282:     }
                   8283:     return $course;
                   8284: }
                   8285: 
                   8286: ###############################################
                   8287: 
                   8288: =pod
                   8289: 
1.542     raeburn  8290: =item * &check_user_status()
1.274     raeburn  8291: 
                   8292: Determines current status of supplied role for a
                   8293: specific user. Roles can be active, previous or future.
                   8294: 
                   8295: Inputs: 
                   8296: user's domain, user's username, course's domain,
1.375     raeburn  8297: course's number, optional section ID.
1.274     raeburn  8298: 
                   8299: Outputs:
                   8300: role status: active, previous or future. 
                   8301: 
                   8302: =cut
                   8303: 
                   8304: sub check_user_status {
1.412     raeburn  8305:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8306:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8307:     my @uroles = keys %userinfo;
                   8308:     my $srchstr;
                   8309:     my $active_chk = 'none';
1.412     raeburn  8310:     my $now = time;
1.274     raeburn  8311:     if (@uroles > 0) {
1.908     raeburn  8312:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8313:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8314:         } else {
1.412     raeburn  8315:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8316:         }
                   8317:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8318:             my $role_end = 0;
                   8319:             my $role_start = 0;
                   8320:             $active_chk = 'active';
1.412     raeburn  8321:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8322:                 $role_end = $1;
                   8323:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8324:                     $role_start = $1;
1.274     raeburn  8325:                 }
                   8326:             }
                   8327:             if ($role_start > 0) {
1.412     raeburn  8328:                 if ($now < $role_start) {
1.274     raeburn  8329:                     $active_chk = 'future';
                   8330:                 }
                   8331:             }
                   8332:             if ($role_end > 0) {
1.412     raeburn  8333:                 if ($now > $role_end) {
1.274     raeburn  8334:                     $active_chk = 'previous';
                   8335:                 }
                   8336:             }
                   8337:         }
                   8338:     }
                   8339:     return $active_chk;
                   8340: }
                   8341: 
                   8342: ###############################################
                   8343: 
                   8344: =pod
                   8345: 
1.405     albertel 8346: =item * &get_sections()
1.233     raeburn  8347: 
                   8348: Determines all the sections for a course including
                   8349: sections with students and sections containing other roles.
1.419     raeburn  8350: Incoming parameters: 
                   8351: 
                   8352: 1. domain
                   8353: 2. course number 
                   8354: 3. reference to array containing roles for which sections should 
                   8355: be gathered (optional).
                   8356: 4. reference to array containing status types for which sections 
                   8357: should be gathered (optional).
                   8358: 
                   8359: If the third argument is undefined, sections are gathered for any role. 
                   8360: If the fourth argument is undefined, sections are gathered for any status.
                   8361: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8362:  
1.374     raeburn  8363: Returns section hash (keys are section IDs, values are
                   8364: number of users in each section), subject to the
1.419     raeburn  8365: optional roles filter, optional status filter 
1.233     raeburn  8366: 
                   8367: =cut
                   8368: 
                   8369: ###############################################
                   8370: sub get_sections {
1.419     raeburn  8371:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8372:     if (!defined($cdom) || !defined($cnum)) {
                   8373:         my $cid =  $env{'request.course.id'};
                   8374: 
                   8375: 	return if (!defined($cid));
                   8376: 
                   8377:         $cdom = $env{'course.'.$cid.'.domain'};
                   8378:         $cnum = $env{'course.'.$cid.'.num'};
                   8379:     }
                   8380: 
                   8381:     my %sectioncount;
1.419     raeburn  8382:     my $now = time;
1.240     albertel 8383: 
1.1118    raeburn  8384:     my $check_students = 1;
                   8385:     my $only_students = 0;
                   8386:     if (ref($possible_roles) eq 'ARRAY') {
                   8387:         if (grep(/^st$/,@{$possible_roles})) {
                   8388:             if (@{$possible_roles} == 1) {
                   8389:                 $only_students = 1;
                   8390:             }
                   8391:         } else {
                   8392:             $check_students = 0;
                   8393:         }
                   8394:     }
                   8395: 
                   8396:     if ($check_students) { 
1.276     albertel 8397: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8398: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8399: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8400:         my $start_index = &Apache::loncoursedata::CL_START();
                   8401:         my $end_index = &Apache::loncoursedata::CL_END();
                   8402:         my $status;
1.366     albertel 8403: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8404: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8405: 				                     $data->[$status_index],
                   8406:                                                      $data->[$start_index],
                   8407:                                                      $data->[$end_index]);
                   8408:             if ($stu_status eq 'Active') {
                   8409:                 $status = 'active';
                   8410:             } elsif ($end < $now) {
                   8411:                 $status = 'previous';
                   8412:             } elsif ($start > $now) {
                   8413:                 $status = 'future';
                   8414:             } 
                   8415: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8416:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8417:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8418: 		    $sectioncount{$section}++;
                   8419:                 }
1.240     albertel 8420: 	    }
                   8421: 	}
                   8422:     }
1.1118    raeburn  8423:     if ($only_students) {
                   8424:         return %sectioncount;
                   8425:     }
1.240     albertel 8426:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8427:     foreach my $user (sort(keys(%courseroles))) {
                   8428: 	if ($user !~ /^(\w{2})/) { next; }
                   8429: 	my ($role) = ($user =~ /^(\w{2})/);
                   8430: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8431: 	my ($section,$status);
1.240     albertel 8432: 	if ($role eq 'cr' &&
                   8433: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8434: 	    $section=$1;
                   8435: 	}
                   8436: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8437: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8438:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8439:         if ($end == -1 && $start == -1) {
                   8440:             next; #deleted role
                   8441:         }
                   8442:         if (!defined($possible_status)) { 
                   8443:             $sectioncount{$section}++;
                   8444:         } else {
                   8445:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8446:                 $status = 'active';
                   8447:             } elsif ($end < $now) {
                   8448:                 $status = 'future';
                   8449:             } elsif ($start > $now) {
                   8450:                 $status = 'previous';
                   8451:             }
                   8452:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8453:                 $sectioncount{$section}++;
                   8454:             }
                   8455:         }
1.233     raeburn  8456:     }
1.366     albertel 8457:     return %sectioncount;
1.233     raeburn  8458: }
                   8459: 
1.274     raeburn  8460: ###############################################
1.294     raeburn  8461: 
                   8462: =pod
1.405     albertel 8463: 
                   8464: =item * &get_course_users()
                   8465: 
1.275     raeburn  8466: Retrieves usernames:domains for users in the specified course
                   8467: with specific role(s), and access status. 
                   8468: 
                   8469: Incoming parameters:
1.277     albertel 8470: 1. course domain
                   8471: 2. course number
                   8472: 3. access status: users must have - either active, 
1.275     raeburn  8473: previous, future, or all.
1.277     albertel 8474: 4. reference to array of permissible roles
1.288     raeburn  8475: 5. reference to array of section restrictions (optional)
                   8476: 6. reference to results object (hash of hashes).
                   8477: 7. reference to optional userdata hash
1.609     raeburn  8478: 8. reference to optional statushash
1.630     raeburn  8479: 9. flag if privileged users (except those set to unhide in
                   8480:    course settings) should be excluded    
1.609     raeburn  8481: Keys of top level results hash are roles.
1.275     raeburn  8482: Keys of inner hashes are username:domain, with 
                   8483: values set to access type.
1.288     raeburn  8484: Optional userdata hash returns an array with arguments in the 
                   8485: same order as loncoursedata::get_classlist() for student data.
                   8486: 
1.609     raeburn  8487: Optional statushash returns
                   8488: 
1.288     raeburn  8489: Entries for end, start, section and status are blank because
                   8490: of the possibility of multiple values for non-student roles.
                   8491: 
1.275     raeburn  8492: =cut
1.405     albertel 8493: 
1.275     raeburn  8494: ###############################################
1.405     albertel 8495: 
1.275     raeburn  8496: sub get_course_users {
1.630     raeburn  8497:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8498:     my %idx = ();
1.419     raeburn  8499:     my %seclists;
1.288     raeburn  8500: 
                   8501:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8502:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8503:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8504:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8505:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8506:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8507:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8508:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8509: 
1.290     albertel 8510:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8511:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8512:         my $now = time;
1.277     albertel 8513:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8514:             my $match = 0;
1.412     raeburn  8515:             my $secmatch = 0;
1.419     raeburn  8516:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8517:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8518:             if ($section eq '') {
                   8519:                 $section = 'none';
                   8520:             }
1.291     albertel 8521:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8522:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8523:                     $secmatch = 1;
                   8524:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8525:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8526:                         $secmatch = 1;
                   8527:                     }
                   8528:                 } else {  
1.419     raeburn  8529: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8530: 		        $secmatch = 1;
                   8531:                     }
1.290     albertel 8532: 		}
1.412     raeburn  8533:                 if (!$secmatch) {
                   8534:                     next;
                   8535:                 }
1.419     raeburn  8536:             }
1.275     raeburn  8537:             if (defined($$types{'active'})) {
1.288     raeburn  8538:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8539:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8540:                     $match = 1;
1.275     raeburn  8541:                 }
                   8542:             }
                   8543:             if (defined($$types{'previous'})) {
1.609     raeburn  8544:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8545:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8546:                     $match = 1;
1.275     raeburn  8547:                 }
                   8548:             }
                   8549:             if (defined($$types{'future'})) {
1.609     raeburn  8550:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8551:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8552:                     $match = 1;
1.275     raeburn  8553:                 }
                   8554:             }
1.609     raeburn  8555:             if ($match) {
                   8556:                 push(@{$seclists{$student}},$section);
                   8557:                 if (ref($userdata) eq 'HASH') {
                   8558:                     $$userdata{$student} = $$classlist{$student};
                   8559:                 }
                   8560:                 if (ref($statushash) eq 'HASH') {
                   8561:                     $statushash->{$student}{'st'}{$section} = $status;
                   8562:                 }
1.288     raeburn  8563:             }
1.275     raeburn  8564:         }
                   8565:     }
1.412     raeburn  8566:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8567:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8568:         my $now = time;
1.609     raeburn  8569:         my %displaystatus = ( previous => 'Expired',
                   8570:                               active   => 'Active',
                   8571:                               future   => 'Future',
                   8572:                             );
1.1121    raeburn  8573:         my (%nothide,@possdoms);
1.630     raeburn  8574:         if ($hidepriv) {
                   8575:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8576:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8577:                 if ($user !~ /:/) {
                   8578:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8579:                 } else {
                   8580:                     $nothide{$user} = 1;
                   8581:                 }
                   8582:             }
1.1121    raeburn  8583:             my @possdoms = ($cdom);
                   8584:             if ($coursehash{'checkforpriv'}) {
                   8585:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8586:             }
1.630     raeburn  8587:         }
1.439     raeburn  8588:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8589:             my $match = 0;
1.412     raeburn  8590:             my $secmatch = 0;
1.439     raeburn  8591:             my $status;
1.412     raeburn  8592:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8593:             $user =~ s/:$//;
1.439     raeburn  8594:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8595:             if ($end == -1 || $start == -1) {
                   8596:                 next;
                   8597:             }
                   8598:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8599:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8600:                 my ($uname,$udom) = split(/:/,$user);
                   8601:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8602:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8603:                         $secmatch = 1;
                   8604:                     } elsif ($usec eq '') {
1.420     albertel 8605:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8606:                             $secmatch = 1;
                   8607:                         }
                   8608:                     } else {
                   8609:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8610:                             $secmatch = 1;
                   8611:                         }
                   8612:                     }
                   8613:                     if (!$secmatch) {
                   8614:                         next;
                   8615:                     }
1.288     raeburn  8616:                 }
1.419     raeburn  8617:                 if ($usec eq '') {
                   8618:                     $usec = 'none';
                   8619:                 }
1.275     raeburn  8620:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8621:                     if ($hidepriv) {
1.1121    raeburn  8622:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8623:                             (!$nothide{$uname.':'.$udom})) {
                   8624:                             next;
                   8625:                         }
                   8626:                     }
1.503     raeburn  8627:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8628:                         $status = 'previous';
                   8629:                     } elsif ($start > $now) {
                   8630:                         $status = 'future';
                   8631:                     } else {
                   8632:                         $status = 'active';
                   8633:                     }
1.277     albertel 8634:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8635:                         if ($status eq $type) {
1.420     albertel 8636:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8637:                                 push(@{$$users{$role}{$user}},$type);
                   8638:                             }
1.288     raeburn  8639:                             $match = 1;
                   8640:                         }
                   8641:                     }
1.419     raeburn  8642:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8643:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8644: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8645:                         }
1.420     albertel 8646:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8647:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8648:                         }
1.609     raeburn  8649:                         if (ref($statushash) eq 'HASH') {
                   8650:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8651:                         }
1.275     raeburn  8652:                     }
                   8653:                 }
                   8654:             }
                   8655:         }
1.290     albertel 8656:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8657:             if ((defined($cdom)) && (defined($cnum))) {
                   8658:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8659:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8660:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8661:                     next if ($owner eq '');
                   8662:                     my ($ownername,$ownerdom);
                   8663:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8664:                         $ownername = $1;
                   8665:                         $ownerdom = $2;
                   8666:                     } else {
                   8667:                         $ownername = $owner;
                   8668:                         $ownerdom = $cdom;
                   8669:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8670:                     }
                   8671:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8672:                     if (defined($userdata) && 
1.609     raeburn  8673: 			!exists($$userdata{$owner})) {
                   8674: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8675:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8676:                             push(@{$seclists{$owner}},'none');
                   8677:                         }
                   8678:                         if (ref($statushash) eq 'HASH') {
                   8679:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8680:                         }
1.290     albertel 8681: 		    }
1.279     raeburn  8682:                 }
                   8683:             }
                   8684:         }
1.419     raeburn  8685:         foreach my $user (keys(%seclists)) {
                   8686:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8687:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8688:         }
1.275     raeburn  8689:     }
                   8690:     return;
                   8691: }
                   8692: 
1.288     raeburn  8693: sub get_user_info {
                   8694:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8695:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8696: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8697:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8698:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8699:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8700:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8701:     return;
                   8702: }
1.275     raeburn  8703: 
1.472     raeburn  8704: ###############################################
                   8705: 
                   8706: =pod
                   8707: 
                   8708: =item * &get_user_quota()
                   8709: 
1.1134    raeburn  8710: Retrieves quota assigned for storage of user files.
                   8711: Default is to report quota for portfolio files.
1.472     raeburn  8712: 
                   8713: Incoming parameters:
                   8714: 1. user's username
                   8715: 2. user's domain
1.1134    raeburn  8716: 3. quota name - portfolio, author, or course
1.1136    raeburn  8717:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  8718: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  8719:    course
1.472     raeburn  8720: 
                   8721: Returns:
1.1163    raeburn  8722: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  8723: 2. (Optional) Type of setting: custom or default
                   8724:    (individually assigned or default for user's 
                   8725:    institutional status).
                   8726: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8727:    or student - types as defined in localenroll::inst_usertypes 
                   8728:    for user's domain, which determines default quota for user.
                   8729: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8730: 
                   8731: If a value has been stored in the user's environment, 
1.536     raeburn  8732: it will return that, otherwise it returns the maximal default
1.1134    raeburn  8733: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8734: 
                   8735: =cut
                   8736: 
                   8737: ###############################################
                   8738: 
                   8739: 
                   8740: sub get_user_quota {
1.1136    raeburn  8741:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  8742:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8743:     if (!defined($udom)) {
                   8744:         $udom = $env{'user.domain'};
                   8745:     }
                   8746:     if (!defined($uname)) {
                   8747:         $uname = $env{'user.name'};
                   8748:     }
                   8749:     if (($udom eq '' || $uname eq '') ||
                   8750:         ($udom eq 'public') && ($uname eq 'public')) {
                   8751:         $quota = 0;
1.536     raeburn  8752:         $quotatype = 'default';
                   8753:         $defquota = 0; 
1.472     raeburn  8754:     } else {
1.536     raeburn  8755:         my $inststatus;
1.1134    raeburn  8756:         if ($quotaname eq 'course') {
                   8757:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   8758:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   8759:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   8760:             } else {
                   8761:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   8762:                 $quota = $cenv{'internal.uploadquota'};
                   8763:             }
1.536     raeburn  8764:         } else {
1.1134    raeburn  8765:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8766:                 if ($quotaname eq 'author') {
                   8767:                     $quota = $env{'environment.authorquota'};
                   8768:                 } else {
                   8769:                     $quota = $env{'environment.portfolioquota'};
                   8770:                 }
                   8771:                 $inststatus = $env{'environment.inststatus'};
                   8772:             } else {
                   8773:                 my %userenv = 
                   8774:                     &Apache::lonnet::get('environment',['portfolioquota',
                   8775:                                          'authorquota','inststatus'],$udom,$uname);
                   8776:                 my ($tmp) = keys(%userenv);
                   8777:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8778:                     if ($quotaname eq 'author') {
                   8779:                         $quota = $userenv{'authorquota'};
                   8780:                     } else {
                   8781:                         $quota = $userenv{'portfolioquota'};
                   8782:                     }
                   8783:                     $inststatus = $userenv{'inststatus'};
                   8784:                 } else {
                   8785:                     undef(%userenv);
                   8786:                 }
                   8787:             }
                   8788:         }
                   8789:         if ($quota eq '' || wantarray) {
                   8790:             if ($quotaname eq 'course') {
                   8791:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  8792:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   8793:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  8794:                     $defquota = $domdefs{$crstype.'quota'};
                   8795:                 }
                   8796:                 if ($defquota eq '') {
                   8797:                     $defquota = 500;
                   8798:                 }
1.1134    raeburn  8799:             } else {
                   8800:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   8801:             }
                   8802:             if ($quota eq '') {
                   8803:                 $quota = $defquota;
                   8804:                 $quotatype = 'default';
                   8805:             } else {
                   8806:                 $quotatype = 'custom';
                   8807:             }
1.472     raeburn  8808:         }
                   8809:     }
1.536     raeburn  8810:     if (wantarray) {
                   8811:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8812:     } else {
                   8813:         return $quota;
                   8814:     }
1.472     raeburn  8815: }
                   8816: 
                   8817: ###############################################
                   8818: 
                   8819: =pod
                   8820: 
                   8821: =item * &default_quota()
                   8822: 
1.536     raeburn  8823: Retrieves default quota assigned for storage of user portfolio files,
                   8824: given an (optional) user's institutional status.
1.472     raeburn  8825: 
                   8826: Incoming parameters:
1.1142    raeburn  8827: 
1.472     raeburn  8828: 1. domain
1.536     raeburn  8829: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8830:    status types (e.g., faculty, staff, student etc.)
                   8831:    which apply to the user for whom the default is being retrieved.
                   8832:    If the institutional status string in undefined, the domain
1.1134    raeburn  8833:    default quota will be returned.
                   8834: 3.  quota name - portfolio, author, or course
                   8835:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  8836: 
                   8837: Returns:
1.1142    raeburn  8838: 
1.1163    raeburn  8839: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  8840: 2. (Optional) institutional type which determined the value of the
                   8841:    default quota.
1.472     raeburn  8842: 
                   8843: If a value has been stored in the domain's configuration db,
                   8844: it will return that, otherwise it returns 20 (for backwards 
                   8845: compatibility with domains which have not set up a configuration
1.1163    raeburn  8846: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  8847: 
1.536     raeburn  8848: If the user's status includes multiple types (e.g., staff and student),
                   8849: the largest default quota which applies to the user determines the
                   8850: default quota returned.
                   8851: 
1.472     raeburn  8852: =cut
                   8853: 
                   8854: ###############################################
                   8855: 
                   8856: 
                   8857: sub default_quota {
1.1134    raeburn  8858:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  8859:     my ($defquota,$settingstatus);
                   8860:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8861:                                             ['quotas'],$udom);
1.1134    raeburn  8862:     my $key = 'defaultquota';
                   8863:     if ($quotaname eq 'author') {
                   8864:         $key = 'authorquota';
                   8865:     }
1.622     raeburn  8866:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8867:         if ($inststatus ne '') {
1.765     raeburn  8868:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8869:             foreach my $item (@statuses) {
1.1134    raeburn  8870:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   8871:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  8872:                         if ($defquota eq '') {
1.1134    raeburn  8873:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8874:                             $settingstatus = $item;
1.1134    raeburn  8875:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   8876:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8877:                             $settingstatus = $item;
                   8878:                         }
                   8879:                     }
1.1134    raeburn  8880:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  8881:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8882:                         if ($defquota eq '') {
                   8883:                             $defquota = $quotahash{'quotas'}{$item};
                   8884:                             $settingstatus = $item;
                   8885:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8886:                             $defquota = $quotahash{'quotas'}{$item};
                   8887:                             $settingstatus = $item;
                   8888:                         }
1.536     raeburn  8889:                     }
                   8890:                 }
                   8891:             }
                   8892:         }
                   8893:         if ($defquota eq '') {
1.1134    raeburn  8894:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   8895:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   8896:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  8897:                 $defquota = $quotahash{'quotas'}{'default'};
                   8898:             }
1.536     raeburn  8899:             $settingstatus = 'default';
1.1139    raeburn  8900:             if ($defquota eq '') {
                   8901:                 if ($quotaname eq 'author') {
                   8902:                     $defquota = 500;
                   8903:                 }
                   8904:             }
1.536     raeburn  8905:         }
                   8906:     } else {
                   8907:         $settingstatus = 'default';
1.1134    raeburn  8908:         if ($quotaname eq 'author') {
                   8909:             $defquota = 500;
                   8910:         } else {
                   8911:             $defquota = 20;
                   8912:         }
1.536     raeburn  8913:     }
                   8914:     if (wantarray) {
                   8915:         return ($defquota,$settingstatus);
1.472     raeburn  8916:     } else {
1.536     raeburn  8917:         return $defquota;
1.472     raeburn  8918:     }
                   8919: }
                   8920: 
1.1135    raeburn  8921: ###############################################
                   8922: 
                   8923: =pod
                   8924: 
1.1136    raeburn  8925: =item * &excess_filesize_warning()
1.1135    raeburn  8926: 
                   8927: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  8928: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  8929: space to be exceeded.
1.1136    raeburn  8930: 
                   8931: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  8932: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  8933: 
1.1165    raeburn  8934: Inputs: 7 
1.1136    raeburn  8935: 1. username or coursenum
1.1135    raeburn  8936: 2. domain
1.1136    raeburn  8937: 3. context ('author' or 'course')
1.1135    raeburn  8938: 4. filename of file for which action is being requested
                   8939: 5. filesize (kB) of file
                   8940: 6. action being taken: copy or upload.
1.1165    raeburn  8941: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  8942: 
                   8943: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  8944:          otherwise return null.
                   8945: 
                   8946: =back
1.1135    raeburn  8947: 
                   8948: =cut
                   8949: 
1.1136    raeburn  8950: sub excess_filesize_warning {
1.1165    raeburn  8951:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  8952:     my $current_disk_usage = 0;
1.1165    raeburn  8953:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  8954:     if ($context eq 'author') {
                   8955:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   8956:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   8957:     } else {
                   8958:         foreach my $subdir ('docs','supplemental') {
                   8959:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   8960:         }
                   8961:     }
1.1135    raeburn  8962:     $disk_quota = int($disk_quota * 1000);
                   8963:     if (($current_disk_usage + $filesize) > $disk_quota) {
                   8964:         return '<p><span class="LC_warning">'.
                   8965:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
                   8966:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
                   8967:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   8968:                             $disk_quota,$current_disk_usage).
                   8969:                '</p>';
                   8970:     }
                   8971:     return;
                   8972: }
                   8973: 
                   8974: ###############################################
                   8975: 
                   8976: 
1.1136    raeburn  8977: 
                   8978: 
1.384     raeburn  8979: sub get_secgrprole_info {
                   8980:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8981:     my %sections_count = &get_sections($cdom,$cnum);
                   8982:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8983:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8984:     my @groups = sort(keys(%curr_groups));
                   8985:     my $allroles = [];
                   8986:     my $rolehash;
                   8987:     my $accesshash = {
                   8988:                      active => 'Currently has access',
                   8989:                      future => 'Will have future access',
                   8990:                      previous => 'Previously had access',
                   8991:                   };
                   8992:     if ($needroles) {
                   8993:         $rolehash = {'all' => 'all'};
1.385     albertel 8994:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8995: 	if (&Apache::lonnet::error(%user_roles)) {
                   8996: 	    undef(%user_roles);
                   8997: 	}
                   8998:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8999:             my ($role)=split(/\:/,$item,2);
                   9000:             if ($role eq 'cr') { next; }
                   9001:             if ($role =~ /^cr/) {
                   9002:                 $$rolehash{$role} = (split('/',$role))[3];
                   9003:             } else {
                   9004:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9005:             }
                   9006:         }
                   9007:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9008:             push(@{$allroles},$key);
                   9009:         }
                   9010:         push (@{$allroles},'st');
                   9011:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9012:     }
                   9013:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9014: }
                   9015: 
1.555     raeburn  9016: sub user_picker {
1.994     raeburn  9017:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9018:     my $currdom = $dom;
                   9019:     my %curr_selected = (
                   9020:                         srchin => 'dom',
1.580     raeburn  9021:                         srchby => 'lastname',
1.555     raeburn  9022:                       );
                   9023:     my $srchterm;
1.625     raeburn  9024:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9025:         if ($srch->{'srchby'} ne '') {
                   9026:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9027:         }
                   9028:         if ($srch->{'srchin'} ne '') {
                   9029:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9030:         }
                   9031:         if ($srch->{'srchtype'} ne '') {
                   9032:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9033:         }
                   9034:         if ($srch->{'srchdomain'} ne '') {
                   9035:             $currdom = $srch->{'srchdomain'};
                   9036:         }
                   9037:         $srchterm = $srch->{'srchterm'};
                   9038:     }
                   9039:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9040:                     'usr'       => 'Search criteria',
1.563     raeburn  9041:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9042:                     'uname'     => 'username',
                   9043:                     'lastname'  => 'last name',
1.555     raeburn  9044:                     'lastfirst' => 'last name, first name',
1.558     albertel 9045:                     'crs'       => 'in this course',
1.576     raeburn  9046:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9047:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9048:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9049:                     'exact'     => 'is',
                   9050:                     'contains'  => 'contains',
1.569     raeburn  9051:                     'begins'    => 'begins with',
1.571     raeburn  9052:                     'youm'      => "You must include some text to search for.",
                   9053:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9054:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9055:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9056:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9057:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9058:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9059:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9060:                                        );
1.563     raeburn  9061:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9062:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9063: 
                   9064:     my @srchins = ('crs','dom','alc','instd');
                   9065: 
                   9066:     foreach my $option (@srchins) {
                   9067:         # FIXME 'alc' option unavailable until 
                   9068:         #       loncreateuser::print_user_query_page()
                   9069:         #       has been completed.
                   9070:         next if ($option eq 'alc');
1.880     raeburn  9071:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9072:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9073:         if ($curr_selected{'srchin'} eq $option) {
                   9074:             $srchinsel .= ' 
                   9075:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9076:         } else {
                   9077:             $srchinsel .= '
                   9078:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9079:         }
1.555     raeburn  9080:     }
1.563     raeburn  9081:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9082: 
                   9083:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9084:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9085:         if ($curr_selected{'srchby'} eq $option) {
                   9086:             $srchbysel .= '
                   9087:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9088:         } else {
                   9089:             $srchbysel .= '
                   9090:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9091:          }
                   9092:     }
                   9093:     $srchbysel .= "\n  </select>\n";
                   9094: 
                   9095:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9096:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9097:         if ($curr_selected{'srchtype'} eq $option) {
                   9098:             $srchtypesel .= '
                   9099:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9100:         } else {
                   9101:             $srchtypesel .= '
                   9102:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9103:         }
                   9104:     }
                   9105:     $srchtypesel .= "\n  </select>\n";
                   9106: 
1.558     albertel 9107:     my ($newuserscript,$new_user_create);
1.994     raeburn  9108:     my $context_dom = $env{'request.role.domain'};
                   9109:     if ($context eq 'requestcrs') {
                   9110:         if ($env{'form.coursedom'} ne '') { 
                   9111:             $context_dom = $env{'form.coursedom'};
                   9112:         }
                   9113:     }
1.556     raeburn  9114:     if ($forcenewuser) {
1.576     raeburn  9115:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9116:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9117:                 if ($cancreate) {
                   9118:                     $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>';
                   9119:                 } else {
1.799     bisitz   9120:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9121:                     my %usertypetext = (
                   9122:                         official   => 'institutional',
                   9123:                         unofficial => 'non-institutional',
                   9124:                     );
1.799     bisitz   9125:                     $new_user_create = '<p class="LC_warning">'
                   9126:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9127:                                       .' '
                   9128:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9129:                                           ,'<a href="'.$helplink.'">','</a>')
                   9130:                                       .'</p><br />';
1.627     raeburn  9131:                 }
1.576     raeburn  9132:             }
                   9133:         }
                   9134: 
1.556     raeburn  9135:         $newuserscript = <<"ENDSCRIPT";
                   9136: 
1.570     raeburn  9137: function setSearch(createnew,callingForm) {
1.556     raeburn  9138:     if (createnew == 1) {
1.570     raeburn  9139:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9140:             if (callingForm.srchby.options[i].value == 'uname') {
                   9141:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9142:             }
                   9143:         }
1.570     raeburn  9144:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9145:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9146: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9147:             }
                   9148:         }
1.570     raeburn  9149:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9150:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9151:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9152:             }
                   9153:         }
1.570     raeburn  9154:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9155:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9156:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9157:             }
                   9158:         }
                   9159:     }
                   9160: }
                   9161: ENDSCRIPT
1.558     albertel 9162: 
1.556     raeburn  9163:     }
                   9164: 
1.555     raeburn  9165:     my $output = <<"END_BLOCK";
1.556     raeburn  9166: <script type="text/javascript">
1.824     bisitz   9167: // <![CDATA[
1.570     raeburn  9168: function validateEntry(callingForm) {
1.558     albertel 9169: 
1.556     raeburn  9170:     var checkok = 1;
1.558     albertel 9171:     var srchin;
1.570     raeburn  9172:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9173: 	if ( callingForm.srchin[i].checked ) {
                   9174: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9175: 	}
                   9176:     }
                   9177: 
1.570     raeburn  9178:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9179:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9180:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9181:     var srchterm =  callingForm.srchterm.value;
                   9182:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9183:     var msg = "";
                   9184: 
                   9185:     if (srchterm == "") {
                   9186:         checkok = 0;
1.571     raeburn  9187:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9188:     }
                   9189: 
1.569     raeburn  9190:     if (srchtype== 'begins') {
                   9191:         if (srchterm.length < 2) {
                   9192:             checkok = 0;
1.571     raeburn  9193:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9194:         }
                   9195:     }
                   9196: 
1.556     raeburn  9197:     if (srchtype== 'contains') {
                   9198:         if (srchterm.length < 3) {
                   9199:             checkok = 0;
1.571     raeburn  9200:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9201:         }
                   9202:     }
                   9203:     if (srchin == 'instd') {
                   9204:         if (srchdomain == '') {
                   9205:             checkok = 0;
1.571     raeburn  9206:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9207:         }
                   9208:     }
                   9209:     if (srchin == 'dom') {
                   9210:         if (srchdomain == '') {
                   9211:             checkok = 0;
1.571     raeburn  9212:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9213:         }
                   9214:     }
                   9215:     if (srchby == 'lastfirst') {
                   9216:         if (srchterm.indexOf(",") == -1) {
                   9217:             checkok = 0;
1.571     raeburn  9218:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9219:         }
                   9220:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9221:             checkok = 0;
1.571     raeburn  9222:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9223:         }
                   9224:     }
                   9225:     if (checkok == 0) {
1.571     raeburn  9226:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9227:         return;
                   9228:     }
                   9229:     if (checkok == 1) {
1.570     raeburn  9230:         callingForm.submit();
1.556     raeburn  9231:     }
                   9232: }
                   9233: 
                   9234: $newuserscript
                   9235: 
1.824     bisitz   9236: // ]]>
1.556     raeburn  9237: </script>
1.558     albertel 9238: 
                   9239: $new_user_create
                   9240: 
1.555     raeburn  9241: END_BLOCK
1.558     albertel 9242: 
1.876     raeburn  9243:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9244:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9245:                $domform.
                   9246:                &Apache::lonhtmlcommon::row_closure().
                   9247:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9248:                $srchbysel.
                   9249:                $srchtypesel. 
                   9250:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9251:                $srchinsel.
                   9252:                &Apache::lonhtmlcommon::row_closure(1). 
                   9253:                &Apache::lonhtmlcommon::end_pick_box().
                   9254:                '<br />';
1.555     raeburn  9255:     return $output;
                   9256: }
                   9257: 
1.612     raeburn  9258: sub user_rule_check {
1.615     raeburn  9259:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9260:     my $response;
                   9261:     if (ref($usershash) eq 'HASH') {
                   9262:         foreach my $user (keys(%{$usershash})) {
                   9263:             my ($uname,$udom) = split(/:/,$user);
                   9264:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9265:             my ($id,$newuser);
1.612     raeburn  9266:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9267:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9268:                 $id = $usershash->{$user}->{'id'};
                   9269:             }
                   9270:             my $inst_response;
                   9271:             if (ref($checks) eq 'HASH') {
                   9272:                 if (defined($checks->{'username'})) {
1.615     raeburn  9273:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9274:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9275:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9276:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9277:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9278:                 }
1.615     raeburn  9279:             } else {
                   9280:                 ($inst_response,%{$inst_results->{$user}}) =
                   9281:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9282:                 return;
1.612     raeburn  9283:             }
1.615     raeburn  9284:             if (!$got_rules->{$udom}) {
1.612     raeburn  9285:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9286:                                                   ['usercreation'],$udom);
                   9287:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9288:                     foreach my $item ('username','id') {
1.612     raeburn  9289:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9290:                             $$curr_rules{$udom}{$item} = 
                   9291:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9292:                         }
                   9293:                     }
                   9294:                 }
1.615     raeburn  9295:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9296:             }
1.612     raeburn  9297:             foreach my $item (keys(%{$checks})) {
                   9298:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9299:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9300:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9301:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9302:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9303:                                 if ($rule_check{$rule}) {
                   9304:                                     $$rulematch{$user}{$item} = $rule;
                   9305:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9306:                                         if (ref($inst_results) eq 'HASH') {
                   9307:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9308:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9309:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9310:                                                 }
1.612     raeburn  9311:                                             }
                   9312:                                         }
1.615     raeburn  9313:                                     }
                   9314:                                     last;
1.585     raeburn  9315:                                 }
                   9316:                             }
                   9317:                         }
                   9318:                     }
                   9319:                 }
                   9320:             }
                   9321:         }
                   9322:     }
1.612     raeburn  9323:     return;
                   9324: }
                   9325: 
                   9326: sub user_rule_formats {
                   9327:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9328:     my %text = ( 
                   9329:                  'username' => 'Usernames',
                   9330:                  'id'       => 'IDs',
                   9331:                );
                   9332:     my $output;
                   9333:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9334:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9335:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9336:             $output = '<br />'.
                   9337:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9338:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9339:                       ' <ul>';
1.612     raeburn  9340:             foreach my $rule (@{$ruleorder}) {
                   9341:                 if (ref($curr_rules) eq 'ARRAY') {
                   9342:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9343:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9344:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9345:                                         $rules->{$rule}{'desc'}.'</li>';
                   9346:                         }
                   9347:                     }
                   9348:                 }
                   9349:             }
                   9350:             $output .= '</ul>';
                   9351:         }
                   9352:     }
                   9353:     return $output;
                   9354: }
                   9355: 
                   9356: sub instrule_disallow_msg {
1.615     raeburn  9357:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9358:     my $response;
                   9359:     my %text = (
                   9360:                   item   => 'username',
                   9361:                   items  => 'usernames',
                   9362:                   match  => 'matches',
                   9363:                   do     => 'does',
                   9364:                   action => 'a username',
                   9365:                   one    => 'one',
                   9366:                );
                   9367:     if ($count > 1) {
                   9368:         $text{'item'} = 'usernames';
                   9369:         $text{'match'} ='match';
                   9370:         $text{'do'} = 'do';
                   9371:         $text{'action'} = 'usernames',
                   9372:         $text{'one'} = 'ones';
                   9373:     }
                   9374:     if ($checkitem eq 'id') {
                   9375:         $text{'items'} = 'IDs';
                   9376:         $text{'item'} = 'ID';
                   9377:         $text{'action'} = 'an ID';
1.615     raeburn  9378:         if ($count > 1) {
                   9379:             $text{'item'} = 'IDs';
                   9380:             $text{'action'} = 'IDs';
                   9381:         }
1.612     raeburn  9382:     }
1.674     bisitz   9383:     $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 />';
1.615     raeburn  9384:     if ($mode eq 'upload') {
                   9385:         if ($checkitem eq 'username') {
                   9386:             $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'}.");
                   9387:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9388:             $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.");
1.615     raeburn  9389:         }
1.669     raeburn  9390:     } elsif ($mode eq 'selfcreate') {
                   9391:         if ($checkitem eq 'id') {
                   9392:             $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.");
                   9393:         }
1.615     raeburn  9394:     } else {
                   9395:         if ($checkitem eq 'username') {
                   9396:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9397:         } elsif ($checkitem eq 'id') {
                   9398:             $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.");
                   9399:         }
1.612     raeburn  9400:     }
                   9401:     return $response;
1.585     raeburn  9402: }
                   9403: 
1.624     raeburn  9404: sub personal_data_fieldtitles {
                   9405:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9406:                         id => 'Student/Employee ID',
                   9407:                         permanentemail => 'E-mail address',
                   9408:                         lastname => 'Last Name',
                   9409:                         firstname => 'First Name',
                   9410:                         middlename => 'Middle Name',
                   9411:                         generation => 'Generation',
                   9412:                         gen => 'Generation',
1.765     raeburn  9413:                         inststatus => 'Affiliation',
1.624     raeburn  9414:                    );
                   9415:     return %fieldtitles;
                   9416: }
                   9417: 
1.642     raeburn  9418: sub sorted_inst_types {
                   9419:     my ($dom) = @_;
                   9420:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9421:     my $othertitle = &mt('All users');
                   9422:     if ($env{'request.course.id'}) {
1.668     raeburn  9423:         $othertitle  = &mt('Any users');
1.642     raeburn  9424:     }
                   9425:     my @types;
                   9426:     if (ref($order) eq 'ARRAY') {
                   9427:         @types = @{$order};
                   9428:     }
                   9429:     if (@types == 0) {
                   9430:         if (ref($usertypes) eq 'HASH') {
                   9431:             @types = sort(keys(%{$usertypes}));
                   9432:         }
                   9433:     }
                   9434:     if (keys(%{$usertypes}) > 0) {
                   9435:         $othertitle = &mt('Other users');
                   9436:     }
                   9437:     return ($othertitle,$usertypes,\@types);
                   9438: }
                   9439: 
1.645     raeburn  9440: sub get_institutional_codes {
                   9441:     my ($settings,$allcourses,$LC_code) = @_;
                   9442: # Get complete list of course sections to update
                   9443:     my @currsections = ();
                   9444:     my @currxlists = ();
                   9445:     my $coursecode = $$settings{'internal.coursecode'};
                   9446: 
                   9447:     if ($$settings{'internal.sectionnums'} ne '') {
                   9448:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9449:     }
                   9450: 
                   9451:     if ($$settings{'internal.crosslistings'} ne '') {
                   9452:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9453:     }
                   9454: 
                   9455:     if (@currxlists > 0) {
                   9456:         foreach (@currxlists) {
                   9457:             if (m/^([^:]+):(\w*)$/) {
                   9458:                 unless (grep/^$1$/,@{$allcourses}) {
                   9459:                     push @{$allcourses},$1;
                   9460:                     $$LC_code{$1} = $2;
                   9461:                 }
                   9462:             }
                   9463:         }
                   9464:     }
                   9465:  
                   9466:     if (@currsections > 0) {
                   9467:         foreach (@currsections) {
                   9468:             if (m/^(\w+):(\w*)$/) {
                   9469:                 my $sec = $coursecode.$1;
                   9470:                 my $lc_sec = $2;
                   9471:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9472:                     push @{$allcourses},$sec;
                   9473:                     $$LC_code{$sec} = $lc_sec;
                   9474:                 }
                   9475:             }
                   9476:         }
                   9477:     }
                   9478:     return;
                   9479: }
                   9480: 
1.971     raeburn  9481: sub get_standard_codeitems {
                   9482:     return ('Year','Semester','Department','Number','Section');
                   9483: }
                   9484: 
1.112     bowersj2 9485: =pod
                   9486: 
1.780     raeburn  9487: =head1 Slot Helpers
                   9488: 
                   9489: =over 4
                   9490: 
                   9491: =item * sorted_slots()
                   9492: 
1.1040    raeburn  9493: Sorts an array of slot names in order of an optional sort key,
                   9494: default sort is by slot start time (earliest first). 
1.780     raeburn  9495: 
                   9496: Inputs:
                   9497: 
                   9498: =over 4
                   9499: 
                   9500: slotsarr  - Reference to array of unsorted slot names.
                   9501: 
                   9502: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9503: 
1.1040    raeburn  9504: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9505: 
1.549     albertel 9506: =back
                   9507: 
1.780     raeburn  9508: Returns:
                   9509: 
                   9510: =over 4
                   9511: 
1.1040    raeburn  9512: sorted   - An array of slot names sorted by a specified sort key 
                   9513:            (default sort key is start time of the slot).
1.780     raeburn  9514: 
                   9515: =back
                   9516: 
                   9517: =cut
                   9518: 
                   9519: 
                   9520: sub sorted_slots {
1.1040    raeburn  9521:     my ($slotsarr,$slots,$sortkey) = @_;
                   9522:     if ($sortkey eq '') {
                   9523:         $sortkey = 'starttime';
                   9524:     }
1.780     raeburn  9525:     my @sorted;
                   9526:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9527:         @sorted =
                   9528:             sort {
                   9529:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9530:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9531:                      }
                   9532:                      if (ref($slots->{$a})) { return -1;}
                   9533:                      if (ref($slots->{$b})) { return 1;}
                   9534:                      return 0;
                   9535:                  } @{$slotsarr};
                   9536:     }
                   9537:     return @sorted;
                   9538: }
                   9539: 
1.1040    raeburn  9540: =pod
                   9541: 
                   9542: =item * get_future_slots()
                   9543: 
                   9544: Inputs:
                   9545: 
                   9546: =over 4
                   9547: 
                   9548: cnum - course number
                   9549: 
                   9550: cdom - course domain
                   9551: 
                   9552: now - current UNIX time
                   9553: 
                   9554: symb - optional symb
                   9555: 
                   9556: =back
                   9557: 
                   9558: Returns:
                   9559: 
                   9560: =over 4
                   9561: 
                   9562: sorted_reservable - ref to array of student_schedulable slots currently 
                   9563:                     reservable, ordered by end date of reservation period.
                   9564: 
                   9565: reservable_now - ref to hash of student_schedulable slots currently
                   9566:                  reservable.
                   9567: 
                   9568:     Keys in inner hash are:
                   9569:     (a) symb: either blank or symb to which slot use is restricted.
                   9570:     (b) endreserve: end date of reservation period. 
                   9571: 
                   9572: sorted_future - ref to array of student_schedulable slots reservable in
                   9573:                 the future, ordered by start date of reservation period.
                   9574: 
                   9575: future_reservable - ref to hash of student_schedulable slots reservable
                   9576:                     in the future.
                   9577: 
                   9578:     Keys in inner hash are:
                   9579:     (a) symb: either blank or symb to which slot use is restricted.
                   9580:     (b) startreserve:  start date of reservation period.
                   9581: 
                   9582: =back
                   9583: 
                   9584: =cut
                   9585: 
                   9586: sub get_future_slots {
                   9587:     my ($cnum,$cdom,$now,$symb) = @_;
                   9588:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9589:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9590:     foreach my $slot (keys(%slots)) {
                   9591:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9592:         if ($symb) {
                   9593:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9594:                      ($slots{$slot}->{'symb'} ne $symb));
                   9595:         }
                   9596:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9597:             ($slots{$slot}->{'endtime'} > $now)) {
                   9598:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9599:                 my $userallowed = 0;
                   9600:                 if ($slots{$slot}->{'allowedsections'}) {
                   9601:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9602:                     if (!defined($env{'request.role.sec'})
                   9603:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9604:                         $userallowed=1;
                   9605:                     } else {
                   9606:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9607:                             $userallowed=1;
                   9608:                         }
                   9609:                     }
                   9610:                     unless ($userallowed) {
                   9611:                         if (defined($env{'request.course.groups'})) {
                   9612:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9613:                             foreach my $group (@groups) {
                   9614:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9615:                                     $userallowed=1;
                   9616:                                     last;
                   9617:                                 }
                   9618:                             }
                   9619:                         }
                   9620:                     }
                   9621:                 }
                   9622:                 if ($slots{$slot}->{'allowedusers'}) {
                   9623:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9624:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9625:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9626:                         $userallowed = 1;
                   9627:                     }
                   9628:                 }
                   9629:                 next unless($userallowed);
                   9630:             }
                   9631:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9632:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9633:             my $symb = $slots{$slot}->{'symb'};
                   9634:             if (($startreserve < $now) &&
                   9635:                 (!$endreserve || $endreserve > $now)) {
                   9636:                 my $lastres = $endreserve;
                   9637:                 if (!$lastres) {
                   9638:                     $lastres = $slots{$slot}->{'starttime'};
                   9639:                 }
                   9640:                 $reservable_now{$slot} = {
                   9641:                                            symb       => $symb,
                   9642:                                            endreserve => $lastres
                   9643:                                          };
                   9644:             } elsif (($startreserve > $now) &&
                   9645:                      (!$endreserve || $endreserve > $startreserve)) {
                   9646:                 $future_reservable{$slot} = {
                   9647:                                               symb         => $symb,
                   9648:                                               startreserve => $startreserve
                   9649:                                             };
                   9650:             }
                   9651:         }
                   9652:     }
                   9653:     my @unsorted_reservable = keys(%reservable_now);
                   9654:     if (@unsorted_reservable > 0) {
                   9655:         @sorted_reservable = 
                   9656:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9657:     }
                   9658:     my @unsorted_future = keys(%future_reservable);
                   9659:     if (@unsorted_future > 0) {
                   9660:         @sorted_future =
                   9661:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9662:     }
                   9663:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9664: }
1.780     raeburn  9665: 
                   9666: =pod
                   9667: 
1.1057    foxr     9668: =back
                   9669: 
1.549     albertel 9670: =head1 HTTP Helpers
                   9671: 
                   9672: =over 4
                   9673: 
1.648     raeburn  9674: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9675: 
1.258     albertel 9676: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9677: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9678: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9679: 
                   9680: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9681: $possible_names is an ref to an array of form element names.  As an example:
                   9682: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9683: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9684: 
                   9685: =cut
1.1       albertel 9686: 
1.6       albertel 9687: sub get_unprocessed_cgi {
1.25      albertel 9688:   my ($query,$possible_names)= @_;
1.26      matthew  9689:   # $Apache::lonxml::debug=1;
1.356     albertel 9690:   foreach my $pair (split(/&/,$query)) {
                   9691:     my ($name, $value) = split(/=/,$pair);
1.369     www      9692:     $name = &unescape($name);
1.25      albertel 9693:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9694:       $value =~ tr/+/ /;
                   9695:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9696:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9697:     }
1.16      harris41 9698:   }
1.6       albertel 9699: }
                   9700: 
1.112     bowersj2 9701: =pod
                   9702: 
1.648     raeburn  9703: =item * &cacheheader() 
1.112     bowersj2 9704: 
                   9705: returns cache-controlling header code
                   9706: 
                   9707: =cut
                   9708: 
1.7       albertel 9709: sub cacheheader {
1.258     albertel 9710:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9711:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9712:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9713:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9714:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9715:     return $output;
1.7       albertel 9716: }
                   9717: 
1.112     bowersj2 9718: =pod
                   9719: 
1.648     raeburn  9720: =item * &no_cache($r) 
1.112     bowersj2 9721: 
                   9722: specifies header code to not have cache
                   9723: 
                   9724: =cut
                   9725: 
1.9       albertel 9726: sub no_cache {
1.216     albertel 9727:     my ($r) = @_;
                   9728:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9729: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9730:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9731:     $r->no_cache(1);
                   9732:     $r->header_out("Expires" => $date);
                   9733:     $r->header_out("Pragma" => "no-cache");
1.123     www      9734: }
                   9735: 
                   9736: sub content_type {
1.181     albertel 9737:     my ($r,$type,$charset) = @_;
1.299     foxr     9738:     if ($r) {
                   9739: 	#  Note that printout.pl calls this with undef for $r.
                   9740: 	&no_cache($r);
                   9741:     }
1.258     albertel 9742:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9743:     unless ($charset) {
                   9744: 	$charset=&Apache::lonlocal::current_encoding;
                   9745:     }
                   9746:     if ($charset) { $type.='; charset='.$charset; }
                   9747:     if ($r) {
                   9748: 	$r->content_type($type);
                   9749:     } else {
                   9750: 	print("Content-type: $type\n\n");
                   9751:     }
1.9       albertel 9752: }
1.25      albertel 9753: 
1.112     bowersj2 9754: =pod
                   9755: 
1.648     raeburn  9756: =item * &add_to_env($name,$value) 
1.112     bowersj2 9757: 
1.258     albertel 9758: adds $name to the %env hash with value
1.112     bowersj2 9759: $value, if $name already exists, the entry is converted to an array
                   9760: reference and $value is added to the array.
                   9761: 
                   9762: =cut
                   9763: 
1.25      albertel 9764: sub add_to_env {
                   9765:   my ($name,$value)=@_;
1.258     albertel 9766:   if (defined($env{$name})) {
                   9767:     if (ref($env{$name})) {
1.25      albertel 9768:       #already have multiple values
1.258     albertel 9769:       push(@{ $env{$name} },$value);
1.25      albertel 9770:     } else {
                   9771:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9772:       my $first=$env{$name};
                   9773:       undef($env{$name});
                   9774:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9775:     }
                   9776:   } else {
1.258     albertel 9777:     $env{$name}=$value;
1.25      albertel 9778:   }
1.31      albertel 9779: }
1.149     albertel 9780: 
                   9781: =pod
                   9782: 
1.648     raeburn  9783: =item * &get_env_multiple($name) 
1.149     albertel 9784: 
1.258     albertel 9785: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9786: values may be defined and end up as an array ref.
                   9787: 
                   9788: returns an array of values
                   9789: 
                   9790: =cut
                   9791: 
                   9792: sub get_env_multiple {
                   9793:     my ($name) = @_;
                   9794:     my @values;
1.258     albertel 9795:     if (defined($env{$name})) {
1.149     albertel 9796:         # exists is it an array
1.258     albertel 9797:         if (ref($env{$name})) {
                   9798:             @values=@{ $env{$name} };
1.149     albertel 9799:         } else {
1.258     albertel 9800:             $values[0]=$env{$name};
1.149     albertel 9801:         }
                   9802:     }
                   9803:     return(@values);
                   9804: }
                   9805: 
1.660     raeburn  9806: sub ask_for_embedded_content {
                   9807:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9808:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  9809:         %currsubfile,%unused,$rem);
1.1071    raeburn  9810:     my $counter = 0;
                   9811:     my $numnew = 0;
1.987     raeburn  9812:     my $numremref = 0;
                   9813:     my $numinvalid = 0;
                   9814:     my $numpathchg = 0;
                   9815:     my $numexisting = 0;
1.1071    raeburn  9816:     my $numunused = 0;
                   9817:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  9818:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  9819:     my $heading = &mt('Upload embedded files');
                   9820:     my $buttontext = &mt('Upload');
                   9821: 
1.1085    raeburn  9822:     if ($env{'request.course.id'}) {
1.1123    raeburn  9823:         if ($actionurl eq '/adm/dependencies') {
                   9824:             $navmap = Apache::lonnavmaps::navmap->new();
                   9825:         }
                   9826:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9827:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  9828:     }
1.1123    raeburn  9829:     if (($actionurl eq '/adm/portfolio') || 
                   9830:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  9831:         my $current_path='/';
                   9832:         if ($env{'form.currentpath'}) {
                   9833:             $current_path = $env{'form.currentpath'};
                   9834:         }
                   9835:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  9836:             $udom = $cdom;
                   9837:             $uname = $cnum;
1.984     raeburn  9838:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9839:         } else {
                   9840:             $udom = $env{'user.domain'};
                   9841:             $uname = $env{'user.name'};
                   9842:             $url = '/userfiles/portfolio';
                   9843:         }
1.987     raeburn  9844:         $toplevel = $url.'/';
1.984     raeburn  9845:         $url .= $current_path;
                   9846:         $getpropath = 1;
1.987     raeburn  9847:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9848:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9849:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9850:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9851:         $toplevel = $url;
1.984     raeburn  9852:         if ($rest ne '') {
1.987     raeburn  9853:             $url .= $rest;
                   9854:         }
                   9855:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9856:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9857:             $url = $args->{'docs_url'};
                   9858:             $toplevel = $url;
1.1084    raeburn  9859:             if ($args->{'context'} eq 'paste') {
                   9860:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9861:                 ($path) = 
                   9862:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9863:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9864:                 $fileloc =~ s{^/}{};
                   9865:             }
1.1071    raeburn  9866:         }
1.1084    raeburn  9867:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  9868:         if ($env{'request.course.id'} ne '') {
                   9869:             if (ref($args) eq 'HASH') {
                   9870:                 $url = $args->{'docs_url'};
                   9871:                 $title = $args->{'docs_title'};
1.1126    raeburn  9872:                 $toplevel = $url; 
                   9873:                 unless ($toplevel =~ m{^/}) {
                   9874:                     $toplevel = "/$url";
                   9875:                 }
1.1085    raeburn  9876:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  9877:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   9878:                     $path = $1;
                   9879:                 } else {
                   9880:                     ($path) =
                   9881:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9882:                 }
1.1071    raeburn  9883:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9884:                 $fileloc =~ s{^/}{};
                   9885:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9886:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9887:             }
1.987     raeburn  9888:         }
1.1123    raeburn  9889:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9890:         $udom = $cdom;
                   9891:         $uname = $cnum;
                   9892:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   9893:         $toplevel = $url;
                   9894:         $path = $url;
                   9895:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   9896:         $fileloc =~ s{^/}{};
1.987     raeburn  9897:     }
1.1126    raeburn  9898:     foreach my $file (keys(%{$allfiles})) {
                   9899:         my $embed_file;
                   9900:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   9901:             $embed_file = $1;
                   9902:         } else {
                   9903:             $embed_file = $file;
                   9904:         }
1.1158    raeburn  9905:         my ($absolutepath,$cleaned_file);
                   9906:         if ($embed_file =~ m{^\w+://}) {
                   9907:             $cleaned_file = $embed_file;
1.1147    raeburn  9908:             $newfiles{$cleaned_file} = 1;
                   9909:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  9910:         } else {
1.1158    raeburn  9911:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  9912:             if ($embed_file =~ m{^/}) {
                   9913:                 $absolutepath = $embed_file;
                   9914:             }
1.1147    raeburn  9915:             if ($cleaned_file =~ m{/}) {
                   9916:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  9917:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9918:                 my $item = $fname;
                   9919:                 if ($path ne '') {
                   9920:                     $item = $path.'/'.$fname;
                   9921:                     $subdependencies{$path}{$fname} = 1;
                   9922:                 } else {
                   9923:                     $dependencies{$item} = 1;
                   9924:                 }
                   9925:                 if ($absolutepath) {
                   9926:                     $mapping{$item} = $absolutepath;
                   9927:                 } else {
                   9928:                     $mapping{$item} = $embed_file;
                   9929:                 }
                   9930:             } else {
                   9931:                 $dependencies{$embed_file} = 1;
                   9932:                 if ($absolutepath) {
1.1147    raeburn  9933:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  9934:                 } else {
1.1147    raeburn  9935:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  9936:                 }
                   9937:             }
1.984     raeburn  9938:         }
                   9939:     }
1.1071    raeburn  9940:     my $dirptr = 16384;
1.984     raeburn  9941:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9942:         $currsubfile{$path} = {};
1.1123    raeburn  9943:         if (($actionurl eq '/adm/portfolio') || 
                   9944:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9945:             my ($sublistref,$listerror) =
                   9946:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9947:             if (ref($sublistref) eq 'ARRAY') {
                   9948:                 foreach my $line (@{$sublistref}) {
                   9949:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9950:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9951:                 }
1.984     raeburn  9952:             }
1.987     raeburn  9953:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9954:             if (opendir(my $dir,$url.'/'.$path)) {
                   9955:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9956:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9957:             }
1.1084    raeburn  9958:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9959:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  9960:                   ($args->{'context'} eq 'paste')) ||
                   9961:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9962:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  9963:                 my $dir;
                   9964:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9965:                     $dir = $fileloc;
                   9966:                 } else {
                   9967:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9968:                 }
1.1071    raeburn  9969:                 if ($dir ne '') {
                   9970:                     my ($sublistref,$listerror) =
                   9971:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9972:                     if (ref($sublistref) eq 'ARRAY') {
                   9973:                         foreach my $line (@{$sublistref}) {
                   9974:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9975:                                 undef,$mtime)=split(/\&/,$line,12);
                   9976:                             unless (($testdir&$dirptr) ||
                   9977:                                     ($file_name =~ /^\.\.?$/)) {
                   9978:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9979:                             }
                   9980:                         }
                   9981:                     }
                   9982:                 }
1.984     raeburn  9983:             }
                   9984:         }
                   9985:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9986:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9987:                 my $item = $path.'/'.$file;
                   9988:                 unless ($mapping{$item} eq $item) {
                   9989:                     $pathchanges{$item} = 1;
                   9990:                 }
                   9991:                 $existing{$item} = 1;
                   9992:                 $numexisting ++;
                   9993:             } else {
                   9994:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9995:             }
                   9996:         }
1.1071    raeburn  9997:         if ($actionurl eq '/adm/dependencies') {
                   9998:             foreach my $path (keys(%currsubfile)) {
                   9999:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10000:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10001:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10002:                              next if (($rem ne '') &&
                   10003:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10004:                                        (ref($navmap) &&
                   10005:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10006:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10007:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10008:                              $unused{$path.'/'.$file} = 1; 
                   10009:                          }
                   10010:                     }
                   10011:                 }
                   10012:             }
                   10013:         }
1.984     raeburn  10014:     }
1.987     raeburn  10015:     my %currfile;
1.1123    raeburn  10016:     if (($actionurl eq '/adm/portfolio') ||
                   10017:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10018:         my ($dirlistref,$listerror) =
                   10019:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10020:         if (ref($dirlistref) eq 'ARRAY') {
                   10021:             foreach my $line (@{$dirlistref}) {
                   10022:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10023:                 $currfile{$file_name} = 1;
                   10024:             }
1.984     raeburn  10025:         }
1.987     raeburn  10026:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10027:         if (opendir(my $dir,$url)) {
1.987     raeburn  10028:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10029:             map {$currfile{$_} = 1;} @dir_list;
                   10030:         }
1.1084    raeburn  10031:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10032:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10033:               ($args->{'context'} eq 'paste')) ||
                   10034:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10035:         if ($env{'request.course.id'} ne '') {
                   10036:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10037:             if ($dir ne '') {
                   10038:                 my ($dirlistref,$listerror) =
                   10039:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10040:                 if (ref($dirlistref) eq 'ARRAY') {
                   10041:                     foreach my $line (@{$dirlistref}) {
                   10042:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10043:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10044:                         unless (($testdir&$dirptr) ||
                   10045:                                 ($file_name =~ /^\.\.?$/)) {
                   10046:                             $currfile{$file_name} = [$size,$mtime];
                   10047:                         }
                   10048:                     }
                   10049:                 }
                   10050:             }
                   10051:         }
1.984     raeburn  10052:     }
                   10053:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10054:         if (exists($currfile{$file})) {
1.987     raeburn  10055:             unless ($mapping{$file} eq $file) {
                   10056:                 $pathchanges{$file} = 1;
                   10057:             }
                   10058:             $existing{$file} = 1;
                   10059:             $numexisting ++;
                   10060:         } else {
1.984     raeburn  10061:             $newfiles{$file} = 1;
                   10062:         }
                   10063:     }
1.1071    raeburn  10064:     foreach my $file (keys(%currfile)) {
                   10065:         unless (($file eq $filename) ||
                   10066:                 ($file eq $filename.'.bak') ||
                   10067:                 ($dependencies{$file})) {
1.1085    raeburn  10068:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10069:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10070:                     next if (($rem ne '') &&
                   10071:                              (($env{"httpref.$rem".$file} ne '') ||
                   10072:                               (ref($navmap) &&
                   10073:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10074:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10075:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10076:                 }
1.1085    raeburn  10077:             }
1.1071    raeburn  10078:             $unused{$file} = 1;
                   10079:         }
                   10080:     }
1.1084    raeburn  10081:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10082:         ($args->{'context'} eq 'paste')) {
                   10083:         $counter = scalar(keys(%existing));
                   10084:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10085:         return ($output,$counter,$numpathchg,\%existing);
                   10086:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10087:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10088:         $counter = scalar(keys(%existing));
                   10089:         $numpathchg = scalar(keys(%pathchanges));
                   10090:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10091:     }
1.984     raeburn  10092:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10093:         if ($actionurl eq '/adm/dependencies') {
                   10094:             next if ($embed_file =~ m{^\w+://});
                   10095:         }
1.660     raeburn  10096:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10097:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10098:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10099:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10100:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10101:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10102:         }
1.1123    raeburn  10103:         $upload_output .= '</td>';
1.1071    raeburn  10104:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10105:             $upload_output.='<td align="right">'.
                   10106:                             '<span class="LC_info LC_fontsize_medium">'.
                   10107:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10108:             $numremref++;
1.660     raeburn  10109:         } elsif ($args->{'error_on_invalid_names'}
                   10110:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10111:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10112:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10113:             $numinvalid++;
1.660     raeburn  10114:         } else {
1.1123    raeburn  10115:             $upload_output .= '<td>'.
                   10116:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10117:                                                      $embed_file,\%mapping,
1.1071    raeburn  10118:                                                      $allfiles,$codebase,'upload');
                   10119:             $counter ++;
                   10120:             $numnew ++;
1.987     raeburn  10121:         }
                   10122:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10123:     }
                   10124:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10125:         if ($actionurl eq '/adm/dependencies') {
                   10126:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10127:             $modify_output .= &start_data_table_row().
                   10128:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10129:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10130:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10131:                               '<td>'.$size.'</td>'.
                   10132:                               '<td>'.$mtime.'</td>'.
                   10133:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10134:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10135:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10136:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10137:                               &embedded_file_element('upload_embedded',$counter,
                   10138:                                                      $embed_file,\%mapping,
                   10139:                                                      $allfiles,$codebase,'modify').
                   10140:                               '</div></td>'.
                   10141:                               &end_data_table_row()."\n";
                   10142:             $counter ++;
                   10143:         } else {
                   10144:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10145:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10146:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10147:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10148:                               &Apache::loncommon::end_data_table_row()."\n";
                   10149:         }
                   10150:     }
                   10151:     my $delidx = $counter;
                   10152:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10153:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10154:         $delete_output .= &start_data_table_row().
                   10155:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10156:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10157:                           '<td>'.$size.'</td>'.
                   10158:                           '<td>'.$mtime.'</td>'.
                   10159:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10160:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10161:                           &embedded_file_element('upload_embedded',$delidx,
                   10162:                                                  $oldfile,\%mapping,$allfiles,
                   10163:                                                  $codebase,'delete').'</td>'.
                   10164:                           &end_data_table_row()."\n"; 
                   10165:         $numunused ++;
                   10166:         $delidx ++;
1.987     raeburn  10167:     }
                   10168:     if ($upload_output) {
                   10169:         $upload_output = &start_data_table().
                   10170:                          $upload_output.
                   10171:                          &end_data_table()."\n";
                   10172:     }
1.1071    raeburn  10173:     if ($modify_output) {
                   10174:         $modify_output = &start_data_table().
                   10175:                          &start_data_table_header_row().
                   10176:                          '<th>'.&mt('File').'</th>'.
                   10177:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10178:                          '<th>'.&mt('Modified').'</th>'.
                   10179:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10180:                          &end_data_table_header_row().
                   10181:                          $modify_output.
                   10182:                          &end_data_table()."\n";
                   10183:     }
                   10184:     if ($delete_output) {
                   10185:         $delete_output = &start_data_table().
                   10186:                          &start_data_table_header_row().
                   10187:                          '<th>'.&mt('File').'</th>'.
                   10188:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10189:                          '<th>'.&mt('Modified').'</th>'.
                   10190:                          '<th>'.&mt('Delete?').'</th>'.
                   10191:                          &end_data_table_header_row().
                   10192:                          $delete_output.
                   10193:                          &end_data_table()."\n";
                   10194:     }
1.987     raeburn  10195:     my $applies = 0;
                   10196:     if ($numremref) {
                   10197:         $applies ++;
                   10198:     }
                   10199:     if ($numinvalid) {
                   10200:         $applies ++;
                   10201:     }
                   10202:     if ($numexisting) {
                   10203:         $applies ++;
                   10204:     }
1.1071    raeburn  10205:     if ($counter || $numunused) {
1.987     raeburn  10206:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10207:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10208:                   $state.'<h3>'.$heading.'</h3>'; 
                   10209:         if ($actionurl eq '/adm/dependencies') {
                   10210:             if ($numnew) {
                   10211:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10212:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10213:                            $upload_output.'<br />'."\n";
                   10214:             }
                   10215:             if ($numexisting) {
                   10216:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10217:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10218:                            $modify_output.'<br />'."\n";
                   10219:                            $buttontext = &mt('Save changes');
                   10220:             }
                   10221:             if ($numunused) {
                   10222:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10223:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10224:                            $delete_output.'<br />'."\n";
                   10225:                            $buttontext = &mt('Save changes');
                   10226:             }
                   10227:         } else {
                   10228:             $output .= $upload_output.'<br />'."\n";
                   10229:         }
                   10230:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10231:                    $counter.'" />'."\n";
                   10232:         if ($actionurl eq '/adm/dependencies') { 
                   10233:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10234:                        $numnew.'" />'."\n";
                   10235:         } elsif ($actionurl eq '') {
1.987     raeburn  10236:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10237:         }
                   10238:     } elsif ($applies) {
                   10239:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10240:         if ($applies > 1) {
                   10241:             $output .=  
1.1123    raeburn  10242:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10243:             if ($numremref) {
                   10244:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10245:             }
                   10246:             if ($numinvalid) {
                   10247:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10248:             }
                   10249:             if ($numexisting) {
                   10250:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10251:             }
                   10252:             $output .= '</ul><br />';
                   10253:         } elsif ($numremref) {
                   10254:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10255:         } elsif ($numinvalid) {
                   10256:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10257:         } elsif ($numexisting) {
                   10258:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10259:         }
                   10260:         $output .= $upload_output.'<br />';
                   10261:     }
                   10262:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10263:     $chgcount = $counter;
1.987     raeburn  10264:     if (keys(%pathchanges) > 0) {
                   10265:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10266:             if ($counter) {
1.987     raeburn  10267:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10268:                                                   $embed_file,\%mapping,
1.1071    raeburn  10269:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10270:             } else {
                   10271:                 $pathchange_output .= 
                   10272:                     &start_data_table_row().
                   10273:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10274:                     $chgcount.'" checked="checked" /></td>'.
                   10275:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10276:                     '<td>'.$embed_file.
                   10277:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10278:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10279:                     '</td>'.&end_data_table_row();
1.660     raeburn  10280:             }
1.987     raeburn  10281:             $numpathchg ++;
                   10282:             $chgcount ++;
1.660     raeburn  10283:         }
                   10284:     }
1.1127    raeburn  10285:     if (($counter) || ($numunused)) {
1.987     raeburn  10286:         if ($numpathchg) {
                   10287:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10288:                        $numpathchg.'" />'."\n";
                   10289:         }
                   10290:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10291:             ($actionurl eq '/adm/imsimport')) {
                   10292:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10293:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10294:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10295:         } elsif ($actionurl eq '/adm/dependencies') {
                   10296:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10297:         }
1.1123    raeburn  10298:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10299:     } elsif ($numpathchg) {
                   10300:         my %pathchange = ();
                   10301:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10302:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10303:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  10304:         }
1.987     raeburn  10305:     }
1.1071    raeburn  10306:     return ($output,$counter,$numpathchg);
1.987     raeburn  10307: }
                   10308: 
1.1147    raeburn  10309: =pod
                   10310: 
                   10311: =item * clean_path($name)
                   10312: 
                   10313: Performs clean-up of directories, subdirectories and filename in an
                   10314: embedded object, referenced in an HTML file which is being uploaded
                   10315: to a course or portfolio, where 
                   10316: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10317: checked.
                   10318: 
                   10319: Clean-up is similar to replacements in lonnet::clean_filename()
                   10320: except each / between sub-directory and next level is preserved.
                   10321: 
                   10322: =cut
                   10323: 
                   10324: sub clean_path {
                   10325:     my ($embed_file) = @_;
                   10326:     $embed_file =~s{^/+}{};
                   10327:     my @contents;
                   10328:     if ($embed_file =~ m{/}) {
                   10329:         @contents = split(/\//,$embed_file);
                   10330:     } else {
                   10331:         @contents = ($embed_file);
                   10332:     }
                   10333:     my $lastidx = scalar(@contents)-1;
                   10334:     for (my $i=0; $i<=$lastidx; $i++) { 
                   10335:         $contents[$i]=~s{\\}{/}g;
                   10336:         $contents[$i]=~s/\s+/\_/g;
                   10337:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10338:         if ($i == $lastidx) {
                   10339:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10340:         }
                   10341:     }
                   10342:     if ($lastidx > 0) {
                   10343:         return join('/',@contents);
                   10344:     } else {
                   10345:         return $contents[0];
                   10346:     }
                   10347: }
                   10348: 
1.987     raeburn  10349: sub embedded_file_element {
1.1071    raeburn  10350:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10351:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10352:                    (ref($codebase) eq 'HASH'));
                   10353:     my $output;
1.1071    raeburn  10354:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10355:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10356:     }
                   10357:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10358:                &escape($embed_file).'" />';
                   10359:     unless (($context eq 'upload_embedded') && 
                   10360:             ($mapping->{$embed_file} eq $embed_file)) {
                   10361:         $output .='
                   10362:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10363:     }
                   10364:     my $attrib;
                   10365:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10366:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10367:     }
                   10368:     $output .=
                   10369:         "\n\t\t".
                   10370:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10371:         $attrib.'" />';
                   10372:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10373:         $output .=
                   10374:             "\n\t\t".
                   10375:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10376:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10377:     }
1.987     raeburn  10378:     return $output;
1.660     raeburn  10379: }
                   10380: 
1.1071    raeburn  10381: sub get_dependency_details {
                   10382:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10383:     my ($size,$mtime,$showsize,$showmtime);
                   10384:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10385:         if ($embed_file =~ m{/}) {
                   10386:             my ($path,$fname) = split(/\//,$embed_file);
                   10387:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10388:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10389:             }
                   10390:         } else {
                   10391:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10392:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10393:             }
                   10394:         }
                   10395:         $showsize = $size/1024.0;
                   10396:         $showsize = sprintf("%.1f",$showsize);
                   10397:         if ($mtime > 0) {
                   10398:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10399:         }
                   10400:     }
                   10401:     return ($showsize,$showmtime);
                   10402: }
                   10403: 
                   10404: sub ask_embedded_js {
                   10405:     return <<"END";
                   10406: <script type="text/javascript"">
                   10407: // <![CDATA[
                   10408: function toggleBrowse(counter) {
                   10409:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10410:     var fileid = document.getElementById('embedded_item_'+counter);
                   10411:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10412:     if (chkboxid.checked == true) {
                   10413:         uploaddivid.style.display='block';
                   10414:     } else {
                   10415:         uploaddivid.style.display='none';
                   10416:         fileid.value = '';
                   10417:     }
                   10418: }
                   10419: // ]]>
                   10420: </script>
                   10421: 
                   10422: END
                   10423: }
                   10424: 
1.661     raeburn  10425: sub upload_embedded {
                   10426:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10427:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10428:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10429:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10430:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10431:         my $orig_uploaded_filename =
                   10432:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10433:         foreach my $type ('orig','ref','attrib','codebase') {
                   10434:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10435:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10436:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10437:             }
                   10438:         }
1.661     raeburn  10439:         my ($path,$fname) =
                   10440:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10441:         # no path, whole string is fname
                   10442:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10443:         $fname = &Apache::lonnet::clean_filename($fname);
                   10444:         # See if there is anything left
                   10445:         next if ($fname eq '');
                   10446: 
                   10447:         # Check if file already exists as a file or directory.
                   10448:         my ($state,$msg);
                   10449:         if ($context eq 'portfolio') {
                   10450:             my $port_path = $dirpath;
                   10451:             if ($group ne '') {
                   10452:                 $port_path = "groups/$group/$port_path";
                   10453:             }
1.987     raeburn  10454:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10455:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10456:                                               $dir_root,$port_path,$disk_quota,
                   10457:                                               $current_disk_usage,$uname,$udom);
                   10458:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10459:                 || $state eq 'file_locked') {
1.661     raeburn  10460:                 $output .= $msg;
                   10461:                 next;
                   10462:             }
                   10463:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10464:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10465:             if ($state eq 'exists') {
                   10466:                 $output .= $msg;
                   10467:                 next;
                   10468:             }
                   10469:         }
                   10470:         # Check if extension is valid
                   10471:         if (($fname =~ /\.(\w+)$/) &&
                   10472:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   10473:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10474:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10475:             next;
                   10476:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10477:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10478:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10479:             next;
                   10480:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10481:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10482:             next;
                   10483:         }
                   10484:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  10485:         my $subdir = $path;
                   10486:         $subdir =~ s{/+$}{};
1.661     raeburn  10487:         if ($context eq 'portfolio') {
1.984     raeburn  10488:             my $result;
                   10489:             if ($state eq 'existingfile') {
                   10490:                 $result=
                   10491:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  10492:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10493:             } else {
1.984     raeburn  10494:                 $result=
                   10495:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10496:                                                     $dirpath.
1.1123    raeburn  10497:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10498:                 if ($result !~ m|^/uploaded/|) {
                   10499:                     $output .= '<span class="LC_error">'
                   10500:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10501:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10502:                                .'</span><br />';
                   10503:                     next;
                   10504:                 } else {
1.987     raeburn  10505:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10506:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10507:                 }
1.661     raeburn  10508:             }
1.1123    raeburn  10509:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  10510:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10511:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10512:             my $result =
1.1126    raeburn  10513:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10514:             if ($result !~ m|^/uploaded/|) {
                   10515:                 $output .= '<span class="LC_error">'
                   10516:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10517:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10518:                            .'</span><br />';
                   10519:                     next;
                   10520:             } else {
                   10521:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10522:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  10523:                 if ($context eq 'syllabus') {
                   10524:                     &Apache::lonnet::make_public_indefinitely($result);
                   10525:                 }
1.987     raeburn  10526:             }
1.661     raeburn  10527:         } else {
                   10528: # Save the file
                   10529:             my $target = $env{'form.embedded_item_'.$i};
                   10530:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10531:             my $dest = $fullpath.$fname;
                   10532:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10533:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10534:             my $count;
                   10535:             my $filepath = $dir_root;
1.1027    raeburn  10536:             foreach my $subdir (@parts) {
                   10537:                 $filepath .= "/$subdir";
                   10538:                 if (!-e $filepath) {
1.661     raeburn  10539:                     mkdir($filepath,0770);
                   10540:                 }
                   10541:             }
                   10542:             my $fh;
                   10543:             if (!open($fh,'>'.$dest)) {
                   10544:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10545:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10546:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10547:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10548:                            '</span><br />';
                   10549:             } else {
                   10550:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10551:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10552:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10553:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10554:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10555:                               '</span><br />';
                   10556:                 } else {
1.987     raeburn  10557:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10558:                                $url.'</span>').'<br />';
                   10559:                     unless ($context eq 'testbank') {
                   10560:                         $footer .= &mt('View embedded file: [_1]',
                   10561:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10562:                     }
                   10563:                 }
                   10564:                 close($fh);
                   10565:             }
                   10566:         }
                   10567:         if ($env{'form.embedded_ref_'.$i}) {
                   10568:             $pathchange{$i} = 1;
                   10569:         }
                   10570:     }
                   10571:     if ($output) {
                   10572:         $output = '<p>'.$output.'</p>';
                   10573:     }
                   10574:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10575:     $returnflag = 'ok';
1.1071    raeburn  10576:     my $numpathchgs = scalar(keys(%pathchange));
                   10577:     if ($numpathchgs > 0) {
1.987     raeburn  10578:         if ($context eq 'portfolio') {
                   10579:             $output .= '<p>'.&mt('or').'</p>';
                   10580:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10581:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10582:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10583:             $returnflag = 'modify_orightml';
                   10584:         }
                   10585:     }
1.1071    raeburn  10586:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10587: }
                   10588: 
                   10589: sub modify_html_form {
                   10590:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10591:     my $end = 0;
                   10592:     my $modifyform;
                   10593:     if ($context eq 'upload_embedded') {
                   10594:         return unless (ref($pathchange) eq 'HASH');
                   10595:         if ($env{'form.number_embedded_items'}) {
                   10596:             $end += $env{'form.number_embedded_items'};
                   10597:         }
                   10598:         if ($env{'form.number_pathchange_items'}) {
                   10599:             $end += $env{'form.number_pathchange_items'};
                   10600:         }
                   10601:         if ($end) {
                   10602:             for (my $i=0; $i<$end; $i++) {
                   10603:                 if ($i < $env{'form.number_embedded_items'}) {
                   10604:                     next unless($pathchange->{$i});
                   10605:                 }
                   10606:                 $modifyform .=
                   10607:                     &start_data_table_row().
                   10608:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10609:                     'checked="checked" /></td>'.
                   10610:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10611:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10612:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10613:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10614:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10615:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10616:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10617:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10618:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10619:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10620:                     &end_data_table_row();
1.1071    raeburn  10621:             }
1.987     raeburn  10622:         }
                   10623:     } else {
                   10624:         $modifyform = $pathchgtable;
                   10625:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10626:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10627:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10628:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10629:         }
                   10630:     }
                   10631:     if ($modifyform) {
1.1071    raeburn  10632:         if ($actionurl eq '/adm/dependencies') {
                   10633:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10634:         }
1.987     raeburn  10635:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10636:                '<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".
                   10637:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10638:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10639:                '</ol></p>'."\n".'<p>'.
                   10640:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10641:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10642:                &start_data_table()."\n".
                   10643:                &start_data_table_header_row().
                   10644:                '<th>'.&mt('Change?').'</th>'.
                   10645:                '<th>'.&mt('Current reference').'</th>'.
                   10646:                '<th>'.&mt('Required reference').'</th>'.
                   10647:                &end_data_table_header_row()."\n".
                   10648:                $modifyform.
                   10649:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10650:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10651:                '</form>'."\n";
                   10652:     }
                   10653:     return;
                   10654: }
                   10655: 
                   10656: sub modify_html_refs {
1.1123    raeburn  10657:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10658:     my $container;
                   10659:     if ($context eq 'portfolio') {
                   10660:         $container = $env{'form.container'};
                   10661:     } elsif ($context eq 'coursedoc') {
                   10662:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10663:     } elsif ($context eq 'manage_dependencies') {
                   10664:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10665:         $container = "/$container";
1.1123    raeburn  10666:     } elsif ($context eq 'syllabus') {
                   10667:         $container = $url;
1.987     raeburn  10668:     } else {
1.1027    raeburn  10669:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10670:     }
                   10671:     my (%allfiles,%codebase,$output,$content);
                   10672:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  10673:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  10674:         if (wantarray) {
                   10675:             return ('',0,0); 
                   10676:         } else {
                   10677:             return;
                   10678:         }
                   10679:     }
                   10680:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  10681:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10682:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10683:             if (wantarray) {
                   10684:                 return ('',0,0);
                   10685:             } else {
                   10686:                 return;
                   10687:             }
                   10688:         } 
1.987     raeburn  10689:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10690:         if ($content eq '-1') {
                   10691:             if (wantarray) {
                   10692:                 return ('',0,0);
                   10693:             } else {
                   10694:                 return;
                   10695:             }
                   10696:         }
1.987     raeburn  10697:     } else {
1.1071    raeburn  10698:         unless ($container =~ /^\Q$dir_root\E/) {
                   10699:             if (wantarray) {
                   10700:                 return ('',0,0);
                   10701:             } else {
                   10702:                 return;
                   10703:             }
                   10704:         } 
1.987     raeburn  10705:         if (open(my $fh,"<$container")) {
                   10706:             $content = join('', <$fh>);
                   10707:             close($fh);
                   10708:         } else {
1.1071    raeburn  10709:             if (wantarray) {
                   10710:                 return ('',0,0);
                   10711:             } else {
                   10712:                 return;
                   10713:             }
1.987     raeburn  10714:         }
                   10715:     }
                   10716:     my ($count,$codebasecount) = (0,0);
                   10717:     my $mm = new File::MMagic;
                   10718:     my $mime_type = $mm->checktype_contents($content);
                   10719:     if ($mime_type eq 'text/html') {
                   10720:         my $parse_result = 
                   10721:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10722:                                                     \%codebase,\$content);
                   10723:         if ($parse_result eq 'ok') {
                   10724:             foreach my $i (@changes) {
                   10725:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10726:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10727:                 if ($allfiles{$ref}) {
                   10728:                     my $newname =  $orig;
                   10729:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10730:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10731:                     if ($attrib_regexp =~ /:/) {
                   10732:                         $attrib_regexp =~ s/\:/|/g;
                   10733:                     }
                   10734:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10735:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10736:                         $count += $numchg;
1.1123    raeburn  10737:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  10738:                         delete($allfiles{$ref});
1.987     raeburn  10739:                     }
                   10740:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10741:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10742:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10743:                         $codebasecount ++;
                   10744:                     }
                   10745:                 }
                   10746:             }
1.1123    raeburn  10747:             my $skiprewrites;
1.987     raeburn  10748:             if ($count || $codebasecount) {
                   10749:                 my $saveresult;
1.1071    raeburn  10750:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  10751:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10752:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10753:                     if ($url eq $container) {
                   10754:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10755:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10756:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10757:                                             $fname.'</span>').'</p>';
1.987     raeburn  10758:                     } else {
                   10759:                          $output = '<p class="LC_error">'.
                   10760:                                    &mt('Error: update failed for: [_1].',
                   10761:                                    '<span class="LC_filename">'.
                   10762:                                    $container.'</span>').'</p>';
                   10763:                     }
1.1123    raeburn  10764:                     if ($context eq 'syllabus') {
                   10765:                         unless ($saveresult eq 'ok') {
                   10766:                             $skiprewrites = 1;
                   10767:                         }
                   10768:                     }
1.987     raeburn  10769:                 } else {
                   10770:                     if (open(my $fh,">$container")) {
                   10771:                         print $fh $content;
                   10772:                         close($fh);
                   10773:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10774:                                   $count,'<span class="LC_filename">'.
                   10775:                                   $container.'</span>').'</p>';
1.661     raeburn  10776:                     } else {
1.987     raeburn  10777:                          $output = '<p class="LC_error">'.
                   10778:                                    &mt('Error: could not update [_1].',
                   10779:                                    '<span class="LC_filename">'.
                   10780:                                    $container.'</span>').'</p>';
1.661     raeburn  10781:                     }
                   10782:                 }
                   10783:             }
1.1123    raeburn  10784:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10785:                 my ($actionurl,$state);
                   10786:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10787:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10788:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10789:                                               \%codebase,
                   10790:                                               {'context' => 'rewrites',
                   10791:                                                'ignore_remote_references' => 1,});
                   10792:                 if (ref($mapping) eq 'HASH') {
                   10793:                     my $rewrites = 0;
                   10794:                     foreach my $key (keys(%{$mapping})) {
                   10795:                         next if ($key =~ m{^https?://});
                   10796:                         my $ref = $mapping->{$key};
                   10797:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10798:                         my $attrib;
                   10799:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   10800:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   10801:                         }
                   10802:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10803:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10804:                             $rewrites += $numchg;
                   10805:                         }
                   10806:                     }
                   10807:                     if ($rewrites) {
                   10808:                         my $saveresult; 
                   10809:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10810:                         if ($url eq $container) {
                   10811:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   10812:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   10813:                                             $count,'<span class="LC_filename">'.
                   10814:                                             $fname.'</span>').'</p>';
                   10815:                         } else {
                   10816:                             $output .= '<p class="LC_error">'.
                   10817:                                        &mt('Error: could not update links in [_1].',
                   10818:                                        '<span class="LC_filename">'.
                   10819:                                        $container.'</span>').'</p>';
                   10820: 
                   10821:                         }
                   10822:                     }
                   10823:                 }
                   10824:             }
1.987     raeburn  10825:         } else {
                   10826:             &logthis('Failed to parse '.$container.
                   10827:                      ' to modify references: '.$parse_result);
1.661     raeburn  10828:         }
                   10829:     }
1.1071    raeburn  10830:     if (wantarray) {
                   10831:         return ($output,$count,$codebasecount);
                   10832:     } else {
                   10833:         return $output;
                   10834:     }
1.661     raeburn  10835: }
                   10836: 
                   10837: sub check_for_existing {
                   10838:     my ($path,$fname,$element) = @_;
                   10839:     my ($state,$msg);
                   10840:     if (-d $path.'/'.$fname) {
                   10841:         $state = 'exists';
                   10842:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10843:     } elsif (-e $path.'/'.$fname) {
                   10844:         $state = 'exists';
                   10845:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10846:     }
                   10847:     if ($state eq 'exists') {
                   10848:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10849:     }
                   10850:     return ($state,$msg);
                   10851: }
                   10852: 
                   10853: sub check_for_upload {
                   10854:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10855:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10856:     my $filesize = length($env{'form.'.$element});
                   10857:     if (!$filesize) {
                   10858:         my $msg = '<span class="LC_error">'.
                   10859:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10860:                       '<span class="LC_filename">'.$fname.'</span>',
                   10861:                       $filesize).'<br />'.
1.1007    raeburn  10862:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10863:                   '</span>';
                   10864:         return ('zero_bytes',$msg);
                   10865:     }
                   10866:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10867:     my $getpropath = 1;
1.1021    raeburn  10868:     my ($dirlistref,$listerror) =
                   10869:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10870:     my $found_file = 0;
                   10871:     my $locked_file = 0;
1.991     raeburn  10872:     my @lockers;
                   10873:     my $navmap;
                   10874:     if ($env{'request.course.id'}) {
                   10875:         $navmap = Apache::lonnavmaps::navmap->new();
                   10876:     }
1.1021    raeburn  10877:     if (ref($dirlistref) eq 'ARRAY') {
                   10878:         foreach my $line (@{$dirlistref}) {
                   10879:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10880:             if ($file_name eq $fname){
                   10881:                 $file_name = $path.$file_name;
                   10882:                 if ($group ne '') {
                   10883:                     $file_name = $group.$file_name;
                   10884:                 }
                   10885:                 $found_file = 1;
                   10886:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10887:                     foreach my $lock (@lockers) {
                   10888:                         if (ref($lock) eq 'ARRAY') {
                   10889:                             my ($symb,$crsid) = @{$lock};
                   10890:                             if ($crsid eq $env{'request.course.id'}) {
                   10891:                                 if (ref($navmap)) {
                   10892:                                     my $res = $navmap->getBySymb($symb);
                   10893:                                     foreach my $part (@{$res->parts()}) { 
                   10894:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10895:                                         unless (($slot_status == $res->RESERVED) ||
                   10896:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10897:                                             $locked_file = 1;
                   10898:                                         }
1.991     raeburn  10899:                                     }
1.1021    raeburn  10900:                                 } else {
                   10901:                                     $locked_file = 1;
1.991     raeburn  10902:                                 }
                   10903:                             } else {
                   10904:                                 $locked_file = 1;
                   10905:                             }
                   10906:                         }
1.1021    raeburn  10907:                    }
                   10908:                 } else {
                   10909:                     my @info = split(/\&/,$rest);
                   10910:                     my $currsize = $info[6]/1000;
                   10911:                     if ($currsize < $filesize) {
                   10912:                         my $extra = $filesize - $currsize;
                   10913:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10914:                             my $msg = '<span class="LC_error">'.
                   10915:                                       &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.',
                   10916:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10917:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10918:                                                    $disk_quota,$current_disk_usage);
                   10919:                             return ('will_exceed_quota',$msg);
                   10920:                         }
1.984     raeburn  10921:                     }
                   10922:                 }
1.661     raeburn  10923:             }
                   10924:         }
                   10925:     }
                   10926:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10927:         my $msg = '<span class="LC_error">'.
                   10928:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10929:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10930:         return ('will_exceed_quota',$msg);
                   10931:     } elsif ($found_file) {
                   10932:         if ($locked_file) {
                   10933:             my $msg = '<span class="LC_error">';
                   10934:             $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>');
                   10935:             $msg .= '</span><br />';
                   10936:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10937:             return ('file_locked',$msg);
                   10938:         } else {
                   10939:             my $msg = '<span class="LC_error">';
1.984     raeburn  10940:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.661     raeburn  10941:             $msg .= '</span>';
1.984     raeburn  10942:             return ('existingfile',$msg);
1.661     raeburn  10943:         }
                   10944:     }
                   10945: }
                   10946: 
1.987     raeburn  10947: sub check_for_traversal {
                   10948:     my ($path,$url,$toplevel) = @_;
                   10949:     my @parts=split(/\//,$path);
                   10950:     my $cleanpath;
                   10951:     my $fullpath = $url;
                   10952:     for (my $i=0;$i<@parts;$i++) {
                   10953:         next if ($parts[$i] eq '.');
                   10954:         if ($parts[$i] eq '..') {
                   10955:             $fullpath =~ s{([^/]+/)$}{};
                   10956:         } else {
                   10957:             $fullpath .= $parts[$i].'/';
                   10958:         }
                   10959:     }
                   10960:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10961:         $cleanpath = $1;
                   10962:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10963:         my $curr_toprel = $1;
                   10964:         my @parts = split(/\//,$curr_toprel);
                   10965:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10966:         my @urlparts = split(/\//,$url_toprel);
                   10967:         my $doubledots;
                   10968:         my $startdiff = -1;
                   10969:         for (my $i=0; $i<@urlparts; $i++) {
                   10970:             if ($startdiff == -1) {
                   10971:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10972:                     $startdiff = $i;
                   10973:                     $doubledots .= '../';
                   10974:                 }
                   10975:             } else {
                   10976:                 $doubledots .= '../';
                   10977:             }
                   10978:         }
                   10979:         if ($startdiff > -1) {
                   10980:             $cleanpath = $doubledots;
                   10981:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10982:                 $cleanpath .= $parts[$i].'/';
                   10983:             }
                   10984:         }
                   10985:     }
                   10986:     $cleanpath =~ s{(/)$}{};
                   10987:     return $cleanpath;
                   10988: }
1.31      albertel 10989: 
1.1053    raeburn  10990: sub is_archive_file {
                   10991:     my ($mimetype) = @_;
                   10992:     if (($mimetype eq 'application/octet-stream') ||
                   10993:         ($mimetype eq 'application/x-stuffit') ||
                   10994:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10995:         return 1;
                   10996:     }
                   10997:     return;
                   10998: }
                   10999: 
                   11000: sub decompress_form {
1.1065    raeburn  11001:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11002:     my %lt = &Apache::lonlocal::texthash (
                   11003:         this => 'This file is an archive file.',
1.1067    raeburn  11004:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11005:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11006:         youm => 'You may wish to extract its contents.',
                   11007:         extr => 'Extract contents',
1.1067    raeburn  11008:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11009:         proa => 'Process automatically?',
1.1053    raeburn  11010:         yes  => 'Yes',
                   11011:         no   => 'No',
1.1067    raeburn  11012:         fold => 'Title for folder containing movie',
                   11013:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11014:     );
1.1065    raeburn  11015:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11016:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11017:     my $info = &list_archive_contents($fileloc,\@paths);
                   11018:     if (@paths) {
                   11019:         foreach my $path (@paths) {
                   11020:             $path =~ s{^/}{};
1.1067    raeburn  11021:             if ($path =~ m{^([^/]+)/$}) {
                   11022:                 $topdir = $1;
                   11023:             }
1.1065    raeburn  11024:             if ($path =~ m{^([^/]+)/}) {
                   11025:                 $toplevel{$1} = $path;
                   11026:             } else {
                   11027:                 $toplevel{$path} = $path;
                   11028:             }
                   11029:         }
                   11030:     }
1.1067    raeburn  11031:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11032:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11033:                         "$topdir/media/",
                   11034:                         "$topdir/media/$topdir.mp4",
                   11035:                         "$topdir/media/FirstFrame.png",
                   11036:                         "$topdir/media/player.swf",
                   11037:                         "$topdir/media/swfobject.js",
                   11038:                         "$topdir/media/expressInstall.swf");
1.1164    raeburn  11039:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
                   11040:                          "$topdir/$topdir.mp4",
                   11041:                          "$topdir/$topdir\_config.xml",
                   11042:                          "$topdir/$topdir\_controller.swf",
                   11043:                          "$topdir/$topdir\_embed.css",
                   11044:                          "$topdir/$topdir\_First_Frame.png",
                   11045:                          "$topdir/$topdir\_player.html",
                   11046:                          "$topdir/$topdir\_Thumbnails.png",
                   11047:                          "$topdir/playerProductInstall.swf",
                   11048:                          "$topdir/scripts/",
                   11049:                          "$topdir/scripts/config_xml.js",
                   11050:                          "$topdir/scripts/handlebars.js",
                   11051:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11052:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11053:                          "$topdir/scripts/modernizr.js",
                   11054:                          "$topdir/scripts/player-min.js",
                   11055:                          "$topdir/scripts/swfobject.js",
                   11056:                          "$topdir/skins/",
                   11057:                          "$topdir/skins/configuration_express.xml",
                   11058:                          "$topdir/skins/express_show/",
                   11059:                          "$topdir/skins/express_show/player-min.css",
                   11060:                          "$topdir/skins/express_show/spritesheet.png");
                   11061:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11062:         if (@diffs == 0) {
1.1164    raeburn  11063:             $is_camtasia = 6;
                   11064:         } else {
                   11065:             @diffs = &compare_arrays(\@paths,\@camtasia8);
                   11066:             if (@diffs == 0) {
                   11067:                 $is_camtasia = 8;
                   11068:             }
1.1067    raeburn  11069:         }
                   11070:     }
                   11071:     my $output;
                   11072:     if ($is_camtasia) {
                   11073:         $output = <<"ENDCAM";
                   11074: <script type="text/javascript" language="Javascript">
                   11075: // <![CDATA[
                   11076: 
                   11077: function camtasiaToggle() {
                   11078:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11079:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11080:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11081: 
                   11082:                 document.getElementById('camtasia_titles').style.display='block';
                   11083:             } else {
                   11084:                 document.getElementById('camtasia_titles').style.display='none';
                   11085:             }
                   11086:         }
                   11087:     }
                   11088:     return;
                   11089: }
                   11090: 
                   11091: // ]]>
                   11092: </script>
                   11093: <p>$lt{'camt'}</p>
                   11094: ENDCAM
1.1065    raeburn  11095:     } else {
1.1067    raeburn  11096:         $output = '<p>'.$lt{'this'};
                   11097:         if ($info eq '') {
                   11098:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11099:         } else {
                   11100:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11101:                        '<div><pre>'.$info.'</pre></div>';
                   11102:         }
1.1065    raeburn  11103:     }
1.1067    raeburn  11104:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11105:     my $duplicates;
                   11106:     my $num = 0;
                   11107:     if (ref($dirlist) eq 'ARRAY') {
                   11108:         foreach my $item (@{$dirlist}) {
                   11109:             if (ref($item) eq 'ARRAY') {
                   11110:                 if (exists($toplevel{$item->[0]})) {
                   11111:                     $duplicates .= 
                   11112:                         &start_data_table_row().
                   11113:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11114:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11115:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11116:                         'value="1" />'.&mt('Yes').'</label>'.
                   11117:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11118:                         '<td>'.$item->[0].'</td>';
                   11119:                     if ($item->[2]) {
                   11120:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11121:                     } else {
                   11122:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11123:                     }
                   11124:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11125:                                    '<td>'.
                   11126:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11127:                                    '</td>'.
                   11128:                                    &end_data_table_row();
                   11129:                     $num ++;
                   11130:                 }
                   11131:             }
                   11132:         }
                   11133:     }
                   11134:     my $itemcount;
                   11135:     if (@paths > 0) {
                   11136:         $itemcount = scalar(@paths);
                   11137:     } else {
                   11138:         $itemcount = 1;
                   11139:     }
1.1067    raeburn  11140:     if ($is_camtasia) {
                   11141:         $output .= $lt{'auto'}.'<br />'.
                   11142:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11143:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11144:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11145:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11146:                    $lt{'no'}.'</label></span><br />'.
                   11147:                    '<div id="camtasia_titles" style="display:block">'.
                   11148:                    &Apache::lonhtmlcommon::start_pick_box().
                   11149:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11150:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11151:                    &Apache::lonhtmlcommon::row_closure().
                   11152:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11153:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11154:                    &Apache::lonhtmlcommon::row_closure(1).
                   11155:                    &Apache::lonhtmlcommon::end_pick_box().
                   11156:                    '</div>';
                   11157:     }
1.1065    raeburn  11158:     $output .= 
                   11159:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11160:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11161:         "\n";
1.1065    raeburn  11162:     if ($duplicates ne '') {
                   11163:         $output .= '<p><span class="LC_warning">'.
                   11164:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11165:                    &start_data_table().
                   11166:                    &start_data_table_header_row().
                   11167:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11168:                    '<th>'.&mt('Name').'</th>'.
                   11169:                    '<th>'.&mt('Type').'</th>'.
                   11170:                    '<th>'.&mt('Size').'</th>'.
                   11171:                    '<th>'.&mt('Last modified').'</th>'.
                   11172:                    &end_data_table_header_row().
                   11173:                    $duplicates.
                   11174:                    &end_data_table().
                   11175:                    '</p>';
                   11176:     }
1.1067    raeburn  11177:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11178:     if (ref($hiddenelements) eq 'HASH') {
                   11179:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11180:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11181:         }
                   11182:     }
                   11183:     $output .= <<"END";
1.1067    raeburn  11184: <br />
1.1053    raeburn  11185: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11186: </form>
                   11187: $noextract
                   11188: END
                   11189:     return $output;
                   11190: }
                   11191: 
1.1065    raeburn  11192: sub decompression_utility {
                   11193:     my ($program) = @_;
                   11194:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11195:     my $location;
                   11196:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11197:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11198:                          '/usr/sbin/') {
                   11199:             if (-x $dir.$program) {
                   11200:                 $location = $dir.$program;
                   11201:                 last;
                   11202:             }
                   11203:         }
                   11204:     }
                   11205:     return $location;
                   11206: }
                   11207: 
                   11208: sub list_archive_contents {
                   11209:     my ($file,$pathsref) = @_;
                   11210:     my (@cmd,$output);
                   11211:     my $needsregexp;
                   11212:     if ($file =~ /\.zip$/) {
                   11213:         @cmd = (&decompression_utility('unzip'),"-l");
                   11214:         $needsregexp = 1;
                   11215:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11216:              ($file =~ /\.tgz$/)) {
                   11217:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11218:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11219:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11220:     } elsif ($file =~ m|\.tar$|) {
                   11221:         @cmd = (&decompression_utility('tar'),"-tf");
                   11222:     }
                   11223:     if (@cmd) {
                   11224:         undef($!);
                   11225:         undef($@);
                   11226:         if (open(my $fh,"-|", @cmd, $file)) {
                   11227:             while (my $line = <$fh>) {
                   11228:                 $output .= $line;
                   11229:                 chomp($line);
                   11230:                 my $item;
                   11231:                 if ($needsregexp) {
                   11232:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11233:                 } else {
                   11234:                     $item = $line;
                   11235:                 }
                   11236:                 if ($item ne '') {
                   11237:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11238:                         push(@{$pathsref},$item);
                   11239:                     } 
                   11240:                 }
                   11241:             }
                   11242:             close($fh);
                   11243:         }
                   11244:     }
                   11245:     return $output;
                   11246: }
                   11247: 
1.1053    raeburn  11248: sub decompress_uploaded_file {
                   11249:     my ($file,$dir) = @_;
                   11250:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11251:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11252:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11253:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11254:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11255:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11256:     my $decompressed = $env{'cgi.decompressed'};
                   11257:     &Apache::lonnet::delenv('cgi.file');
                   11258:     &Apache::lonnet::delenv('cgi.dir');
                   11259:     &Apache::lonnet::delenv('cgi.decompressed');
                   11260:     return ($decompressed,$result);
                   11261: }
                   11262: 
1.1055    raeburn  11263: sub process_decompression {
                   11264:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11265:     my ($dir,$error,$warning,$output);
                   11266:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
1.1120    bisitz   11267:         $error = &mt('Filename not a supported archive file type.').
                   11268:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11269:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11270:     } else {
                   11271:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11272:         if ($docuhome eq 'no_host') {
                   11273:             $error = &mt('Could not determine home server for course.');
                   11274:         } else {
                   11275:             my @ids=&Apache::lonnet::current_machine_ids();
                   11276:             my $currdir = "$dir_root/$destination";
                   11277:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11278:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11279:                        "$dir_root/$destination";
                   11280:             } else {
                   11281:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11282:                        "$dir_root/$docudom/$docuname/$destination";
                   11283:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11284:                     $error = &mt('Archive file not found.');
                   11285:                 }
                   11286:             }
1.1065    raeburn  11287:             my (@to_overwrite,@to_skip);
                   11288:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11289:                 my $total = $env{'form.archive_overwrite_total'};
                   11290:                 for (my $i=0; $i<$total; $i++) {
                   11291:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11292:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11293:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11294:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11295:                     }
                   11296:                 }
                   11297:             }
                   11298:             my $numskip = scalar(@to_skip);
                   11299:             if (($numskip > 0) && 
                   11300:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11301:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11302:             } elsif ($dir eq '') {
1.1055    raeburn  11303:                 $error = &mt('Directory containing archive file unavailable.');
                   11304:             } elsif (!$error) {
1.1065    raeburn  11305:                 my ($decompressed,$display);
                   11306:                 if ($numskip > 0) {
                   11307:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11308:                     mkdir("$dir/$tempdir",0755);
                   11309:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11310:                     ($decompressed,$display) = 
                   11311:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11312:                     foreach my $item (@to_skip) {
                   11313:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11314:                             if (-f "$dir/$tempdir/$item") { 
                   11315:                                 unlink("$dir/$tempdir/$item");
                   11316:                             } elsif (-d "$dir/$tempdir/$item") {
                   11317:                                 system("rm -rf $dir/$tempdir/$item");
                   11318:                             }
                   11319:                         }
                   11320:                     }
                   11321:                     system("mv $dir/$tempdir/* $dir");
                   11322:                     rmdir("$dir/$tempdir");   
                   11323:                 } else {
                   11324:                     ($decompressed,$display) = 
                   11325:                         &decompress_uploaded_file($file,$dir);
                   11326:                 }
1.1055    raeburn  11327:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11328:                     $output = '<p class="LC_info">'.
                   11329:                               &mt('Files extracted successfully from archive.').
                   11330:                               '</p>'."\n";
1.1055    raeburn  11331:                     my ($warning,$result,@contents);
                   11332:                     my ($newdirlistref,$newlisterror) =
                   11333:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11334:                                                  $docuname,1);
                   11335:                     my (%is_dir,%changes,@newitems);
                   11336:                     my $dirptr = 16384;
1.1065    raeburn  11337:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11338:                         foreach my $dir_line (@{$newdirlistref}) {
                   11339:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11340:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11341:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11342:                                 push(@newitems,$item);
                   11343:                                 if ($dirptr&$testdir) {
                   11344:                                     $is_dir{$item} = 1;
                   11345:                                 }
                   11346:                                 $changes{$item} = 1;
                   11347:                             }
                   11348:                         }
                   11349:                     }
                   11350:                     if (keys(%changes) > 0) {
                   11351:                         foreach my $item (sort(@newitems)) {
                   11352:                             if ($changes{$item}) {
                   11353:                                 push(@contents,$item);
                   11354:                             }
                   11355:                         }
                   11356:                     }
                   11357:                     if (@contents > 0) {
1.1067    raeburn  11358:                         my $wantform;
                   11359:                         unless ($env{'form.autoextract_camtasia'}) {
                   11360:                             $wantform = 1;
                   11361:                         }
1.1056    raeburn  11362:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11363:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11364:                                                                 $currdir,\%is_dir,
                   11365:                                                                 \%children,\%parent,
1.1056    raeburn  11366:                                                                 \@contents,\%dirorder,
                   11367:                                                                 \%titles,$wantform);
1.1055    raeburn  11368:                         if ($datatable ne '') {
                   11369:                             $output .= &archive_options_form('decompressed',$datatable,
                   11370:                                                              $count,$hiddenelem);
1.1065    raeburn  11371:                             my $startcount = 6;
1.1055    raeburn  11372:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11373:                                                            \%titles,\%children);
1.1055    raeburn  11374:                         }
1.1067    raeburn  11375:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  11376:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11377:                             my %displayed;
                   11378:                             my $total = 1;
                   11379:                             $env{'form.archive_directory'} = [];
                   11380:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11381:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11382:                                 $path =~ s{/$}{};
                   11383:                                 my $item;
                   11384:                                 if ($path ne '') {
                   11385:                                     $item = "$path/$titles{$i}";
                   11386:                                 } else {
                   11387:                                     $item = $titles{$i};
                   11388:                                 }
                   11389:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11390:                                 if ($item eq $contents[0]) {
                   11391:                                     push(@{$env{'form.archive_directory'}},$i);
                   11392:                                     $env{'form.archive_'.$i} = 'display';
                   11393:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11394:                                     $displayed{'folder'} = $i;
1.1164    raeburn  11395:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11396:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  11397:                                     $env{'form.archive_'.$i} = 'display';
                   11398:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11399:                                     $displayed{'web'} = $i;
                   11400:                                 } else {
1.1164    raeburn  11401:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11402:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11403:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11404:                                         push(@{$env{'form.archive_directory'}},$i);
                   11405:                                     }
                   11406:                                     $env{'form.archive_'.$i} = 'dependency';
                   11407:                                 }
                   11408:                                 $total ++;
                   11409:                             }
                   11410:                             for (my $i=1; $i<$total; $i++) {
                   11411:                                 next if ($i == $displayed{'web'});
                   11412:                                 next if ($i == $displayed{'folder'});
                   11413:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11414:                             }
                   11415:                             $env{'form.phase'} = 'decompress_cleanup';
                   11416:                             $env{'form.archivedelete'} = 1;
                   11417:                             $env{'form.archive_count'} = $total-1;
                   11418:                             $output .=
                   11419:                                 &process_extracted_files('coursedocs',$docudom,
                   11420:                                                          $docuname,$destination,
                   11421:                                                          $dir_root,$hiddenelem);
                   11422:                         }
1.1055    raeburn  11423:                     } else {
                   11424:                         $warning = &mt('No new items extracted from archive file.');
                   11425:                     }
                   11426:                 } else {
                   11427:                     $output = $display;
                   11428:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11429:                 }
                   11430:             }
                   11431:         }
                   11432:     }
                   11433:     if ($error) {
                   11434:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11435:                    $error.'</p>'."\n";
                   11436:     }
                   11437:     if ($warning) {
                   11438:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11439:     }
                   11440:     return $output;
                   11441: }
                   11442: 
                   11443: sub get_extracted {
1.1056    raeburn  11444:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11445:         $titles,$wantform) = @_;
1.1055    raeburn  11446:     my $count = 0;
                   11447:     my $depth = 0;
                   11448:     my $datatable;
1.1056    raeburn  11449:     my @hierarchy;
1.1055    raeburn  11450:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11451:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11452:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11453:     foreach my $item (@{$contents}) {
                   11454:         $count ++;
1.1056    raeburn  11455:         @{$dirorder->{$count}} = @hierarchy;
                   11456:         $titles->{$count} = $item;
1.1055    raeburn  11457:         &archive_hierarchy($depth,$count,$parent,$children);
                   11458:         if ($wantform) {
                   11459:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11460:                                        $currdir,$depth,$count);
                   11461:         }
                   11462:         if ($is_dir->{$item}) {
                   11463:             $depth ++;
1.1056    raeburn  11464:             push(@hierarchy,$count);
                   11465:             $parent->{$depth} = $count;
1.1055    raeburn  11466:             $datatable .=
                   11467:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11468:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11469:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11470:             $depth --;
1.1056    raeburn  11471:             pop(@hierarchy);
1.1055    raeburn  11472:         }
                   11473:     }
                   11474:     return ($count,$datatable);
                   11475: }
                   11476: 
                   11477: sub recurse_extracted_archive {
1.1056    raeburn  11478:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11479:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11480:     my $result='';
1.1056    raeburn  11481:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11482:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11483:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11484:         return $result;
                   11485:     }
                   11486:     my $dirptr = 16384;
                   11487:     my ($newdirlistref,$newlisterror) =
                   11488:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11489:     if (ref($newdirlistref) eq 'ARRAY') {
                   11490:         foreach my $dir_line (@{$newdirlistref}) {
                   11491:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11492:             unless ($item =~ /^\.+$/) {
                   11493:                 $$count ++;
1.1056    raeburn  11494:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11495:                 $titles->{$$count} = $item;
1.1055    raeburn  11496:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11497: 
1.1055    raeburn  11498:                 my $is_dir;
                   11499:                 if ($dirptr&$testdir) {
                   11500:                     $is_dir = 1;
                   11501:                 }
                   11502:                 if ($wantform) {
                   11503:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11504:                 }
                   11505:                 if ($is_dir) {
                   11506:                     $$depth ++;
1.1056    raeburn  11507:                     push(@{$hierarchy},$$count);
                   11508:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11509:                     $result .=
                   11510:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11511:                                                    $docuname,$depth,$count,
1.1056    raeburn  11512:                                                    $hierarchy,$dirorder,$children,
                   11513:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11514:                     $$depth --;
1.1056    raeburn  11515:                     pop(@{$hierarchy});
1.1055    raeburn  11516:                 }
                   11517:             }
                   11518:         }
                   11519:     }
                   11520:     return $result;
                   11521: }
                   11522: 
                   11523: sub archive_hierarchy {
                   11524:     my ($depth,$count,$parent,$children) =@_;
                   11525:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11526:         if (exists($parent->{$depth})) {
                   11527:              $children->{$parent->{$depth}} .= $count.':';
                   11528:         }
                   11529:     }
                   11530:     return;
                   11531: }
                   11532: 
                   11533: sub archive_row {
                   11534:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11535:     my ($name) = ($item =~ m{([^/]+)$});
                   11536:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11537:                                        'display'    => 'Add as file',
1.1055    raeburn  11538:                                        'dependency' => 'Include as dependency',
                   11539:                                        'discard'    => 'Discard',
                   11540:                                       );
                   11541:     if ($is_dir) {
1.1059    raeburn  11542:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11543:     }
1.1056    raeburn  11544:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11545:     my $offset = 0;
1.1055    raeburn  11546:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11547:         $offset ++;
1.1065    raeburn  11548:         if ($action ne 'display') {
                   11549:             $offset ++;
                   11550:         }  
1.1055    raeburn  11551:         $output .= '<td><span class="LC_nobreak">'.
                   11552:                    '<label><input type="radio" name="archive_'.$count.
                   11553:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11554:         my $text = $choices{$action};
                   11555:         if ($is_dir) {
                   11556:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11557:             if ($action eq 'display') {
1.1059    raeburn  11558:                 $text = &mt('Add as folder');
1.1055    raeburn  11559:             }
1.1056    raeburn  11560:         } else {
                   11561:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11562: 
                   11563:         }
                   11564:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11565:         if ($action eq 'dependency') {
                   11566:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11567:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11568:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11569:                        '<option value=""></option>'."\n".
                   11570:                        '</select>'."\n".
                   11571:                        '</div>';
1.1059    raeburn  11572:         } elsif ($action eq 'display') {
                   11573:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11574:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11575:                        '</div>';
1.1055    raeburn  11576:         }
1.1056    raeburn  11577:         $output .= '</td>';
1.1055    raeburn  11578:     }
                   11579:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11580:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11581:     for (my $i=0; $i<$depth; $i++) {
                   11582:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11583:     }
                   11584:     if ($is_dir) {
                   11585:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11586:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11587:     } else {
                   11588:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11589:     }
                   11590:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11591:                &end_data_table_row();
                   11592:     return $output;
                   11593: }
                   11594: 
                   11595: sub archive_options_form {
1.1065    raeburn  11596:     my ($form,$display,$count,$hiddenelem) = @_;
                   11597:     my %lt = &Apache::lonlocal::texthash(
                   11598:                perm => 'Permanently remove archive file?',
                   11599:                hows => 'How should each extracted item be incorporated in the course?',
                   11600:                cont => 'Content actions for all',
                   11601:                addf => 'Add as folder/file',
                   11602:                incd => 'Include as dependency for a displayed file',
                   11603:                disc => 'Discard',
                   11604:                no   => 'No',
                   11605:                yes  => 'Yes',
                   11606:                save => 'Save',
                   11607:     );
                   11608:     my $output = <<"END";
                   11609: <form name="$form" method="post" action="">
                   11610: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11611: <label>
                   11612:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11613: </label>
                   11614: &nbsp;
                   11615: <label>
                   11616:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11617: </span>
                   11618: </p>
                   11619: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11620: <br />$lt{'hows'}
                   11621: <div class="LC_columnSection">
                   11622:   <fieldset>
                   11623:     <legend>$lt{'cont'}</legend>
                   11624:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11625:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11626:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11627:   </fieldset>
                   11628: </div>
                   11629: END
                   11630:     return $output.
1.1055    raeburn  11631:            &start_data_table()."\n".
1.1065    raeburn  11632:            $display."\n".
1.1055    raeburn  11633:            &end_data_table()."\n".
                   11634:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11635:            $hiddenelem.
1.1065    raeburn  11636:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11637:            '</form>';
                   11638: }
                   11639: 
                   11640: sub archive_javascript {
1.1056    raeburn  11641:     my ($startcount,$numitems,$titles,$children) = @_;
                   11642:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11643:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11644:     my $scripttag = <<START;
                   11645: <script type="text/javascript">
                   11646: // <![CDATA[
                   11647: 
                   11648: function checkAll(form,prefix) {
                   11649:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11650:     for (var i=0; i < form.elements.length; i++) {
                   11651:         var id = form.elements[i].id;
                   11652:         if ((id != '') && (id != undefined)) {
                   11653:             if (idstr.test(id)) {
                   11654:                 if (form.elements[i].type == 'radio') {
                   11655:                     form.elements[i].checked = true;
1.1056    raeburn  11656:                     var nostart = i-$startcount;
1.1059    raeburn  11657:                     var offset = nostart%7;
                   11658:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11659:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11660:                 }
                   11661:             }
                   11662:         }
                   11663:     }
                   11664: }
                   11665: 
                   11666: function propagateCheck(form,count) {
                   11667:     if (count > 0) {
1.1059    raeburn  11668:         var startelement = $startcount + ((count-1) * 7);
                   11669:         for (var j=1; j<6; j++) {
                   11670:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11671:                 var item = startelement + j; 
                   11672:                 if (form.elements[item].type == 'radio') {
                   11673:                     if (form.elements[item].checked) {
                   11674:                         containerCheck(form,count,j);
                   11675:                         break;
                   11676:                     }
1.1055    raeburn  11677:                 }
                   11678:             }
                   11679:         }
                   11680:     }
                   11681: }
                   11682: 
                   11683: numitems = $numitems
1.1056    raeburn  11684: var titles = new Array(numitems);
                   11685: var parents = new Array(numitems);
1.1055    raeburn  11686: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11687:     parents[i] = new Array;
1.1055    raeburn  11688: }
1.1059    raeburn  11689: var maintitle = '$maintitle';
1.1055    raeburn  11690: 
                   11691: START
                   11692: 
1.1056    raeburn  11693:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11694:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11695:         for (my $i=0; $i<@contents; $i ++) {
                   11696:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11697:         }
                   11698:     }
                   11699: 
1.1056    raeburn  11700:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11701:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11702:     }
                   11703: 
1.1055    raeburn  11704:     $scripttag .= <<END;
                   11705: 
                   11706: function containerCheck(form,count,offset) {
                   11707:     if (count > 0) {
1.1056    raeburn  11708:         dependencyCheck(form,count,offset);
1.1059    raeburn  11709:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11710:         form.elements[item].checked = true;
                   11711:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11712:             if (parents[count].length > 0) {
                   11713:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11714:                     containerCheck(form,parents[count][j],offset);
                   11715:                 }
                   11716:             }
                   11717:         }
                   11718:     }
                   11719: }
                   11720: 
                   11721: function dependencyCheck(form,count,offset) {
                   11722:     if (count > 0) {
1.1059    raeburn  11723:         var chosen = (offset+$startcount)+7*(count-1);
                   11724:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11725:         var currtype = form.elements[depitem].type;
                   11726:         if (form.elements[chosen].value == 'dependency') {
                   11727:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11728:             form.elements[depitem].options.length = 0;
                   11729:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  11730:             for (var i=1; i<=numitems; i++) {
                   11731:                 if (i == count) {
                   11732:                     continue;
                   11733:                 }
1.1059    raeburn  11734:                 var startelement = $startcount + (i-1) * 7;
                   11735:                 for (var j=1; j<6; j++) {
                   11736:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11737:                         var item = startelement + j;
                   11738:                         if (form.elements[item].type == 'radio') {
                   11739:                             if (form.elements[item].checked) {
                   11740:                                 if (form.elements[item].value == 'display') {
                   11741:                                     var n = form.elements[depitem].options.length;
                   11742:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11743:                                 }
                   11744:                             }
                   11745:                         }
                   11746:                     }
                   11747:                 }
                   11748:             }
                   11749:         } else {
                   11750:             document.getElementById('arc_depon_'+count).style.display='none';
                   11751:             form.elements[depitem].options.length = 0;
                   11752:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11753:         }
1.1059    raeburn  11754:         titleCheck(form,count,offset);
1.1056    raeburn  11755:     }
                   11756: }
                   11757: 
                   11758: function propagateSelect(form,count,offset) {
                   11759:     if (count > 0) {
1.1065    raeburn  11760:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11761:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11762:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11763:             if (parents[count].length > 0) {
                   11764:                 for (var j=0; j<parents[count].length; j++) {
                   11765:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11766:                 }
                   11767:             }
                   11768:         }
                   11769:     }
                   11770: }
1.1056    raeburn  11771: 
                   11772: function containerSelect(form,count,offset,picked) {
                   11773:     if (count > 0) {
1.1065    raeburn  11774:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11775:         if (form.elements[item].type == 'radio') {
                   11776:             if (form.elements[item].value == 'dependency') {
                   11777:                 if (form.elements[item+1].type == 'select-one') {
                   11778:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11779:                         if (form.elements[item+1].options[i].value == picked) {
                   11780:                             form.elements[item+1].selectedIndex = i;
                   11781:                             break;
                   11782:                         }
                   11783:                     }
                   11784:                 }
                   11785:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11786:                     if (parents[count].length > 0) {
                   11787:                         for (var j=0; j<parents[count].length; j++) {
                   11788:                             containerSelect(form,parents[count][j],offset,picked);
                   11789:                         }
                   11790:                     }
                   11791:                 }
                   11792:             }
                   11793:         }
                   11794:     }
                   11795: }
                   11796: 
1.1059    raeburn  11797: function titleCheck(form,count,offset) {
                   11798:     if (count > 0) {
                   11799:         var chosen = (offset+$startcount)+7*(count-1);
                   11800:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11801:         var currtype = form.elements[depitem].type;
                   11802:         if (form.elements[chosen].value == 'display') {
                   11803:             document.getElementById('arc_title_'+count).style.display='block';
                   11804:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11805:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11806:             }
                   11807:         } else {
                   11808:             document.getElementById('arc_title_'+count).style.display='none';
                   11809:             if (currtype == 'text') { 
                   11810:                 document.getElementById('archive_title_'+count).value='';
                   11811:             }
                   11812:         }
                   11813:     }
                   11814:     return;
                   11815: }
                   11816: 
1.1055    raeburn  11817: // ]]>
                   11818: </script>
                   11819: END
                   11820:     return $scripttag;
                   11821: }
                   11822: 
                   11823: sub process_extracted_files {
1.1067    raeburn  11824:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11825:     my $numitems = $env{'form.archive_count'};
                   11826:     return unless ($numitems);
                   11827:     my @ids=&Apache::lonnet::current_machine_ids();
                   11828:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11829:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11830:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11831:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11832:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11833:         $pathtocheck = "$dir_root/$destination";
                   11834:         $dir = $dir_root;
                   11835:         $ishome = 1;
                   11836:     } else {
                   11837:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11838:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11839:         $dir = "$dir_root/$docudom/$docuname";    
                   11840:     }
                   11841:     my $currdir = "$dir_root/$destination";
                   11842:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11843:     if ($env{'form.folderpath'}) {
                   11844:         my @items = split('&',$env{'form.folderpath'});
                   11845:         $folders{'0'} = $items[-2];
1.1099    raeburn  11846:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11847:             $containers{'0'}='page';
                   11848:         } else {  
                   11849:             $containers{'0'}='sequence';
                   11850:         }
1.1055    raeburn  11851:     }
                   11852:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11853:     if ($numitems) {
                   11854:         for (my $i=1; $i<=$numitems; $i++) {
                   11855:             my $path = $env{'form.archive_content_'.$i};
                   11856:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11857:                 my $item = $1;
                   11858:                 $toplevelitems{$item} = $i;
                   11859:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11860:                     $is_dir{$item} = 1;
                   11861:                 }
                   11862:             }
                   11863:         }
                   11864:     }
1.1067    raeburn  11865:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11866:     if (keys(%toplevelitems) > 0) {
                   11867:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11868:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11869:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11870:     }
1.1066    raeburn  11871:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11872:     if ($numitems) {
                   11873:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  11874:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11875:             my $path = $env{'form.archive_content_'.$i};
                   11876:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11877:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11878:                     if ($prefix ne '' && $path ne '') {
                   11879:                         if (-e $prefix.$path) {
1.1066    raeburn  11880:                             if ((@archdirs > 0) && 
                   11881:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11882:                                 $todeletedir{$prefix.$path} = 1;
                   11883:                             } else {
                   11884:                                 $todelete{$prefix.$path} = 1;
                   11885:                             }
1.1055    raeburn  11886:                         }
                   11887:                     }
                   11888:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11889:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11890:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11891:                     $docstitle = $env{'form.archive_title_'.$i};
                   11892:                     if ($docstitle eq '') {
                   11893:                         $docstitle = $title;
                   11894:                     }
1.1055    raeburn  11895:                     $outer = 0;
1.1056    raeburn  11896:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11897:                         if (@{$dirorder{$i}} > 0) {
                   11898:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11899:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11900:                                     $outer = $item;
                   11901:                                     last;
                   11902:                                 }
                   11903:                             }
                   11904:                         }
                   11905:                     }
                   11906:                     my ($errtext,$fatal) = 
                   11907:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11908:                                                '/'.$folders{$outer}.'.'.
                   11909:                                                $containers{$outer});
                   11910:                     next if ($fatal);
                   11911:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11912:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11913:                             $mapinner{$i} = time;
1.1055    raeburn  11914:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11915:                             $containers{$i} = 'sequence';
                   11916:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11917:                                       $folders{$i}.'.'.$containers{$i};
                   11918:                             my $newidx = &LONCAPA::map::getresidx();
                   11919:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11920:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11921:                             push(@LONCAPA::map::order,$newidx);
                   11922:                             my ($outtext,$errtext) =
                   11923:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11924:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11925:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11926:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11927:                             unless ($errtext) {
                   11928:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11929:                             }
1.1055    raeburn  11930:                         }
                   11931:                     } else {
                   11932:                         if ($context eq 'coursedocs') {
                   11933:                             my $newidx=&LONCAPA::map::getresidx();
                   11934:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11935:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11936:                                       $title;
                   11937:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11938:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11939:                             }
                   11940:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11941:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11942:                             }
                   11943:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11944:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11945:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11946:                                 unless ($ishome) {
                   11947:                                     my $fetch = "$newdest{$i}/$title";
                   11948:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11949:                                     $prompttofetch{$fetch} = 1;
                   11950:                                 }
1.1055    raeburn  11951:                             }
                   11952:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11953:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11954:                             push(@LONCAPA::map::order, $newidx);
                   11955:                             my ($outtext,$errtext)=
                   11956:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11957:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11958:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11959:                             unless ($errtext) {
                   11960:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11961:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11962:                                 }
                   11963:                             }
1.1055    raeburn  11964:                         }
                   11965:                     }
1.1086    raeburn  11966:                 }
                   11967:             } else {
                   11968:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11969:             }
                   11970:         }
                   11971:         for (my $i=1; $i<=$numitems; $i++) {
                   11972:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11973:             my $path = $env{'form.archive_content_'.$i};
                   11974:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11975:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11976:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11977:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11978:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11979:                         my ($itemidx,$fullpath,$relpath);
                   11980:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11981:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11982:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  11983:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11984:                                     $itemidx = $j;
1.1056    raeburn  11985:                                 }
                   11986:                             }
1.1086    raeburn  11987:                         }
                   11988:                         if ($itemidx eq '') {
                   11989:                             $itemidx =  0;
                   11990:                         } 
                   11991:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11992:                             if ($mapinner{$referrer{$i}}) {
                   11993:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11994:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11995:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11996:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11997:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11998:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11999:                                             if (!-e $fullpath) {
                   12000:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12001:                                             }
                   12002:                                         }
1.1086    raeburn  12003:                                     } else {
                   12004:                                         last;
1.1056    raeburn  12005:                                     }
1.1086    raeburn  12006:                                 }
                   12007:                             }
                   12008:                         } elsif ($newdest{$referrer{$i}}) {
                   12009:                             $fullpath = $newdest{$referrer{$i}};
                   12010:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12011:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12012:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12013:                                     last;
                   12014:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12015:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12016:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12017:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12018:                                         if (!-e $fullpath) {
                   12019:                                             mkdir($fullpath,0755);
1.1056    raeburn  12020:                                         }
                   12021:                                     }
1.1086    raeburn  12022:                                 } else {
                   12023:                                     last;
1.1056    raeburn  12024:                                 }
1.1055    raeburn  12025:                             }
                   12026:                         }
1.1086    raeburn  12027:                         if ($fullpath ne '') {
                   12028:                             if (-e "$prefix$path") {
                   12029:                                 system("mv $prefix$path $fullpath/$title");
                   12030:                             }
                   12031:                             if (-e "$fullpath/$title") {
                   12032:                                 my $showpath;
                   12033:                                 if ($relpath ne '') {
                   12034:                                     $showpath = "$relpath/$title";
                   12035:                                 } else {
                   12036:                                     $showpath = "/$title";
                   12037:                                 } 
                   12038:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12039:                             } 
                   12040:                             unless ($ishome) {
                   12041:                                 my $fetch = "$fullpath/$title";
                   12042:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12043:                                 $prompttofetch{$fetch} = 1;
                   12044:                             }
                   12045:                         }
1.1055    raeburn  12046:                     }
1.1086    raeburn  12047:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12048:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12049:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12050:                 }
                   12051:             } else {
                   12052:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12053:             }
                   12054:         }
                   12055:         if (keys(%todelete)) {
                   12056:             foreach my $key (keys(%todelete)) {
                   12057:                 unlink($key);
1.1066    raeburn  12058:             }
                   12059:         }
                   12060:         if (keys(%todeletedir)) {
                   12061:             foreach my $key (keys(%todeletedir)) {
                   12062:                 rmdir($key);
                   12063:             }
                   12064:         }
                   12065:         foreach my $dir (sort(keys(%is_dir))) {
                   12066:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12067:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12068:             }
                   12069:         }
1.1067    raeburn  12070:         if ($result ne '') {
                   12071:             $output .= '<ul>'."\n".
                   12072:                        $result."\n".
                   12073:                        '</ul>';
                   12074:         }
                   12075:         unless ($ishome) {
                   12076:             my $replicationfail;
                   12077:             foreach my $item (keys(%prompttofetch)) {
                   12078:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12079:                 unless ($fetchresult eq 'ok') {
                   12080:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12081:                 }
                   12082:             }
                   12083:             if ($replicationfail) {
                   12084:                 $output .= '<p class="LC_error">'.
                   12085:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12086:                            $replicationfail.
                   12087:                            '</ul></p>';
                   12088:             }
                   12089:         }
1.1055    raeburn  12090:     } else {
                   12091:         $warning = &mt('No items found in archive.');
                   12092:     }
                   12093:     if ($error) {
                   12094:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12095:                    $error.'</p>'."\n";
                   12096:     }
                   12097:     if ($warning) {
                   12098:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12099:     }
                   12100:     return $output;
                   12101: }
                   12102: 
1.1066    raeburn  12103: sub cleanup_empty_dirs {
                   12104:     my ($path) = @_;
                   12105:     if (($path ne '') && (-d $path)) {
                   12106:         if (opendir(my $dirh,$path)) {
                   12107:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12108:             my $numitems = 0;
                   12109:             foreach my $item (@dircontents) {
                   12110:                 if (-d "$path/$item") {
1.1111    raeburn  12111:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12112:                     if (-e "$path/$item") {
                   12113:                         $numitems ++;
                   12114:                     }
                   12115:                 } else {
                   12116:                     $numitems ++;
                   12117:                 }
                   12118:             }
                   12119:             if ($numitems == 0) {
                   12120:                 rmdir($path);
                   12121:             }
                   12122:             closedir($dirh);
                   12123:         }
                   12124:     }
                   12125:     return;
                   12126: }
                   12127: 
1.41      ng       12128: =pod
1.45      matthew  12129: 
1.1162    raeburn  12130: =item * &get_folder_hierarchy()
1.1068    raeburn  12131: 
                   12132: Provides hierarchy of names of folders/sub-folders containing the current
                   12133: item,
                   12134: 
                   12135: Inputs: 3
                   12136:      - $navmap - navmaps object
                   12137: 
                   12138:      - $map - url for map (either the trigger itself, or map containing
                   12139:                            the resource, which is the trigger).
                   12140: 
                   12141:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12142: 
                   12143: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12144: 
                   12145: =cut
                   12146: 
                   12147: sub get_folder_hierarchy {
                   12148:     my ($navmap,$map,$showitem) = @_;
                   12149:     my @pathitems;
                   12150:     if (ref($navmap)) {
                   12151:         my $mapres = $navmap->getResourceByUrl($map);
                   12152:         if (ref($mapres)) {
                   12153:             my $pcslist = $mapres->map_hierarchy();
                   12154:             if ($pcslist ne '') {
                   12155:                 my @pcs = split(/,/,$pcslist);
                   12156:                 foreach my $pc (@pcs) {
                   12157:                     if ($pc == 1) {
1.1129    raeburn  12158:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12159:                     } else {
                   12160:                         my $res = $navmap->getByMapPc($pc);
                   12161:                         if (ref($res)) {
                   12162:                             my $title = $res->compTitle();
                   12163:                             $title =~ s/\W+/_/g;
                   12164:                             if ($title ne '') {
                   12165:                                 push(@pathitems,$title);
                   12166:                             }
                   12167:                         }
                   12168:                     }
                   12169:                 }
                   12170:             }
1.1071    raeburn  12171:             if ($showitem) {
                   12172:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12173:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12174:                 } else {
                   12175:                     my $maptitle = $mapres->compTitle();
                   12176:                     $maptitle =~ s/\W+/_/g;
                   12177:                     if ($maptitle ne '') {
                   12178:                         push(@pathitems,$maptitle);
                   12179:                     }
1.1068    raeburn  12180:                 }
                   12181:             }
                   12182:         }
                   12183:     }
                   12184:     return @pathitems;
                   12185: }
                   12186: 
                   12187: =pod
                   12188: 
1.1015    raeburn  12189: =item * &get_turnedin_filepath()
                   12190: 
                   12191: Determines path in a user's portfolio file for storage of files uploaded
                   12192: to a specific essayresponse or dropbox item.
                   12193: 
                   12194: Inputs: 3 required + 1 optional.
                   12195: $symb is symb for resource, $uname and $udom are for current user (required).
                   12196: $caller is optional (can be "submission", if routine is called when storing
                   12197: an upoaded file when "Submit Answer" button was pressed).
                   12198: 
                   12199: Returns array containing $path and $multiresp. 
                   12200: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12201: than one file upload item.  Callers of routine should append partid as a 
                   12202: subdirectory to $path in cases where $multiresp is 1.
                   12203: 
                   12204: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12205: 
                   12206: =cut
                   12207: 
                   12208: sub get_turnedin_filepath {
                   12209:     my ($symb,$uname,$udom,$caller) = @_;
                   12210:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12211:     my $turnindir;
                   12212:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12213:     $turnindir = $userhash{'turnindir'};
                   12214:     my ($path,$multiresp);
                   12215:     if ($turnindir eq '') {
                   12216:         if ($caller eq 'submission') {
                   12217:             $turnindir = &mt('turned in');
                   12218:             $turnindir =~ s/\W+/_/g;
                   12219:             my %newhash = (
                   12220:                             'turnindir' => $turnindir,
                   12221:                           );
                   12222:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12223:         }
                   12224:     }
                   12225:     if ($turnindir ne '') {
                   12226:         $path = '/'.$turnindir.'/';
                   12227:         my ($multipart,$turnin,@pathitems);
                   12228:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12229:         if (defined($navmap)) {
                   12230:             my $mapres = $navmap->getResourceByUrl($map);
                   12231:             if (ref($mapres)) {
                   12232:                 my $pcslist = $mapres->map_hierarchy();
                   12233:                 if ($pcslist ne '') {
                   12234:                     foreach my $pc (split(/,/,$pcslist)) {
                   12235:                         my $res = $navmap->getByMapPc($pc);
                   12236:                         if (ref($res)) {
                   12237:                             my $title = $res->compTitle();
                   12238:                             $title =~ s/\W+/_/g;
                   12239:                             if ($title ne '') {
1.1149    raeburn  12240:                                 if (($pc > 1) && (length($title) > 12)) {
                   12241:                                     $title = substr($title,0,12);
                   12242:                                 }
1.1015    raeburn  12243:                                 push(@pathitems,$title);
                   12244:                             }
                   12245:                         }
                   12246:                     }
                   12247:                 }
                   12248:                 my $maptitle = $mapres->compTitle();
                   12249:                 $maptitle =~ s/\W+/_/g;
                   12250:                 if ($maptitle ne '') {
1.1149    raeburn  12251:                     if (length($maptitle) > 12) {
                   12252:                         $maptitle = substr($maptitle,0,12);
                   12253:                     }
1.1015    raeburn  12254:                     push(@pathitems,$maptitle);
                   12255:                 }
                   12256:                 unless ($env{'request.state'} eq 'construct') {
                   12257:                     my $res = $navmap->getBySymb($symb);
                   12258:                     if (ref($res)) {
                   12259:                         my $partlist = $res->parts();
                   12260:                         my $totaluploads = 0;
                   12261:                         if (ref($partlist) eq 'ARRAY') {
                   12262:                             foreach my $part (@{$partlist}) {
                   12263:                                 my @types = $res->responseType($part);
                   12264:                                 my @ids = $res->responseIds($part);
                   12265:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12266:                                     if ($types[$i] eq 'essay') {
                   12267:                                         my $partid = $part.'_'.$ids[$i];
                   12268:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12269:                                             $totaluploads ++;
                   12270:                                         }
                   12271:                                     }
                   12272:                                 }
                   12273:                             }
                   12274:                             if ($totaluploads > 1) {
                   12275:                                 $multiresp = 1;
                   12276:                             }
                   12277:                         }
                   12278:                     }
                   12279:                 }
                   12280:             } else {
                   12281:                 return;
                   12282:             }
                   12283:         } else {
                   12284:             return;
                   12285:         }
                   12286:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12287:         $restitle =~ s/\W+/_/g;
                   12288:         if ($restitle eq '') {
                   12289:             $restitle = ($resurl =~ m{/[^/]+$});
                   12290:             if ($restitle eq '') {
                   12291:                 $restitle = time;
                   12292:             }
                   12293:         }
1.1149    raeburn  12294:         if (length($restitle) > 12) {
                   12295:             $restitle = substr($restitle,0,12);
                   12296:         }
1.1015    raeburn  12297:         push(@pathitems,$restitle);
                   12298:         $path .= join('/',@pathitems);
                   12299:     }
                   12300:     return ($path,$multiresp);
                   12301: }
                   12302: 
                   12303: =pod
                   12304: 
1.464     albertel 12305: =back
1.41      ng       12306: 
1.112     bowersj2 12307: =head1 CSV Upload/Handling functions
1.38      albertel 12308: 
1.41      ng       12309: =over 4
                   12310: 
1.648     raeburn  12311: =item * &upfile_store($r)
1.41      ng       12312: 
                   12313: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12314: needs $env{'form.upfile'}
1.41      ng       12315: returns $datatoken to be put into hidden field
                   12316: 
                   12317: =cut
1.31      albertel 12318: 
                   12319: sub upfile_store {
                   12320:     my $r=shift;
1.258     albertel 12321:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12322:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12323:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12324:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12325: 
1.258     albertel 12326:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12327: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12328:     {
1.158     raeburn  12329:         my $datafile = $r->dir_config('lonDaemons').
                   12330:                            '/tmp/'.$datatoken.'.tmp';
                   12331:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12332:             print $fh $env{'form.upfile'};
1.158     raeburn  12333:             close($fh);
                   12334:         }
1.31      albertel 12335:     }
                   12336:     return $datatoken;
                   12337: }
                   12338: 
1.56      matthew  12339: =pod
                   12340: 
1.648     raeburn  12341: =item * &load_tmp_file($r)
1.41      ng       12342: 
                   12343: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12344: needs $env{'form.datatoken'},
                   12345: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12346: 
                   12347: =cut
1.31      albertel 12348: 
                   12349: sub load_tmp_file {
                   12350:     my $r=shift;
                   12351:     my @studentdata=();
                   12352:     {
1.158     raeburn  12353:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12354:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12355:         if ( open(my $fh,"<$studentfile") ) {
                   12356:             @studentdata=<$fh>;
                   12357:             close($fh);
                   12358:         }
1.31      albertel 12359:     }
1.258     albertel 12360:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12361: }
                   12362: 
1.56      matthew  12363: =pod
                   12364: 
1.648     raeburn  12365: =item * &upfile_record_sep()
1.41      ng       12366: 
                   12367: Separate uploaded file into records
                   12368: returns array of records,
1.258     albertel 12369: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12370: 
                   12371: =cut
1.31      albertel 12372: 
                   12373: sub upfile_record_sep {
1.258     albertel 12374:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12375:     } else {
1.248     albertel 12376: 	my @records;
1.258     albertel 12377: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12378: 	    if ($line=~/^\s*$/) { next; }
                   12379: 	    push(@records,$line);
                   12380: 	}
                   12381: 	return @records;
1.31      albertel 12382:     }
                   12383: }
                   12384: 
1.56      matthew  12385: =pod
                   12386: 
1.648     raeburn  12387: =item * &record_sep($record)
1.41      ng       12388: 
1.258     albertel 12389: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12390: 
                   12391: =cut
                   12392: 
1.263     www      12393: sub takeleft {
                   12394:     my $index=shift;
                   12395:     return substr('0000'.$index,-4,4);
                   12396: }
                   12397: 
1.31      albertel 12398: sub record_sep {
                   12399:     my $record=shift;
                   12400:     my %components=();
1.258     albertel 12401:     if ($env{'form.upfiletype'} eq 'xml') {
                   12402:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12403:         my $i=0;
1.356     albertel 12404:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12405:             $field=~s/^(\"|\')//;
                   12406:             $field=~s/(\"|\')$//;
1.263     www      12407:             $components{&takeleft($i)}=$field;
1.31      albertel 12408:             $i++;
                   12409:         }
1.258     albertel 12410:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12411:         my $i=0;
1.356     albertel 12412:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12413:             $field=~s/^(\"|\')//;
                   12414:             $field=~s/(\"|\')$//;
1.263     www      12415:             $components{&takeleft($i)}=$field;
1.31      albertel 12416:             $i++;
                   12417:         }
                   12418:     } else {
1.561     www      12419:         my $separator=',';
1.480     banghart 12420:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12421:             $separator=';';
1.480     banghart 12422:         }
1.31      albertel 12423:         my $i=0;
1.561     www      12424: # the character we are looking for to indicate the end of a quote or a record 
                   12425:         my $looking_for=$separator;
                   12426: # do not add the characters to the fields
                   12427:         my $ignore=0;
                   12428: # we just encountered a separator (or the beginning of the record)
                   12429:         my $just_found_separator=1;
                   12430: # store the field we are working on here
                   12431:         my $field='';
                   12432: # work our way through all characters in record
                   12433:         foreach my $character ($record=~/(.)/g) {
                   12434:             if ($character eq $looking_for) {
                   12435:                if ($character ne $separator) {
                   12436: # Found the end of a quote, again looking for separator
                   12437:                   $looking_for=$separator;
                   12438:                   $ignore=1;
                   12439:                } else {
                   12440: # Found a separator, store away what we got
                   12441:                   $components{&takeleft($i)}=$field;
                   12442: 	          $i++;
                   12443:                   $just_found_separator=1;
                   12444:                   $ignore=0;
                   12445:                   $field='';
                   12446:                }
                   12447:                next;
                   12448:             }
                   12449: # single or double quotation marks after a separator indicate beginning of a quote
                   12450: # we are now looking for the end of the quote and need to ignore separators
                   12451:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12452:                $looking_for=$character;
                   12453:                next;
                   12454:             }
                   12455: # ignore would be true after we reached the end of a quote
                   12456:             if ($ignore) { next; }
                   12457:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12458:             $field.=$character;
                   12459:             $just_found_separator=0; 
1.31      albertel 12460:         }
1.561     www      12461: # catch the very last entry, since we never encountered the separator
                   12462:         $components{&takeleft($i)}=$field;
1.31      albertel 12463:     }
                   12464:     return %components;
                   12465: }
                   12466: 
1.144     matthew  12467: ######################################################
                   12468: ######################################################
                   12469: 
1.56      matthew  12470: =pod
                   12471: 
1.648     raeburn  12472: =item * &upfile_select_html()
1.41      ng       12473: 
1.144     matthew  12474: Return HTML code to select a file from the users machine and specify 
                   12475: the file type.
1.41      ng       12476: 
                   12477: =cut
                   12478: 
1.144     matthew  12479: ######################################################
                   12480: ######################################################
1.31      albertel 12481: sub upfile_select_html {
1.144     matthew  12482:     my %Types = (
                   12483:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12484:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12485:                  space => &mt('Space separated'),
                   12486:                  tab   => &mt('Tabulator separated'),
                   12487: #                 xml   => &mt('HTML/XML'),
                   12488:                  );
                   12489:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12490:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12491:     foreach my $type (sort(keys(%Types))) {
                   12492:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12493:     }
                   12494:     $Str .= "</select>\n";
                   12495:     return $Str;
1.31      albertel 12496: }
                   12497: 
1.301     albertel 12498: sub get_samples {
                   12499:     my ($records,$toget) = @_;
                   12500:     my @samples=({});
                   12501:     my $got=0;
                   12502:     foreach my $rec (@$records) {
                   12503: 	my %temp = &record_sep($rec);
                   12504: 	if (! grep(/\S/, values(%temp))) { next; }
                   12505: 	if (%temp) {
                   12506: 	    $samples[$got]=\%temp;
                   12507: 	    $got++;
                   12508: 	    if ($got == $toget) { last; }
                   12509: 	}
                   12510:     }
                   12511:     return \@samples;
                   12512: }
                   12513: 
1.144     matthew  12514: ######################################################
                   12515: ######################################################
                   12516: 
1.56      matthew  12517: =pod
                   12518: 
1.648     raeburn  12519: =item * &csv_print_samples($r,$records)
1.41      ng       12520: 
                   12521: Prints a table of sample values from each column uploaded $r is an
                   12522: Apache Request ref, $records is an arrayref from
                   12523: &Apache::loncommon::upfile_record_sep
                   12524: 
                   12525: =cut
                   12526: 
1.144     matthew  12527: ######################################################
                   12528: ######################################################
1.31      albertel 12529: sub csv_print_samples {
                   12530:     my ($r,$records) = @_;
1.662     bisitz   12531:     my $samples = &get_samples($records,5);
1.301     albertel 12532: 
1.594     raeburn  12533:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12534:               &start_data_table_header_row());
1.356     albertel 12535:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12536:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12537:     $r->print(&end_data_table_header_row());
1.301     albertel 12538:     foreach my $hash (@$samples) {
1.594     raeburn  12539: 	$r->print(&start_data_table_row());
1.356     albertel 12540: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12541: 	    $r->print('<td>');
1.356     albertel 12542: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12543: 	    $r->print('</td>');
                   12544: 	}
1.594     raeburn  12545: 	$r->print(&end_data_table_row());
1.31      albertel 12546:     }
1.594     raeburn  12547:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12548: }
                   12549: 
1.144     matthew  12550: ######################################################
                   12551: ######################################################
                   12552: 
1.56      matthew  12553: =pod
                   12554: 
1.648     raeburn  12555: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12556: 
                   12557: Prints a table to create associations between values and table columns.
1.144     matthew  12558: 
1.41      ng       12559: $r is an Apache Request ref,
                   12560: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12561: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12562: 
                   12563: =cut
                   12564: 
1.144     matthew  12565: ######################################################
                   12566: ######################################################
1.31      albertel 12567: sub csv_print_select_table {
                   12568:     my ($r,$records,$d) = @_;
1.301     albertel 12569:     my $i=0;
                   12570:     my $samples = &get_samples($records,1);
1.144     matthew  12571:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12572: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12573:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12574:               '<th>'.&mt('Column').'</th>'.
                   12575:               &end_data_table_header_row()."\n");
1.356     albertel 12576:     foreach my $array_ref (@$d) {
                   12577: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12578: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12579: 
1.875     bisitz   12580: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12581: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12582: 	$r->print('<option value="none"></option>');
1.356     albertel 12583: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12584: 	    $r->print('<option value="'.$sample.'"'.
                   12585:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12586:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12587: 	}
1.594     raeburn  12588: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12589: 	$i++;
                   12590:     }
1.594     raeburn  12591:     $r->print(&end_data_table());
1.31      albertel 12592:     $i--;
                   12593:     return $i;
                   12594: }
1.56      matthew  12595: 
1.144     matthew  12596: ######################################################
                   12597: ######################################################
                   12598: 
1.56      matthew  12599: =pod
1.31      albertel 12600: 
1.648     raeburn  12601: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12602: 
                   12603: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12604: 
                   12605: $r is an Apache Request ref,
                   12606: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12607: $d is an array of 2 element arrays (internal name, displayed name)
                   12608: 
                   12609: =cut
                   12610: 
1.144     matthew  12611: ######################################################
                   12612: ######################################################
1.31      albertel 12613: sub csv_samples_select_table {
                   12614:     my ($r,$records,$d) = @_;
                   12615:     my $i=0;
1.144     matthew  12616:     #
1.662     bisitz   12617:     my $max_samples = 5;
                   12618:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12619:     $r->print(&start_data_table().
                   12620:               &start_data_table_header_row().'<th>'.
                   12621:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12622:               &end_data_table_header_row());
1.301     albertel 12623: 
                   12624:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12625: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12626: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12627: 	foreach my $option (@$d) {
                   12628: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12629: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12630:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12631:                       $display.'</option>');
1.31      albertel 12632: 	}
                   12633: 	$r->print('</select></td><td>');
1.662     bisitz   12634: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12635: 	    if (defined($samples->[$line]{$key})) { 
                   12636: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12637: 	    }
                   12638: 	}
1.594     raeburn  12639: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12640: 	$i++;
                   12641:     }
1.594     raeburn  12642:     $r->print(&end_data_table());
1.31      albertel 12643:     $i--;
                   12644:     return($i);
1.115     matthew  12645: }
                   12646: 
1.144     matthew  12647: ######################################################
                   12648: ######################################################
                   12649: 
1.115     matthew  12650: =pod
                   12651: 
1.648     raeburn  12652: =item * &clean_excel_name($name)
1.115     matthew  12653: 
                   12654: Returns a replacement for $name which does not contain any illegal characters.
                   12655: 
                   12656: =cut
                   12657: 
1.144     matthew  12658: ######################################################
                   12659: ######################################################
1.115     matthew  12660: sub clean_excel_name {
                   12661:     my ($name) = @_;
                   12662:     $name =~ s/[:\*\?\/\\]//g;
                   12663:     if (length($name) > 31) {
                   12664:         $name = substr($name,0,31);
                   12665:     }
                   12666:     return $name;
1.25      albertel 12667: }
1.84      albertel 12668: 
1.85      albertel 12669: =pod
                   12670: 
1.648     raeburn  12671: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12672: 
                   12673: Returns either 1 or undef
                   12674: 
                   12675: 1 if the part is to be hidden, undef if it is to be shown
                   12676: 
                   12677: Arguments are:
                   12678: 
                   12679: $id the id of the part to be checked
                   12680: $symb, optional the symb of the resource to check
                   12681: $udom, optional the domain of the user to check for
                   12682: $uname, optional the username of the user to check for
                   12683: 
                   12684: =cut
1.84      albertel 12685: 
                   12686: sub check_if_partid_hidden {
                   12687:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12688:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12689: 					 $symb,$udom,$uname);
1.141     albertel 12690:     my $truth=1;
                   12691:     #if the string starts with !, then the list is the list to show not hide
                   12692:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12693:     my @hiddenlist=split(/,/,$hiddenparts);
                   12694:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12695: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12696:     }
1.141     albertel 12697:     return !$truth;
1.84      albertel 12698: }
1.127     matthew  12699: 
1.138     matthew  12700: 
                   12701: ############################################################
                   12702: ############################################################
                   12703: 
                   12704: =pod
                   12705: 
1.157     matthew  12706: =back 
                   12707: 
1.138     matthew  12708: =head1 cgi-bin script and graphing routines
                   12709: 
1.157     matthew  12710: =over 4
                   12711: 
1.648     raeburn  12712: =item * &get_cgi_id()
1.138     matthew  12713: 
                   12714: Inputs: none
                   12715: 
                   12716: Returns an id which can be used to pass environment variables
                   12717: to various cgi-bin scripts.  These environment variables will
                   12718: be removed from the users environment after a given time by
                   12719: the routine &Apache::lonnet::transfer_profile_to_env.
                   12720: 
                   12721: =cut
                   12722: 
                   12723: ############################################################
                   12724: ############################################################
1.152     albertel 12725: my $uniq=0;
1.136     matthew  12726: sub get_cgi_id {
1.154     albertel 12727:     $uniq=($uniq+1)%100000;
1.280     albertel 12728:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12729: }
                   12730: 
1.127     matthew  12731: ############################################################
                   12732: ############################################################
                   12733: 
                   12734: =pod
                   12735: 
1.648     raeburn  12736: =item * &DrawBarGraph()
1.127     matthew  12737: 
1.138     matthew  12738: Facilitates the plotting of data in a (stacked) bar graph.
                   12739: Puts plot definition data into the users environment in order for 
                   12740: graph.png to plot it.  Returns an <img> tag for the plot.
                   12741: The bars on the plot are labeled '1','2',...,'n'.
                   12742: 
                   12743: Inputs:
                   12744: 
                   12745: =over 4
                   12746: 
                   12747: =item $Title: string, the title of the plot
                   12748: 
                   12749: =item $xlabel: string, text describing the X-axis of the plot
                   12750: 
                   12751: =item $ylabel: string, text describing the Y-axis of the plot
                   12752: 
                   12753: =item $Max: scalar, the maximum Y value to use in the plot
                   12754: If $Max is < any data point, the graph will not be rendered.
                   12755: 
1.140     matthew  12756: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12757: they are plotted.  If undefined, default values will be used.
                   12758: 
1.178     matthew  12759: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12760: 
1.138     matthew  12761: =item @Values: An array of array references.  Each array reference holds data
                   12762: to be plotted in a stacked bar chart.
                   12763: 
1.239     matthew  12764: =item If the final element of @Values is a hash reference the key/value
                   12765: pairs will be added to the graph definition.
                   12766: 
1.138     matthew  12767: =back
                   12768: 
                   12769: Returns:
                   12770: 
                   12771: An <img> tag which references graph.png and the appropriate identifying
                   12772: information for the plot.
                   12773: 
1.127     matthew  12774: =cut
                   12775: 
                   12776: ############################################################
                   12777: ############################################################
1.134     matthew  12778: sub DrawBarGraph {
1.178     matthew  12779:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12780:     #
                   12781:     if (! defined($colors)) {
                   12782:         $colors = ['#33ff00', 
                   12783:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12784:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12785:                   ]; 
                   12786:     }
1.228     matthew  12787:     my $extra_settings = {};
                   12788:     if (ref($Values[-1]) eq 'HASH') {
                   12789:         $extra_settings = pop(@Values);
                   12790:     }
1.127     matthew  12791:     #
1.136     matthew  12792:     my $identifier = &get_cgi_id();
                   12793:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12794:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12795:         return '';
                   12796:     }
1.225     matthew  12797:     #
                   12798:     my @Labels;
                   12799:     if (defined($labels)) {
                   12800:         @Labels = @$labels;
                   12801:     } else {
                   12802:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12803:             push (@Labels,$i+1);
                   12804:         }
                   12805:     }
                   12806:     #
1.129     matthew  12807:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12808:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12809:     my %ValuesHash;
                   12810:     my $NumSets=1;
                   12811:     foreach my $array (@Values) {
                   12812:         next if (! ref($array));
1.136     matthew  12813:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12814:             join(',',@$array);
1.129     matthew  12815:     }
1.127     matthew  12816:     #
1.136     matthew  12817:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12818:     if ($NumBars < 3) {
                   12819:         $width = 120+$NumBars*32;
1.220     matthew  12820:         $xskip = 1;
1.225     matthew  12821:         $bar_width = 30;
                   12822:     } elsif ($NumBars < 5) {
                   12823:         $width = 120+$NumBars*20;
                   12824:         $xskip = 1;
                   12825:         $bar_width = 20;
1.220     matthew  12826:     } elsif ($NumBars < 10) {
1.136     matthew  12827:         $width = 120+$NumBars*15;
                   12828:         $xskip = 1;
                   12829:         $bar_width = 15;
                   12830:     } elsif ($NumBars <= 25) {
                   12831:         $width = 120+$NumBars*11;
                   12832:         $xskip = 5;
                   12833:         $bar_width = 8;
                   12834:     } elsif ($NumBars <= 50) {
                   12835:         $width = 120+$NumBars*8;
                   12836:         $xskip = 5;
                   12837:         $bar_width = 4;
                   12838:     } else {
                   12839:         $width = 120+$NumBars*8;
                   12840:         $xskip = 5;
                   12841:         $bar_width = 4;
                   12842:     }
                   12843:     #
1.137     matthew  12844:     $Max = 1 if ($Max < 1);
                   12845:     if ( int($Max) < $Max ) {
                   12846:         $Max++;
                   12847:         $Max = int($Max);
                   12848:     }
1.127     matthew  12849:     $Title  = '' if (! defined($Title));
                   12850:     $xlabel = '' if (! defined($xlabel));
                   12851:     $ylabel = '' if (! defined($ylabel));
1.369     www      12852:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12853:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12854:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12855:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12856:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12857:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12858:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12859:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12860:     $ValuesHash{$id.'.height'}   = $height;
                   12861:     $ValuesHash{$id.'.width'}    = $width;
                   12862:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12863:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12864:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12865:     #
1.228     matthew  12866:     # Deal with other parameters
                   12867:     while (my ($key,$value) = each(%$extra_settings)) {
                   12868:         $ValuesHash{$id.'.'.$key} = $value;
                   12869:     }
                   12870:     #
1.646     raeburn  12871:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12872:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12873: }
                   12874: 
                   12875: ############################################################
                   12876: ############################################################
                   12877: 
                   12878: =pod
                   12879: 
1.648     raeburn  12880: =item * &DrawXYGraph()
1.137     matthew  12881: 
1.138     matthew  12882: Facilitates the plotting of data in an XY graph.
                   12883: Puts plot definition data into the users environment in order for 
                   12884: graph.png to plot it.  Returns an <img> tag for the plot.
                   12885: 
                   12886: Inputs:
                   12887: 
                   12888: =over 4
                   12889: 
                   12890: =item $Title: string, the title of the plot
                   12891: 
                   12892: =item $xlabel: string, text describing the X-axis of the plot
                   12893: 
                   12894: =item $ylabel: string, text describing the Y-axis of the plot
                   12895: 
                   12896: =item $Max: scalar, the maximum Y value to use in the plot
                   12897: If $Max is < any data point, the graph will not be rendered.
                   12898: 
                   12899: =item $colors: Array ref containing the hex color codes for the data to be 
                   12900: plotted in.  If undefined, default values will be used.
                   12901: 
                   12902: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12903: 
                   12904: =item $Ydata: Array ref containing Array refs.  
1.185     www      12905: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12906: 
                   12907: =item %Values: hash indicating or overriding any default values which are 
                   12908: passed to graph.png.  
                   12909: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12910: 
                   12911: =back
                   12912: 
                   12913: Returns:
                   12914: 
                   12915: An <img> tag which references graph.png and the appropriate identifying
                   12916: information for the plot.
                   12917: 
1.137     matthew  12918: =cut
                   12919: 
                   12920: ############################################################
                   12921: ############################################################
                   12922: sub DrawXYGraph {
                   12923:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12924:     #
                   12925:     # Create the identifier for the graph
                   12926:     my $identifier = &get_cgi_id();
                   12927:     my $id = 'cgi.'.$identifier;
                   12928:     #
                   12929:     $Title  = '' if (! defined($Title));
                   12930:     $xlabel = '' if (! defined($xlabel));
                   12931:     $ylabel = '' if (! defined($ylabel));
                   12932:     my %ValuesHash = 
                   12933:         (
1.369     www      12934:          $id.'.title'  => &escape($Title),
                   12935:          $id.'.xlabel' => &escape($xlabel),
                   12936:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12937:          $id.'.y_max_value'=> $Max,
                   12938:          $id.'.labels'     => join(',',@$Xlabels),
                   12939:          $id.'.PlotType'   => 'XY',
                   12940:          );
                   12941:     #
                   12942:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12943:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12944:     }
                   12945:     #
                   12946:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12947:         return '';
                   12948:     }
                   12949:     my $NumSets=1;
1.138     matthew  12950:     foreach my $array (@{$Ydata}){
1.137     matthew  12951:         next if (! ref($array));
                   12952:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12953:     }
1.138     matthew  12954:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12955:     #
                   12956:     # Deal with other parameters
                   12957:     while (my ($key,$value) = each(%Values)) {
                   12958:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12959:     }
                   12960:     #
1.646     raeburn  12961:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12962:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12963: }
                   12964: 
                   12965: ############################################################
                   12966: ############################################################
                   12967: 
                   12968: =pod
                   12969: 
1.648     raeburn  12970: =item * &DrawXYYGraph()
1.138     matthew  12971: 
                   12972: Facilitates the plotting of data in an XY graph with two Y axes.
                   12973: Puts plot definition data into the users environment in order for 
                   12974: graph.png to plot it.  Returns an <img> tag for the plot.
                   12975: 
                   12976: Inputs:
                   12977: 
                   12978: =over 4
                   12979: 
                   12980: =item $Title: string, the title of the plot
                   12981: 
                   12982: =item $xlabel: string, text describing the X-axis of the plot
                   12983: 
                   12984: =item $ylabel: string, text describing the Y-axis of the plot
                   12985: 
                   12986: =item $colors: Array ref containing the hex color codes for the data to be 
                   12987: plotted in.  If undefined, default values will be used.
                   12988: 
                   12989: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12990: 
                   12991: =item $Ydata1: The first data set
                   12992: 
                   12993: =item $Min1: The minimum value of the left Y-axis
                   12994: 
                   12995: =item $Max1: The maximum value of the left Y-axis
                   12996: 
                   12997: =item $Ydata2: The second data set
                   12998: 
                   12999: =item $Min2: The minimum value of the right Y-axis
                   13000: 
                   13001: =item $Max2: The maximum value of the left Y-axis
                   13002: 
                   13003: =item %Values: hash indicating or overriding any default values which are 
                   13004: passed to graph.png.  
                   13005: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13006: 
                   13007: =back
                   13008: 
                   13009: Returns:
                   13010: 
                   13011: An <img> tag which references graph.png and the appropriate identifying
                   13012: information for the plot.
1.136     matthew  13013: 
                   13014: =cut
                   13015: 
                   13016: ############################################################
                   13017: ############################################################
1.137     matthew  13018: sub DrawXYYGraph {
                   13019:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13020:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13021:     #
                   13022:     # Create the identifier for the graph
                   13023:     my $identifier = &get_cgi_id();
                   13024:     my $id = 'cgi.'.$identifier;
                   13025:     #
                   13026:     $Title  = '' if (! defined($Title));
                   13027:     $xlabel = '' if (! defined($xlabel));
                   13028:     $ylabel = '' if (! defined($ylabel));
                   13029:     my %ValuesHash = 
                   13030:         (
1.369     www      13031:          $id.'.title'  => &escape($Title),
                   13032:          $id.'.xlabel' => &escape($xlabel),
                   13033:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13034:          $id.'.labels' => join(',',@$Xlabels),
                   13035:          $id.'.PlotType' => 'XY',
                   13036:          $id.'.NumSets' => 2,
1.137     matthew  13037:          $id.'.two_axes' => 1,
                   13038:          $id.'.y1_max_value' => $Max1,
                   13039:          $id.'.y1_min_value' => $Min1,
                   13040:          $id.'.y2_max_value' => $Max2,
                   13041:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13042:          );
                   13043:     #
1.137     matthew  13044:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13045:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13046:     }
                   13047:     #
                   13048:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13049:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13050:         return '';
                   13051:     }
                   13052:     my $NumSets=1;
1.137     matthew  13053:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13054:         next if (! ref($array));
                   13055:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13056:     }
                   13057:     #
                   13058:     # Deal with other parameters
                   13059:     while (my ($key,$value) = each(%Values)) {
                   13060:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13061:     }
                   13062:     #
1.646     raeburn  13063:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13064:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13065: }
                   13066: 
                   13067: ############################################################
                   13068: ############################################################
                   13069: 
                   13070: =pod
                   13071: 
1.157     matthew  13072: =back 
                   13073: 
1.139     matthew  13074: =head1 Statistics helper routines?  
                   13075: 
                   13076: Bad place for them but what the hell.
                   13077: 
1.157     matthew  13078: =over 4
                   13079: 
1.648     raeburn  13080: =item * &chartlink()
1.139     matthew  13081: 
                   13082: Returns a link to the chart for a specific student.  
                   13083: 
                   13084: Inputs:
                   13085: 
                   13086: =over 4
                   13087: 
                   13088: =item $linktext: The text of the link
                   13089: 
                   13090: =item $sname: The students username
                   13091: 
                   13092: =item $sdomain: The students domain
                   13093: 
                   13094: =back
                   13095: 
1.157     matthew  13096: =back
                   13097: 
1.139     matthew  13098: =cut
                   13099: 
                   13100: ############################################################
                   13101: ############################################################
                   13102: sub chartlink {
                   13103:     my ($linktext, $sname, $sdomain) = @_;
                   13104:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13105:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13106:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13107:        '">'.$linktext.'</a>';
1.153     matthew  13108: }
                   13109: 
                   13110: #######################################################
                   13111: #######################################################
                   13112: 
                   13113: =pod
                   13114: 
                   13115: =head1 Course Environment Routines
1.157     matthew  13116: 
                   13117: =over 4
1.153     matthew  13118: 
1.648     raeburn  13119: =item * &restore_course_settings()
1.153     matthew  13120: 
1.648     raeburn  13121: =item * &store_course_settings()
1.153     matthew  13122: 
                   13123: Restores/Store indicated form parameters from the course environment.
                   13124: Will not overwrite existing values of the form parameters.
                   13125: 
                   13126: Inputs: 
                   13127: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13128: 
                   13129: a hash ref describing the data to be stored.  For example:
                   13130:    
                   13131: %Save_Parameters = ('Status' => 'scalar',
                   13132:     'chartoutputmode' => 'scalar',
                   13133:     'chartoutputdata' => 'scalar',
                   13134:     'Section' => 'array',
1.373     raeburn  13135:     'Group' => 'array',
1.153     matthew  13136:     'StudentData' => 'array',
                   13137:     'Maps' => 'array');
                   13138: 
                   13139: Returns: both routines return nothing
                   13140: 
1.631     raeburn  13141: =back
                   13142: 
1.153     matthew  13143: =cut
                   13144: 
                   13145: #######################################################
                   13146: #######################################################
                   13147: sub store_course_settings {
1.496     albertel 13148:     return &store_settings($env{'request.course.id'},@_);
                   13149: }
                   13150: 
                   13151: sub store_settings {
1.153     matthew  13152:     # save to the environment
                   13153:     # appenv the same items, just to be safe
1.300     albertel 13154:     my $udom  = $env{'user.domain'};
                   13155:     my $uname = $env{'user.name'};
1.496     albertel 13156:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13157:     my %SaveHash;
                   13158:     my %AppHash;
                   13159:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13160:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13161:         my $envname = 'environment.'.$basename;
1.258     albertel 13162:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13163:             # Save this value away
                   13164:             if ($type eq 'scalar' &&
1.258     albertel 13165:                 (! exists($env{$envname}) || 
                   13166:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13167:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13168:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13169:             } elsif ($type eq 'array') {
                   13170:                 my $stored_form;
1.258     albertel 13171:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13172:                     $stored_form = join(',',
                   13173:                                         map {
1.369     www      13174:                                             &escape($_);
1.258     albertel 13175:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13176:                 } else {
                   13177:                     $stored_form = 
1.369     www      13178:                         &escape($env{'form.'.$setting});
1.153     matthew  13179:                 }
                   13180:                 # Determine if the array contents are the same.
1.258     albertel 13181:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13182:                     $SaveHash{$basename} = $stored_form;
                   13183:                     $AppHash{$envname}   = $stored_form;
                   13184:                 }
                   13185:             }
                   13186:         }
                   13187:     }
                   13188:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13189:                                           $udom,$uname);
1.153     matthew  13190:     if ($put_result !~ /^(ok|delayed)/) {
                   13191:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13192:                                  'got error:'.$put_result);
                   13193:     }
                   13194:     # Make sure these settings stick around in this session, too
1.646     raeburn  13195:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13196:     return;
                   13197: }
                   13198: 
                   13199: sub restore_course_settings {
1.499     albertel 13200:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13201: }
                   13202: 
                   13203: sub restore_settings {
                   13204:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13205:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13206:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13207:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13208:             '.'.$setting;
1.258     albertel 13209:         if (exists($env{$envname})) {
1.153     matthew  13210:             if ($type eq 'scalar') {
1.258     albertel 13211:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13212:             } elsif ($type eq 'array') {
1.258     albertel 13213:                 $env{'form.'.$setting} = [ 
1.153     matthew  13214:                                            map { 
1.369     www      13215:                                                &unescape($_); 
1.258     albertel 13216:                                            } split(',',$env{$envname})
1.153     matthew  13217:                                            ];
                   13218:             }
                   13219:         }
                   13220:     }
1.127     matthew  13221: }
                   13222: 
1.618     raeburn  13223: #######################################################
                   13224: #######################################################
                   13225: 
                   13226: =pod
                   13227: 
                   13228: =head1 Domain E-mail Routines  
                   13229: 
                   13230: =over 4
                   13231: 
1.648     raeburn  13232: =item * &build_recipient_list()
1.618     raeburn  13233: 
1.1144    raeburn  13234: Build recipient lists for following types of e-mail:
1.766     raeburn  13235: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  13236: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13237: module change checking, student/employee ID conflict checks, as
                   13238: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13239: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13240: 
                   13241: Inputs:
1.619     raeburn  13242: defmail (scalar - email address of default recipient), 
1.1144    raeburn  13243: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13244: requestsmail, updatesmail, or idconflictsmail).
                   13245: 
1.619     raeburn  13246: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  13247: 
1.619     raeburn  13248: origmail (scalar - email address of recipient from loncapa.conf, 
                   13249: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  13250: 
1.655     raeburn  13251: Returns: comma separated list of addresses to which to send e-mail.
                   13252: 
                   13253: =back
1.618     raeburn  13254: 
                   13255: =cut
                   13256: 
                   13257: ############################################################
                   13258: ############################################################
                   13259: sub build_recipient_list {
1.619     raeburn  13260:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13261:     my @recipients;
                   13262:     my $otheremails;
                   13263:     my %domconfig =
                   13264:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13265:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13266:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13267:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13268:                 my @contacts = ('adminemail','supportemail');
                   13269:                 foreach my $item (@contacts) {
                   13270:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13271:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13272:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13273:                             push(@recipients,$addr);
                   13274:                         }
1.619     raeburn  13275:                     }
1.766     raeburn  13276:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13277:                 }
                   13278:             }
1.766     raeburn  13279:         } elsif ($origmail ne '') {
                   13280:             push(@recipients,$origmail);
1.618     raeburn  13281:         }
1.619     raeburn  13282:     } elsif ($origmail ne '') {
                   13283:         push(@recipients,$origmail);
1.618     raeburn  13284:     }
1.688     raeburn  13285:     if (defined($defmail)) {
                   13286:         if ($defmail ne '') {
                   13287:             push(@recipients,$defmail);
                   13288:         }
1.618     raeburn  13289:     }
                   13290:     if ($otheremails) {
1.619     raeburn  13291:         my @others;
                   13292:         if ($otheremails =~ /,/) {
                   13293:             @others = split(/,/,$otheremails);
1.618     raeburn  13294:         } else {
1.619     raeburn  13295:             push(@others,$otheremails);
                   13296:         }
                   13297:         foreach my $addr (@others) {
                   13298:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13299:                 push(@recipients,$addr);
                   13300:             }
1.618     raeburn  13301:         }
                   13302:     }
1.619     raeburn  13303:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13304:     return $recipientlist;
                   13305: }
                   13306: 
1.127     matthew  13307: ############################################################
                   13308: ############################################################
1.154     albertel 13309: 
1.655     raeburn  13310: =pod
                   13311: 
                   13312: =head1 Course Catalog Routines
                   13313: 
                   13314: =over 4
                   13315: 
                   13316: =item * &gather_categories()
                   13317: 
                   13318: Converts category definitions - keys of categories hash stored in  
                   13319: coursecategories in configuration.db on the primary library server in a 
                   13320: domain - to an array.  Also generates javascript and idx hash used to 
                   13321: generate Domain Coordinator interface for editing Course Categories.
                   13322: 
                   13323: Inputs:
1.663     raeburn  13324: 
1.655     raeburn  13325: categories (reference to hash of category definitions).
1.663     raeburn  13326: 
1.655     raeburn  13327: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13328:       categories and subcategories).
1.663     raeburn  13329: 
1.655     raeburn  13330: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13331:       editing Course Categories).
1.663     raeburn  13332: 
1.655     raeburn  13333: jsarray (reference to array of categories used to create Javascript arrays for
                   13334:          Domain Coordinator interface for editing Course Categories).
                   13335: 
                   13336: Returns: nothing
                   13337: 
                   13338: Side effects: populates cats, idx and jsarray. 
                   13339: 
                   13340: =cut
                   13341: 
                   13342: sub gather_categories {
                   13343:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13344:     my %counters;
                   13345:     my $num = 0;
                   13346:     foreach my $item (keys(%{$categories})) {
                   13347:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13348:         if ($container eq '' && $depth == 0) {
                   13349:             $cats->[$depth][$categories->{$item}] = $cat;
                   13350:         } else {
                   13351:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13352:         }
                   13353:         my ($escitem,$tail) = split(/:/,$item,2);
                   13354:         if ($counters{$tail} eq '') {
                   13355:             $counters{$tail} = $num;
                   13356:             $num ++;
                   13357:         }
                   13358:         if (ref($idx) eq 'HASH') {
                   13359:             $idx->{$item} = $counters{$tail};
                   13360:         }
                   13361:         if (ref($jsarray) eq 'ARRAY') {
                   13362:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13363:         }
                   13364:     }
                   13365:     return;
                   13366: }
                   13367: 
                   13368: =pod
                   13369: 
                   13370: =item * &extract_categories()
                   13371: 
                   13372: Used to generate breadcrumb trails for course categories.
                   13373: 
                   13374: Inputs:
1.663     raeburn  13375: 
1.655     raeburn  13376: categories (reference to hash of category definitions).
1.663     raeburn  13377: 
1.655     raeburn  13378: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13379:       categories and subcategories).
1.663     raeburn  13380: 
1.655     raeburn  13381: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13382: 
1.655     raeburn  13383: allitems (reference to hash - key is category key 
                   13384:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13385: 
1.655     raeburn  13386: idx (reference to hash of counters used in Domain Coordinator interface for
                   13387:       editing Course Categories).
1.663     raeburn  13388: 
1.655     raeburn  13389: jsarray (reference to array of categories used to create Javascript arrays for
                   13390:          Domain Coordinator interface for editing Course Categories).
                   13391: 
1.665     raeburn  13392: subcats (reference to hash of arrays containing all subcategories within each 
                   13393:          category, -recursive)
                   13394: 
1.655     raeburn  13395: Returns: nothing
                   13396: 
                   13397: Side effects: populates trails and allitems hash references.
                   13398: 
                   13399: =cut
                   13400: 
                   13401: sub extract_categories {
1.665     raeburn  13402:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13403:     if (ref($categories) eq 'HASH') {
                   13404:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13405:         if (ref($cats->[0]) eq 'ARRAY') {
                   13406:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13407:                 my $name = $cats->[0][$i];
                   13408:                 my $item = &escape($name).'::0';
                   13409:                 my $trailstr;
                   13410:                 if ($name eq 'instcode') {
                   13411:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13412:                 } elsif ($name eq 'communities') {
                   13413:                     $trailstr = &mt('Communities');
1.655     raeburn  13414:                 } else {
                   13415:                     $trailstr = $name;
                   13416:                 }
                   13417:                 if ($allitems->{$item} eq '') {
                   13418:                     push(@{$trails},$trailstr);
                   13419:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13420:                 }
                   13421:                 my @parents = ($name);
                   13422:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13423:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13424:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13425:                         if (ref($subcats) eq 'HASH') {
                   13426:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13427:                         }
                   13428:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13429:                     }
                   13430:                 } else {
                   13431:                     if (ref($subcats) eq 'HASH') {
                   13432:                         $subcats->{$item} = [];
1.655     raeburn  13433:                     }
                   13434:                 }
                   13435:             }
                   13436:         }
                   13437:     }
                   13438:     return;
                   13439: }
                   13440: 
                   13441: =pod
                   13442: 
1.1162    raeburn  13443: =item * &recurse_categories()
1.655     raeburn  13444: 
                   13445: Recursively used to generate breadcrumb trails for course categories.
                   13446: 
                   13447: Inputs:
1.663     raeburn  13448: 
1.655     raeburn  13449: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13450:       categories and subcategories).
1.663     raeburn  13451: 
1.655     raeburn  13452: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13453: 
                   13454: category (current course category, for which breadcrumb trail is being generated).
                   13455: 
                   13456: trails (reference to array of breadcrumb trails for each category).
                   13457: 
1.655     raeburn  13458: allitems (reference to hash - key is category key
                   13459:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13460: 
1.655     raeburn  13461: parents (array containing containers directories for current category, 
                   13462:          back to top level). 
                   13463: 
                   13464: Returns: nothing
                   13465: 
                   13466: Side effects: populates trails and allitems hash references
                   13467: 
                   13468: =cut
                   13469: 
                   13470: sub recurse_categories {
1.665     raeburn  13471:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13472:     my $shallower = $depth - 1;
                   13473:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13474:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13475:             my $name = $cats->[$depth]{$category}[$k];
                   13476:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13477:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13478:             if ($allitems->{$item} eq '') {
                   13479:                 push(@{$trails},$trailstr);
                   13480:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13481:             }
                   13482:             my $deeper = $depth+1;
                   13483:             push(@{$parents},$category);
1.665     raeburn  13484:             if (ref($subcats) eq 'HASH') {
                   13485:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13486:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13487:                     my $higher;
                   13488:                     if ($j > 0) {
                   13489:                         $higher = &escape($parents->[$j]).':'.
                   13490:                                   &escape($parents->[$j-1]).':'.$j;
                   13491:                     } else {
                   13492:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13493:                     }
                   13494:                     push(@{$subcats->{$higher}},$subcat);
                   13495:                 }
                   13496:             }
                   13497:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13498:                                 $subcats);
1.655     raeburn  13499:             pop(@{$parents});
                   13500:         }
                   13501:     } else {
                   13502:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13503:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13504:         if ($allitems->{$item} eq '') {
                   13505:             push(@{$trails},$trailstr);
                   13506:             $allitems->{$item} = scalar(@{$trails})-1;
                   13507:         }
                   13508:     }
                   13509:     return;
                   13510: }
                   13511: 
1.663     raeburn  13512: =pod
                   13513: 
1.1162    raeburn  13514: =item * &assign_categories_table()
1.663     raeburn  13515: 
                   13516: Create a datatable for display of hierarchical categories in a domain,
                   13517: with checkboxes to allow a course to be categorized. 
                   13518: 
                   13519: Inputs:
                   13520: 
                   13521: cathash - reference to hash of categories defined for the domain (from
                   13522:           configuration.db)
                   13523: 
                   13524: currcat - scalar with an & separated list of categories assigned to a course. 
                   13525: 
1.919     raeburn  13526: type    - scalar contains course type (Course or Community).
                   13527: 
1.663     raeburn  13528: Returns: $output (markup to be displayed) 
                   13529: 
                   13530: =cut
                   13531: 
                   13532: sub assign_categories_table {
1.919     raeburn  13533:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13534:     my $output;
                   13535:     if (ref($cathash) eq 'HASH') {
                   13536:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13537:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13538:         $maxdepth = scalar(@cats);
                   13539:         if (@cats > 0) {
                   13540:             my $itemcount = 0;
                   13541:             if (ref($cats[0]) eq 'ARRAY') {
                   13542:                 my @currcategories;
                   13543:                 if ($currcat ne '') {
                   13544:                     @currcategories = split('&',$currcat);
                   13545:                 }
1.919     raeburn  13546:                 my $table;
1.663     raeburn  13547:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13548:                     my $parent = $cats[0][$i];
1.919     raeburn  13549:                     next if ($parent eq 'instcode');
                   13550:                     if ($type eq 'Community') {
                   13551:                         next unless ($parent eq 'communities');
                   13552:                     } else {
                   13553:                         next if ($parent eq 'communities');
                   13554:                     }
1.663     raeburn  13555:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13556:                     my $item = &escape($parent).'::0';
                   13557:                     my $checked = '';
                   13558:                     if (@currcategories > 0) {
                   13559:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13560:                             $checked = ' checked="checked"';
1.663     raeburn  13561:                         }
                   13562:                     }
1.919     raeburn  13563:                     my $parent_title = $parent;
                   13564:                     if ($parent eq 'communities') {
                   13565:                         $parent_title = &mt('Communities');
                   13566:                     }
                   13567:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13568:                               '<input type="checkbox" name="usecategory" value="'.
                   13569:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13570:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13571:                     my $depth = 1;
                   13572:                     push(@path,$parent);
1.919     raeburn  13573:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13574:                     pop(@path);
1.919     raeburn  13575:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13576:                     $itemcount ++;
                   13577:                 }
1.919     raeburn  13578:                 if ($itemcount) {
                   13579:                     $output = &Apache::loncommon::start_data_table().
                   13580:                               $table.
                   13581:                               &Apache::loncommon::end_data_table();
                   13582:                 }
1.663     raeburn  13583:             }
                   13584:         }
                   13585:     }
                   13586:     return $output;
                   13587: }
                   13588: 
                   13589: =pod
                   13590: 
1.1162    raeburn  13591: =item * &assign_category_rows()
1.663     raeburn  13592: 
                   13593: Create a datatable row for display of nested categories in a domain,
                   13594: with checkboxes to allow a course to be categorized,called recursively.
                   13595: 
                   13596: Inputs:
                   13597: 
                   13598: itemcount - track row number for alternating colors
                   13599: 
                   13600: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13601:       categories and subcategories.
                   13602: 
                   13603: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13604: 
                   13605: parent - parent of current category item
                   13606: 
                   13607: path - Array containing all categories back up through the hierarchy from the
                   13608:        current category to the top level.
                   13609: 
                   13610: currcategories - reference to array of current categories assigned to the course
                   13611: 
                   13612: Returns: $output (markup to be displayed).
                   13613: 
                   13614: =cut
                   13615: 
                   13616: sub assign_category_rows {
                   13617:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13618:     my ($text,$name,$item,$chgstr);
                   13619:     if (ref($cats) eq 'ARRAY') {
                   13620:         my $maxdepth = scalar(@{$cats});
                   13621:         if (ref($cats->[$depth]) eq 'HASH') {
                   13622:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13623:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13624:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  13625:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  13626:                 for (my $j=0; $j<$numchildren; $j++) {
                   13627:                     $name = $cats->[$depth]{$parent}[$j];
                   13628:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13629:                     my $deeper = $depth+1;
                   13630:                     my $checked = '';
                   13631:                     if (ref($currcategories) eq 'ARRAY') {
                   13632:                         if (@{$currcategories} > 0) {
                   13633:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13634:                                 $checked = ' checked="checked"';
1.663     raeburn  13635:                             }
                   13636:                         }
                   13637:                     }
1.664     raeburn  13638:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13639:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13640:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13641:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13642:                              '</td><td>';
1.663     raeburn  13643:                     if (ref($path) eq 'ARRAY') {
                   13644:                         push(@{$path},$name);
                   13645:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13646:                         pop(@{$path});
                   13647:                     }
                   13648:                     $text .= '</td></tr>';
                   13649:                 }
                   13650:                 $text .= '</table></td>';
                   13651:             }
                   13652:         }
                   13653:     }
                   13654:     return $text;
                   13655: }
                   13656: 
1.655     raeburn  13657: ############################################################
                   13658: ############################################################
                   13659: 
                   13660: 
1.443     albertel 13661: sub commit_customrole {
1.664     raeburn  13662:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13663:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13664:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13665:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13666:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13667:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13668:                  '</b><br />';
                   13669:     return $output;
                   13670: }
                   13671: 
                   13672: sub commit_standardrole {
1.1116    raeburn  13673:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13674:     my ($output,$logmsg,$linefeed);
                   13675:     if ($context eq 'auto') {
                   13676:         $linefeed = "\n";
                   13677:     } else {
                   13678:         $linefeed = "<br />\n";
                   13679:     }  
1.443     albertel 13680:     if ($three eq 'st') {
1.541     raeburn  13681:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  13682:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13683:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13684:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13685:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13686:         } else {
1.541     raeburn  13687:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13688:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13689:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13690:             if ($context eq 'auto') {
                   13691:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13692:             } else {
                   13693:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13694:                &mt('Add to classlist').': <b>ok</b>';
                   13695:             }
                   13696:             $output .= $linefeed;
1.443     albertel 13697:         }
                   13698:     } else {
                   13699:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13700:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13701:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13702:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13703:         if ($context eq 'auto') {
                   13704:             $output .= $result.$linefeed;
                   13705:         } else {
                   13706:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13707:         }
1.443     albertel 13708:     }
                   13709:     return $output;
                   13710: }
                   13711: 
                   13712: sub commit_studentrole {
1.1116    raeburn  13713:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13714:         $credits) = @_;
1.626     raeburn  13715:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13716:     if ($context eq 'auto') {
                   13717:         $linefeed = "\n";
                   13718:     } else {
                   13719:         $linefeed = '<br />'."\n";
                   13720:     }
1.443     albertel 13721:     if (defined($one) && defined($two)) {
                   13722:         my $cid=$one.'_'.$two;
                   13723:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13724:         my $secchange = 0;
                   13725:         my $expire_role_result;
                   13726:         my $modify_section_result;
1.628     raeburn  13727:         if ($oldsec ne '-1') { 
                   13728:             if ($oldsec ne $sec) {
1.443     albertel 13729:                 $secchange = 1;
1.628     raeburn  13730:                 my $now = time;
1.443     albertel 13731:                 my $uurl='/'.$cid;
                   13732:                 $uurl=~s/\_/\//g;
                   13733:                 if ($oldsec) {
                   13734:                     $uurl.='/'.$oldsec;
                   13735:                 }
1.626     raeburn  13736:                 $oldsecurl = $uurl;
1.628     raeburn  13737:                 $expire_role_result = 
1.652     raeburn  13738:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13739:                 if ($env{'request.course.sec'} ne '') { 
                   13740:                     if ($expire_role_result eq 'refused') {
                   13741:                         my @roles = ('st');
                   13742:                         my @statuses = ('previous');
                   13743:                         my @roledoms = ($one);
                   13744:                         my $withsec = 1;
                   13745:                         my %roleshash = 
                   13746:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13747:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13748:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13749:                             my ($oldstart,$oldend) = 
                   13750:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13751:                             if ($oldend > 0 && $oldend <= $now) {
                   13752:                                 $expire_role_result = 'ok';
                   13753:                             }
                   13754:                         }
                   13755:                     }
                   13756:                 }
1.443     albertel 13757:                 $result = $expire_role_result;
                   13758:             }
                   13759:         }
                   13760:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  13761:             $modify_section_result = 
                   13762:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13763:                                                            undef,undef,undef,$sec,
                   13764:                                                            $end,$start,'','',$cid,
                   13765:                                                            '',$context,$credits);
1.443     albertel 13766:             if ($modify_section_result =~ /^ok/) {
                   13767:                 if ($secchange == 1) {
1.628     raeburn  13768:                     if ($sec eq '') {
                   13769:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13770:                     } else {
                   13771:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13772:                     }
1.443     albertel 13773:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13774:                     if ($sec eq '') {
                   13775:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13776:                     } else {
                   13777:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13778:                     }
1.443     albertel 13779:                 } else {
1.628     raeburn  13780:                     if ($sec eq '') {
                   13781:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13782:                     } else {
                   13783:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13784:                     }
1.443     albertel 13785:                 }
                   13786:             } else {
1.1115    raeburn  13787:                 if ($secchange) { 
1.628     raeburn  13788:                     $$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;
                   13789:                 } else {
                   13790:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13791:                 }
1.443     albertel 13792:             }
                   13793:             $result = $modify_section_result;
                   13794:         } elsif ($secchange == 1) {
1.628     raeburn  13795:             if ($oldsec eq '') {
1.1103    raeburn  13796:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
1.628     raeburn  13797:             } else {
                   13798:                 $$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;
                   13799:             }
1.626     raeburn  13800:             if ($expire_role_result eq 'refused') {
                   13801:                 my $newsecurl = '/'.$cid;
                   13802:                 $newsecurl =~ s/\_/\//g;
                   13803:                 if ($sec ne '') {
                   13804:                     $newsecurl.='/'.$sec;
                   13805:                 }
                   13806:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13807:                     if ($sec eq '') {
                   13808:                         $$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;
                   13809:                     } else {
                   13810:                         $$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;
                   13811:                     }
                   13812:                 }
                   13813:             }
1.443     albertel 13814:         }
                   13815:     } else {
1.626     raeburn  13816:         $$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;
1.443     albertel 13817:         $result = "error: incomplete course id\n";
                   13818:     }
                   13819:     return $result;
                   13820: }
                   13821: 
1.1108    raeburn  13822: sub show_role_extent {
                   13823:     my ($scope,$context,$role) = @_;
                   13824:     $scope =~ s{^/}{};
                   13825:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   13826:     push(@courseroles,'co');
                   13827:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   13828:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   13829:         $scope =~ s{/}{_};
                   13830:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   13831:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   13832:         my ($audom,$auname) = split(/\//,$scope);
                   13833:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   13834:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   13835:     } else {
                   13836:         $scope =~ s{/$}{};
                   13837:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   13838:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   13839:     }
                   13840: }
                   13841: 
1.443     albertel 13842: ############################################################
                   13843: ############################################################
                   13844: 
1.566     albertel 13845: sub check_clone {
1.578     raeburn  13846:     my ($args,$linefeed) = @_;
1.566     albertel 13847:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13848:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13849:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13850:     my $clonemsg;
                   13851:     my $can_clone = 0;
1.944     raeburn  13852:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13853:     if ($lctype ne 'community') {
                   13854:         $lctype = 'course';
                   13855:     }
1.566     albertel 13856:     if ($clonehome eq 'no_host') {
1.944     raeburn  13857:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13858:             $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'});
                   13859:         } else {
                   13860:             $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'});
                   13861:         }     
1.566     albertel 13862:     } else {
                   13863: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13864:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13865:             if ($clonedesc{'type'} ne 'Community') {
                   13866:                  $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'});
                   13867:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13868:             }
                   13869:         }
1.882     raeburn  13870: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13871:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13872: 	    $can_clone = 1;
                   13873: 	} else {
                   13874: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13875: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13876: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13877:             if (grep(/^\*$/,@cloners)) {
                   13878:                 $can_clone = 1;
                   13879:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13880:                 $can_clone = 1;
                   13881:             } else {
1.908     raeburn  13882:                 my $ccrole = 'cc';
1.944     raeburn  13883:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13884:                     $ccrole = 'co';
                   13885:                 }
1.578     raeburn  13886: 	        my %roleshash =
                   13887: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13888: 					 $args->{'ccdomain'},
1.908     raeburn  13889:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13890: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13891: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13892:                     $can_clone = 1;
                   13893:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13894:                     $can_clone = 1;
                   13895:                 } else {
1.944     raeburn  13896:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13897:                         $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'});
                   13898:                     } else {
                   13899:                         $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'});
                   13900:                     }
1.578     raeburn  13901: 	        }
1.566     albertel 13902: 	    }
1.578     raeburn  13903:         }
1.566     albertel 13904:     }
                   13905:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13906: }
                   13907: 
1.444     albertel 13908: sub construct_course {
1.1166    raeburn  13909:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 13910:     my $outcome;
1.541     raeburn  13911:     my $linefeed =  '<br />'."\n";
                   13912:     if ($context eq 'auto') {
                   13913:         $linefeed = "\n";
                   13914:     }
1.566     albertel 13915: 
                   13916: #
                   13917: # Are we cloning?
                   13918: #
                   13919:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13920:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13921: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13922: 	if ($context ne 'auto') {
1.578     raeburn  13923:             if ($clonemsg ne '') {
                   13924: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13925:             }
1.566     albertel 13926: 	}
                   13927: 	$outcome .= $clonemsg.$linefeed;
                   13928: 
                   13929:         if (!$can_clone) {
                   13930: 	    return (0,$outcome);
                   13931: 	}
                   13932:     }
                   13933: 
1.444     albertel 13934: #
                   13935: # Open course
                   13936: #
                   13937:     my $crstype = lc($args->{'crstype'});
                   13938:     my %cenv=();
                   13939:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13940:                                              $args->{'cdescr'},
                   13941:                                              $args->{'curl'},
                   13942:                                              $args->{'course_home'},
                   13943:                                              $args->{'nonstandard'},
                   13944:                                              $args->{'crscode'},
                   13945:                                              $args->{'ccuname'}.':'.
                   13946:                                              $args->{'ccdomain'},
1.882     raeburn  13947:                                              $args->{'crstype'},
1.885     raeburn  13948:                                              $cnum,$context,$category);
1.444     albertel 13949: 
                   13950:     # Note: The testing routines depend on this being output; see 
                   13951:     # Utils::Course. This needs to at least be output as a comment
                   13952:     # if anyone ever decides to not show this, and Utils::Course::new
                   13953:     # will need to be suitably modified.
1.541     raeburn  13954:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13955:     if ($$courseid =~ /^error:/) {
                   13956:         return (0,$outcome);
                   13957:     }
                   13958: 
1.444     albertel 13959: #
                   13960: # Check if created correctly
                   13961: #
1.479     albertel 13962:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13963:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13964:     if ($crsuhome eq 'no_host') {
                   13965:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13966:         return (0,$outcome);
                   13967:     }
1.541     raeburn  13968:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13969: 
1.444     albertel 13970: #
1.566     albertel 13971: # Do the cloning
                   13972: #   
                   13973:     if ($can_clone && $cloneid) {
                   13974: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13975: 	if ($context ne 'auto') {
                   13976: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13977: 	}
                   13978: 	$outcome .= $clonemsg.$linefeed;
                   13979: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13980: # Copy all files
1.637     www      13981: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13982: # Restore URL
1.566     albertel 13983: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13984: # Restore title
1.566     albertel 13985: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13986: # Restore creation date, creator and creation context.
                   13987:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13988:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13989:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13990: # Mark as cloned
1.566     albertel 13991: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13992: # Need to clone grading mode
                   13993:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13994:         $cenv{'grading'}=$newenv{'grading'};
                   13995: # Do not clone these environment entries
                   13996:         &Apache::lonnet::del('environment',
                   13997:                   ['default_enrollment_start_date',
                   13998:                    'default_enrollment_end_date',
                   13999:                    'question.email',
                   14000:                    'policy.email',
                   14001:                    'comment.email',
                   14002:                    'pch.users.denied',
1.725     raeburn  14003:                    'plc.users.denied',
                   14004:                    'hidefromcat',
1.1121    raeburn  14005:                    'checkforpriv',
1.1166    raeburn  14006:                    'categories',
                   14007:                    'internal.uniquecode'],
1.638     www      14008:                    $$crsudom,$$crsunum);
1.1170    raeburn  14009:         if ($args->{'textbook'}) {
                   14010:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14011:         }
1.444     albertel 14012:     }
1.566     albertel 14013: 
1.444     albertel 14014: #
                   14015: # Set environment (will override cloned, if existing)
                   14016: #
                   14017:     my @sections = ();
                   14018:     my @xlists = ();
                   14019:     if ($args->{'crstype'}) {
                   14020:         $cenv{'type'}=$args->{'crstype'};
                   14021:     }
                   14022:     if ($args->{'crsid'}) {
                   14023:         $cenv{'courseid'}=$args->{'crsid'};
                   14024:     }
                   14025:     if ($args->{'crscode'}) {
                   14026:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14027:     }
                   14028:     if ($args->{'crsquota'} ne '') {
                   14029:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14030:     } else {
                   14031:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14032:     }
                   14033:     if ($args->{'ccuname'}) {
                   14034:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14035:                                         ':'.$args->{'ccdomain'};
                   14036:     } else {
                   14037:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14038:     }
1.1116    raeburn  14039:     if ($args->{'defaultcredits'}) {
                   14040:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14041:     }
1.444     albertel 14042:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14043:     if ($args->{'crssections'}) {
                   14044:         $cenv{'internal.sectionnums'} = '';
                   14045:         if ($args->{'crssections'} =~ m/,/) {
                   14046:             @sections = split/,/,$args->{'crssections'};
                   14047:         } else {
                   14048:             $sections[0] = $args->{'crssections'};
                   14049:         }
                   14050:         if (@sections > 0) {
                   14051:             foreach my $item (@sections) {
                   14052:                 my ($sec,$gp) = split/:/,$item;
                   14053:                 my $class = $args->{'crscode'}.$sec;
                   14054:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14055:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14056:                 unless ($addcheck eq 'ok') {
                   14057:                     push @badclasses, $class;
                   14058:                 }
                   14059:             }
                   14060:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14061:         }
                   14062:     }
                   14063: # do not hide course coordinator from staff listing, 
                   14064: # even if privileged
                   14065:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14066: # add course coordinator's domain to domains to check for privileged users
                   14067: # if different to course domain
                   14068:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14069:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14070:     }
1.444     albertel 14071: # add crosslistings
                   14072:     if ($args->{'crsxlist'}) {
                   14073:         $cenv{'internal.crosslistings'}='';
                   14074:         if ($args->{'crsxlist'} =~ m/,/) {
                   14075:             @xlists = split/,/,$args->{'crsxlist'};
                   14076:         } else {
                   14077:             $xlists[0] = $args->{'crsxlist'};
                   14078:         }
                   14079:         if (@xlists > 0) {
                   14080:             foreach my $item (@xlists) {
                   14081:                 my ($xl,$gp) = split/:/,$item;
                   14082:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14083:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14084:                 unless ($addcheck eq 'ok') {
                   14085:                     push @badclasses, $xl;
                   14086:                 }
                   14087:             }
                   14088:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14089:         }
                   14090:     }
                   14091:     if ($args->{'autoadds'}) {
                   14092:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14093:     }
                   14094:     if ($args->{'autodrops'}) {
                   14095:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14096:     }
                   14097: # check for notification of enrollment changes
                   14098:     my @notified = ();
                   14099:     if ($args->{'notify_owner'}) {
                   14100:         if ($args->{'ccuname'} ne '') {
                   14101:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14102:         }
                   14103:     }
                   14104:     if ($args->{'notify_dc'}) {
                   14105:         if ($uname ne '') { 
1.630     raeburn  14106:             push(@notified,$uname.':'.$udom);
1.444     albertel 14107:         }
                   14108:     }
                   14109:     if (@notified > 0) {
                   14110:         my $notifylist;
                   14111:         if (@notified > 1) {
                   14112:             $notifylist = join(',',@notified);
                   14113:         } else {
                   14114:             $notifylist = $notified[0];
                   14115:         }
                   14116:         $cenv{'internal.notifylist'} = $notifylist;
                   14117:     }
                   14118:     if (@badclasses > 0) {
                   14119:         my %lt=&Apache::lonlocal::texthash(
                   14120:                 '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',
                   14121:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14122:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14123:         );
1.541     raeburn  14124:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14125:                            ' ('.$lt{'adby'}.')';
                   14126:         if ($context eq 'auto') {
                   14127:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14128:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14129:             foreach my $item (@badclasses) {
                   14130:                 if ($context eq 'auto') {
                   14131:                     $outcome .= " - $item\n";
                   14132:                 } else {
                   14133:                     $outcome .= "<li>$item</li>\n";
                   14134:                 }
                   14135:             }
                   14136:             if ($context eq 'auto') {
                   14137:                 $outcome .= $linefeed;
                   14138:             } else {
1.566     albertel 14139:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14140:             }
                   14141:         } 
1.444     albertel 14142:     }
                   14143:     if ($args->{'no_end_date'}) {
                   14144:         $args->{'endaccess'} = 0;
                   14145:     }
                   14146:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14147:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14148:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14149:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14150:     if ($args->{'showphotos'}) {
                   14151:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14152:     }
                   14153:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14154:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14155:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14156:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14157:             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'); 
                   14158:             if ($context eq 'auto') {
                   14159:                 $outcome .= $krb_msg;
                   14160:             } else {
1.566     albertel 14161:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14162:             }
                   14163:             $outcome .= $linefeed;
1.444     albertel 14164:         }
                   14165:     }
                   14166:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14167:        if ($args->{'setpolicy'}) {
                   14168:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14169:        }
                   14170:        if ($args->{'setcontent'}) {
                   14171:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14172:        }
                   14173:     }
                   14174:     if ($args->{'reshome'}) {
                   14175: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14176: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14177:     }
                   14178: #
                   14179: # course has keyed access
                   14180: #
                   14181:     if ($args->{'setkeys'}) {
                   14182:        $cenv{'keyaccess'}='yes';
                   14183:     }
                   14184: # if specified, key authority is not course, but user
                   14185: # only active if keyaccess is yes
                   14186:     if ($args->{'keyauth'}) {
1.487     albertel 14187: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14188: 	$user = &LONCAPA::clean_username($user);
                   14189: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14190: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14191: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14192: 	}
                   14193:     }
                   14194: 
1.1166    raeburn  14195: #
1.1167    raeburn  14196: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  14197: #
                   14198:     if ($args->{'uniquecode'}) {
                   14199:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14200:         if ($code) {
                   14201:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  14202:             my %crsinfo =
                   14203:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14204:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14205:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14206:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14207:             } 
1.1166    raeburn  14208:             if (ref($coderef)) {
                   14209:                 $$coderef = $code;
                   14210:             }
                   14211:         }
                   14212:     }
                   14213: 
1.444     albertel 14214:     if ($args->{'disresdis'}) {
                   14215:         $cenv{'pch.roles.denied'}='st';
                   14216:     }
                   14217:     if ($args->{'disablechat'}) {
                   14218:         $cenv{'plc.roles.denied'}='st';
                   14219:     }
                   14220: 
                   14221:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14222:     # course
                   14223:     $cenv{'course.helper.not.run'} = 1;
                   14224:     #
                   14225:     # Use new Randomseed
                   14226:     #
                   14227:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14228:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14229:     #
                   14230:     # The encryption code and receipt prefix for this course
                   14231:     #
                   14232:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14233:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14234:     #
                   14235:     # By default, use standard grading
                   14236:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14237: 
1.541     raeburn  14238:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14239:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14240: #
                   14241: # Open all assignments
                   14242: #
                   14243:     if ($args->{'openall'}) {
                   14244:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14245:        my %storecontent = ($storeunder         => time,
                   14246:                            $storeunder.'.type' => 'date_start');
                   14247:        
                   14248:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14249:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14250:    }
                   14251: #
                   14252: # Set first page
                   14253: #
                   14254:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14255: 	    || ($cloneid)) {
1.445     albertel 14256: 	use LONCAPA::map;
1.444     albertel 14257: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14258: 
                   14259: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14260:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14261: 
1.444     albertel 14262:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14263:         my $title; my $url;
                   14264:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14265: 	    $title=&mt('Syllabus');
1.444     albertel 14266:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14267:         } else {
1.963     raeburn  14268:             $title=&mt('Table of Contents');
1.444     albertel 14269:             $url='/adm/navmaps';
                   14270:         }
1.445     albertel 14271: 
                   14272:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14273: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14274: 
                   14275: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14276:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14277:     }
1.566     albertel 14278: 
                   14279:     return (1,$outcome);
1.444     albertel 14280: }
                   14281: 
1.1166    raeburn  14282: sub make_unique_code {
                   14283:     my ($cdom,$cnum) = @_;
                   14284:     # get lock on uniquecodes db
                   14285:     my $lockhash = {
                   14286:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14287:                                                   ':'.$env{'user.domain'},
                   14288:                    };
                   14289:     my $tries = 0;
                   14290:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14291:     my ($code,$error);
                   14292:   
                   14293:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14294:         $tries ++;
                   14295:         sleep 1;
                   14296:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14297:     }
                   14298:     if ($gotlock eq 'ok') {
                   14299:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14300:         my $gotcode;
                   14301:         my $attempts = 0;
                   14302:         while ((!$gotcode) && ($attempts < 100)) {
                   14303:             $code = &generate_code();
                   14304:             if (!exists($currcodes{$code})) {
                   14305:                 $gotcode = 1;
                   14306:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14307:                     $error = 'nostore';
                   14308:                 }
                   14309:             }
                   14310:             $attempts ++;
                   14311:         }
                   14312:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14313:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14314:     } else {
                   14315:         $error = 'nolock';
                   14316:     }
                   14317:     return ($code,$error);
                   14318: }
                   14319: 
                   14320: sub generate_code {
                   14321:     my $code;
                   14322:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14323:     for (my $i=0; $i<6; $i++) {
                   14324:         my $lettnum = int (rand 2);
                   14325:         my $item = '';
                   14326:         if ($lettnum) {
                   14327:             $item = $letts[int( rand(18) )];
                   14328:         } else {
                   14329:             $item = 1+int( rand(8) );
                   14330:         }
                   14331:         $code .= $item;
                   14332:     }
                   14333:     return $code;
                   14334: }
                   14335: 
1.444     albertel 14336: ############################################################
                   14337: ############################################################
                   14338: 
1.953     droeschl 14339: #SD
                   14340: # only Community and Course, or anything else?
1.378     raeburn  14341: sub course_type {
                   14342:     my ($cid) = @_;
                   14343:     if (!defined($cid)) {
                   14344:         $cid = $env{'request.course.id'};
                   14345:     }
1.404     albertel 14346:     if (defined($env{'course.'.$cid.'.type'})) {
                   14347:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14348:     } else {
                   14349:         return 'Course';
1.377     raeburn  14350:     }
                   14351: }
1.156     albertel 14352: 
1.406     raeburn  14353: sub group_term {
                   14354:     my $crstype = &course_type();
                   14355:     my %names = (
                   14356:                   'Course' => 'group',
1.865     raeburn  14357:                   'Community' => 'group',
1.406     raeburn  14358:                 );
                   14359:     return $names{$crstype};
                   14360: }
                   14361: 
1.902     raeburn  14362: sub course_types {
1.1165    raeburn  14363:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14364:     my %typename = (
                   14365:                          official   => 'Official course',
                   14366:                          unofficial => 'Unofficial course',
                   14367:                          community  => 'Community',
1.1165    raeburn  14368:                          textbook   => 'Textbook course',
1.902     raeburn  14369:                    );
                   14370:     return (\@types,\%typename);
                   14371: }
                   14372: 
1.156     albertel 14373: sub icon {
                   14374:     my ($file)=@_;
1.505     albertel 14375:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14376:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14377:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14378:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14379: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14380: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14381: 	            $curfext.".gif") {
                   14382: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14383: 		$curfext.".gif";
                   14384: 	}
                   14385:     }
1.249     albertel 14386:     return &lonhttpdurl($iconname);
1.154     albertel 14387: } 
1.84      albertel 14388: 
1.575     albertel 14389: sub lonhttpdurl {
1.692     www      14390: #
                   14391: # Had been used for "small fry" static images on separate port 8080.
                   14392: # Modify here if lightweight http functionality desired again.
                   14393: # Currently eliminated due to increasing firewall issues.
                   14394: #
1.575     albertel 14395:     my ($url)=@_;
1.692     www      14396:     return $url;
1.215     albertel 14397: }
                   14398: 
1.213     albertel 14399: sub connection_aborted {
                   14400:     my ($r)=@_;
                   14401:     $r->print(" ");$r->rflush();
                   14402:     my $c = $r->connection;
                   14403:     return $c->aborted();
                   14404: }
                   14405: 
1.221     foxr     14406: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14407: #    strings as 'strings'.
                   14408: sub escape_single {
1.221     foxr     14409:     my ($input) = @_;
1.223     albertel 14410:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14411:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14412:     return $input;
                   14413: }
1.223     albertel 14414: 
1.222     foxr     14415: #  Same as escape_single, but escape's "'s  This 
                   14416: #  can be used for  "strings"
                   14417: sub escape_double {
                   14418:     my ($input) = @_;
                   14419:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14420:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14421:     return $input;
                   14422: }
1.223     albertel 14423:  
1.222     foxr     14424: #   Escapes the last element of a full URL.
                   14425: sub escape_url {
                   14426:     my ($url)   = @_;
1.238     raeburn  14427:     my @urlslices = split(/\//, $url,-1);
1.369     www      14428:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 14429:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     14430: }
1.462     albertel 14431: 
1.820     raeburn  14432: sub compare_arrays {
                   14433:     my ($arrayref1,$arrayref2) = @_;
                   14434:     my (@difference,%count);
                   14435:     @difference = ();
                   14436:     %count = ();
                   14437:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14438:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14439:         foreach my $element (keys(%count)) {
                   14440:             if ($count{$element} == 1) {
                   14441:                 push(@difference,$element);
                   14442:             }
                   14443:         }
                   14444:     }
                   14445:     return @difference;
                   14446: }
                   14447: 
1.817     bisitz   14448: # -------------------------------------------------------- Initialize user login
1.462     albertel 14449: sub init_user_environment {
1.463     albertel 14450:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14451:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14452: 
                   14453:     my $public=($username eq 'public' && $domain eq 'public');
                   14454: 
                   14455: # See if old ID present, if so, remove
                   14456: 
1.1062    raeburn  14457:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14458:     my $now=time;
                   14459: 
                   14460:     if ($public) {
                   14461: 	my $max_public=100;
                   14462: 	my $oldest;
                   14463: 	my $oldest_time=0;
                   14464: 	for(my $next=1;$next<=$max_public;$next++) {
                   14465: 	    if (-e $lonids."/publicuser_$next.id") {
                   14466: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14467: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14468: 		    $oldest_time=$mtime;
                   14469: 		    $oldest=$next;
                   14470: 		}
                   14471: 	    } else {
                   14472: 		$cookie="publicuser_$next";
                   14473: 		last;
                   14474: 	    }
                   14475: 	}
                   14476: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14477:     } else {
1.463     albertel 14478: 	# if this isn't a robot, kill any existing non-robot sessions
                   14479: 	if (!$args->{'robot'}) {
                   14480: 	    opendir(DIR,$lonids);
                   14481: 	    while ($filename=readdir(DIR)) {
                   14482: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14483: 		    unlink($lonids.'/'.$filename);
                   14484: 		}
1.462     albertel 14485: 	    }
1.463     albertel 14486: 	    closedir(DIR);
1.462     albertel 14487: 	}
                   14488: # Give them a new cookie
1.463     albertel 14489: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14490: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14491: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14492:     
                   14493: # Initialize roles
                   14494: 
1.1062    raeburn  14495: 	($userroles,$firstaccenv,$timerintenv) = 
                   14496:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14497:     }
                   14498: # ------------------------------------ Check browser type and MathML capability
                   14499: 
                   14500:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1141    raeburn  14501:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
1.462     albertel 14502: 
                   14503: # ------------------------------------------------------------- Get environment
                   14504: 
                   14505:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14506:     my ($tmp) = keys(%userenv);
                   14507:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14508:     } else {
                   14509: 	undef(%userenv);
                   14510:     }
                   14511:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14512: 	$form->{'interface'}=$userenv{'interface'};
                   14513:     }
                   14514:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14515: 
                   14516: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14517:     foreach my $option ('interface','localpath','localres') {
                   14518:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14519:     }
                   14520: # --------------------------------------------------------- Write first profile
                   14521: 
                   14522:     {
                   14523: 	my %initial_env = 
                   14524: 	    ("user.name"          => $username,
                   14525: 	     "user.domain"        => $domain,
                   14526: 	     "user.home"          => $authhost,
                   14527: 	     "browser.type"       => $clientbrowser,
                   14528: 	     "browser.version"    => $clientversion,
                   14529: 	     "browser.mathml"     => $clientmathml,
                   14530: 	     "browser.unicode"    => $clientunicode,
                   14531: 	     "browser.os"         => $clientos,
1.1137    raeburn  14532:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  14533:              "browser.info"       => $clientinfo,
1.462     albertel 14534: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14535: 	     "request.course.fn"  => '',
                   14536: 	     "request.course.uri" => '',
                   14537: 	     "request.course.sec" => '',
                   14538: 	     "request.role"       => 'cm',
                   14539: 	     "request.role.adv"   => $env{'user.adv'},
                   14540: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14541: 
                   14542:         if ($form->{'localpath'}) {
                   14543: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14544: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14545:         }
                   14546: 	
                   14547: 	if ($form->{'interface'}) {
                   14548: 	    $form->{'interface'}=~s/\W//gs;
                   14549: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14550: 	    $env{'browser.interface'}=$form->{'interface'};
                   14551: 	}
                   14552: 
1.1157    raeburn  14553:         if ($form->{'iptoken'}) {
                   14554:             my $lonhost = $r->dir_config('lonHostID');
                   14555:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14556:             $env{'user.noloadbalance'} = $lonhost;
                   14557:         }
                   14558: 
1.981     raeburn  14559:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14560:         my %domdef;
                   14561:         unless ($domain eq 'public') {
                   14562:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14563:         }
1.980     raeburn  14564: 
1.1081    raeburn  14565:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14566:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14567:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14568:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14569:         }
                   14570: 
1.1165    raeburn  14571:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14572:             $userenv{'canrequest.'.$crstype} =
                   14573:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14574:                                                   'reload','requestcourses',
                   14575:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14576:         }
                   14577: 
1.1092    raeburn  14578:         $userenv{'canrequest.author'} =
                   14579:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14580:                                         'reload','requestauthor',
                   14581:                                         \%userenv,\%domdef,\%is_adv);
                   14582:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14583:                                              $domain,$username);
                   14584:         my $reqstatus = $reqauthor{'author_status'};
                   14585:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   14586:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14587:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14588:                                                   $reqauthor{'author'}{'timestamp'};
                   14589:             }
                   14590:         }
                   14591: 
1.462     albertel 14592: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14593: 
1.462     albertel 14594: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14595: 		 &GDBM_WRCREAT(),0640)) {
                   14596: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14597: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14598: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14599:             if (ref($firstaccenv) eq 'HASH') {
                   14600:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14601:             }
                   14602:             if (ref($timerintenv) eq 'HASH') {
                   14603:                 &_add_to_env(\%disk_env,$timerintenv);
                   14604:             }
1.463     albertel 14605: 	    if (ref($args->{'extra_env'})) {
                   14606: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14607: 	    }
1.462     albertel 14608: 	    untie(%disk_env);
                   14609: 	} else {
1.705     tempelho 14610: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14611: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14612: 	    return 'error: '.$!;
                   14613: 	}
                   14614:     }
                   14615:     $env{'request.role'}='cm';
                   14616:     $env{'request.role.adv'}=$env{'user.adv'};
                   14617:     $env{'browser.type'}=$clientbrowser;
                   14618: 
                   14619:     return $cookie;
                   14620: 
                   14621: }
                   14622: 
                   14623: sub _add_to_env {
                   14624:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14625:     if (ref($env_data) eq 'HASH') {
                   14626:         while (my ($key,$value) = each(%$env_data)) {
                   14627: 	    $idf->{$prefix.$key} = $value;
                   14628: 	    $env{$prefix.$key}   = $value;
                   14629:         }
1.462     albertel 14630:     }
                   14631: }
                   14632: 
1.685     tempelho 14633: # --- Get the symbolic name of a problem and the url
                   14634: sub get_symb {
                   14635:     my ($request,$silent) = @_;
1.726     raeburn  14636:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14637:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14638:     if ($symb eq '') {
                   14639:         if (!$silent) {
1.1071    raeburn  14640:             if (ref($request)) { 
                   14641:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14642:             }
1.685     tempelho 14643:             return ();
                   14644:         }
                   14645:     }
                   14646:     &Apache::lonenc::check_decrypt(\$symb);
                   14647:     return ($symb);
                   14648: }
                   14649: 
                   14650: # --------------------------------------------------------------Get annotation
                   14651: 
                   14652: sub get_annotation {
                   14653:     my ($symb,$enc) = @_;
                   14654: 
                   14655:     my $key = $symb;
                   14656:     if (!$enc) {
                   14657:         $key =
                   14658:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14659:     }
                   14660:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14661:     return $annotation{$key};
                   14662: }
                   14663: 
                   14664: sub clean_symb {
1.731     raeburn  14665:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14666: 
                   14667:     &Apache::lonenc::check_decrypt(\$symb);
                   14668:     my $enc = $env{'request.enc'};
1.731     raeburn  14669:     if ($delete_enc) {
1.730     raeburn  14670:         delete($env{'request.enc'});
                   14671:     }
1.685     tempelho 14672: 
                   14673:     return ($symb,$enc);
                   14674: }
1.462     albertel 14675: 
1.990     raeburn  14676: sub build_release_hashes {
                   14677:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14678:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14679:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14680:                   (ref($randomizetry) eq 'HASH'));
                   14681:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14682:         my ($item,$name,$value) = split(/:/,$key);
                   14683:         if ($item eq 'parameter') {
                   14684:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14685:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14686:                     push(@{$checkparms->{$name}},$value);
                   14687:                 }
                   14688:             } else {
                   14689:                 push(@{$checkparms->{$name}},$value);
                   14690:             }
                   14691:         } elsif ($item eq 'resourcetag') {
                   14692:             if ($name eq 'responsetype') {
                   14693:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14694:             }
                   14695:         } elsif ($item eq 'course') {
                   14696:             if ($name eq 'crstype') {
                   14697:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14698:             }
                   14699:         }
                   14700:     }
                   14701:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14702:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14703:     return;
                   14704: }
                   14705: 
1.1083    raeburn  14706: sub update_content_constraints {
                   14707:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14708:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14709:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14710:     my %checkresponsetypes;
                   14711:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14712:         my ($item,$name,$value) = split(/:/,$key);
                   14713:         if ($item eq 'resourcetag') {
                   14714:             if ($name eq 'responsetype') {
                   14715:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14716:             }
                   14717:         }
                   14718:     }
                   14719:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14720:     if (defined($navmap)) {
                   14721:         my %allresponses;
                   14722:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14723:             my %responses = $res->responseTypes();
                   14724:             foreach my $key (keys(%responses)) {
                   14725:                 next unless(exists($checkresponsetypes{$key}));
                   14726:                 $allresponses{$key} += $responses{$key};
                   14727:             }
                   14728:         }
                   14729:         foreach my $key (keys(%allresponses)) {
                   14730:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14731:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14732:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14733:             }
                   14734:         }
                   14735:         undef($navmap);
                   14736:     }
                   14737:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14738:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14739:     }
                   14740:     return;
                   14741: }
                   14742: 
1.1110    raeburn  14743: sub allmaps_incourse {
                   14744:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14745:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   14746:         $cid = $env{'request.course.id'};
                   14747:         $cdom = $env{'course.'.$cid.'.domain'};
                   14748:         $cnum = $env{'course.'.$cid.'.num'};
                   14749:         $chome = $env{'course.'.$cid.'.home'};
                   14750:     }
                   14751:     my %allmaps = ();
                   14752:     my $lastchange =
                   14753:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   14754:     if ($lastchange > $env{'request.course.tied'}) {
                   14755:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   14756:         unless ($ferr) {
                   14757:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   14758:         }
                   14759:     }
                   14760:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14761:     if (defined($navmap)) {
                   14762:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   14763:             $allmaps{$res->src()} = 1;
                   14764:         }
                   14765:     }
                   14766:     return \%allmaps;
                   14767: }
                   14768: 
1.1083    raeburn  14769: sub parse_supplemental_title {
                   14770:     my ($title) = @_;
                   14771: 
                   14772:     my ($foldertitle,$renametitle);
                   14773:     if ($title =~ /&amp;&amp;&amp;/) {
                   14774:         $title = &HTML::Entites::decode($title);
                   14775:     }
                   14776:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14777:         $renametitle=$4;
                   14778:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14779:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14780:         my $name =  &plainname($uname,$udom);
                   14781:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14782:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14783:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14784:             $name.': <br />'.$foldertitle;
                   14785:     }
                   14786:     if (wantarray) {
                   14787:         return ($title,$foldertitle,$renametitle);
                   14788:     }
                   14789:     return $title;
                   14790: }
                   14791: 
1.1143    raeburn  14792: sub recurse_supplemental {
                   14793:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   14794:     if ($suppmap) {
                   14795:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   14796:         if ($fatal) {
                   14797:             $errors ++;
                   14798:         } else {
                   14799:             if ($#LONCAPA::map::resources > 0) {
                   14800:                 foreach my $res (@LONCAPA::map::resources) {
                   14801:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   14802:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  14803:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   14804:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  14805:                         } else {
                   14806:                             $numfiles ++;
                   14807:                         }
                   14808:                     }
                   14809:                 }
                   14810:             }
                   14811:         }
                   14812:     }
                   14813:     return ($numfiles,$errors);
                   14814: }
                   14815: 
1.1101    raeburn  14816: sub symb_to_docspath {
                   14817:     my ($symb) = @_;
                   14818:     return unless ($symb);
                   14819:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14820:     if ($resurl=~/\.(sequence|page)$/) {
                   14821:         $mapurl=$resurl;
                   14822:     } elsif ($resurl eq 'adm/navmaps') {
                   14823:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14824:     }
                   14825:     my $mapresobj;
                   14826:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14827:     if (ref($navmap)) {
                   14828:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14829:     }
                   14830:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14831:     my $type=$2;
                   14832:     my $path;
                   14833:     if (ref($mapresobj)) {
                   14834:         my $pcslist = $mapresobj->map_hierarchy();
                   14835:         if ($pcslist ne '') {
                   14836:             foreach my $pc (split(/,/,$pcslist)) {
                   14837:                 next if ($pc <= 1);
                   14838:                 my $res = $navmap->getByMapPc($pc);
                   14839:                 if (ref($res)) {
                   14840:                     my $thisurl = $res->src();
                   14841:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14842:                     my $thistitle = $res->title();
                   14843:                     $path .= '&'.
                   14844:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  14845:                              &escape($thistitle).
1.1101    raeburn  14846:                              ':'.$res->randompick().
                   14847:                              ':'.$res->randomout().
                   14848:                              ':'.$res->encrypted().
                   14849:                              ':'.$res->randomorder().
                   14850:                              ':'.$res->is_page();
                   14851:                 }
                   14852:             }
                   14853:         }
                   14854:         $path =~ s/^\&//;
                   14855:         my $maptitle = $mapresobj->title();
                   14856:         if ($mapurl eq 'default') {
1.1129    raeburn  14857:             $maptitle = 'Main Content';
1.1101    raeburn  14858:         }
                   14859:         $path .= (($path ne '')? '&' : '').
                   14860:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  14861:                  &escape($maptitle).
1.1101    raeburn  14862:                  ':'.$mapresobj->randompick().
                   14863:                  ':'.$mapresobj->randomout().
                   14864:                  ':'.$mapresobj->encrypted().
                   14865:                  ':'.$mapresobj->randomorder().
                   14866:                  ':'.$mapresobj->is_page();
                   14867:     } else {
                   14868:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14869:         my $ispage = (($type eq 'page')? 1 : '');
                   14870:         if ($mapurl eq 'default') {
1.1129    raeburn  14871:             $maptitle = 'Main Content';
1.1101    raeburn  14872:         }
                   14873:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  14874:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  14875:     }
                   14876:     unless ($mapurl eq 'default') {
                   14877:         $path = 'default&'.
1.1146    raeburn  14878:                 &escape('Main Content').
1.1101    raeburn  14879:                 ':::::&'.$path;
                   14880:     }
                   14881:     return $path;
                   14882: }
                   14883: 
1.1094    raeburn  14884: sub captcha_display {
                   14885:     my ($context,$lonhost) = @_;
                   14886:     my ($output,$error);
                   14887:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14888:     if ($captcha eq 'original') {
1.1094    raeburn  14889:         $output = &create_captcha();
                   14890:         unless ($output) {
1.1172  ! raeburn  14891:             $error = 'captcha';
1.1094    raeburn  14892:         }
                   14893:     } elsif ($captcha eq 'recaptcha') {
                   14894:         $output = &create_recaptcha($pubkey);
                   14895:         unless ($output) {
1.1172  ! raeburn  14896:             $error = 'recaptcha';
1.1094    raeburn  14897:         }
                   14898:     }
                   14899:     return ($output,$error);
                   14900: }
                   14901: 
                   14902: sub captcha_response {
                   14903:     my ($context,$lonhost) = @_;
                   14904:     my ($captcha_chk,$captcha_error);
                   14905:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14906:     if ($captcha eq 'original') {
1.1094    raeburn  14907:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14908:     } elsif ($captcha eq 'recaptcha') {
                   14909:         $captcha_chk = &check_recaptcha($privkey);
                   14910:     } else {
                   14911:         $captcha_chk = 1;
                   14912:     }
                   14913:     return ($captcha_chk,$captcha_error);
                   14914: }
                   14915: 
                   14916: sub get_captcha_config {
                   14917:     my ($context,$lonhost) = @_;
1.1095    raeburn  14918:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  14919:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14920:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14921:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  14922:     if ($context eq 'usercreation') {
                   14923:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14924:         if (ref($domconfig{$context}) eq 'HASH') {
                   14925:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14926:             if (ref($hashtocheck) eq 'HASH') {
                   14927:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14928:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14929:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14930:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14931:                     }
                   14932:                     if ($privkey && $pubkey) {
                   14933:                         $captcha = 'recaptcha';
                   14934:                     } else {
                   14935:                         $captcha = 'original';
                   14936:                     }
                   14937:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14938:                     $captcha = 'original';
                   14939:                 }
1.1094    raeburn  14940:             }
1.1095    raeburn  14941:         } else {
                   14942:             $captcha = 'captcha';
                   14943:         }
                   14944:     } elsif ($context eq 'login') {
                   14945:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14946:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14947:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14948:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  14949:             if ($privkey && $pubkey) {
                   14950:                 $captcha = 'recaptcha';
1.1095    raeburn  14951:             } else {
                   14952:                 $captcha = 'original';
1.1094    raeburn  14953:             }
1.1095    raeburn  14954:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14955:             $captcha = 'original';
1.1094    raeburn  14956:         }
                   14957:     }
                   14958:     return ($captcha,$pubkey,$privkey);
                   14959: }
                   14960: 
                   14961: sub create_captcha {
                   14962:     my %captcha_params = &captcha_settings();
                   14963:     my ($output,$maxtries,$tries) = ('',10,0);
                   14964:     while ($tries < $maxtries) {
                   14965:         $tries ++;
                   14966:         my $captcha = Authen::Captcha->new (
                   14967:                                            output_folder => $captcha_params{'output_dir'},
                   14968:                                            data_folder   => $captcha_params{'db_dir'},
                   14969:                                           );
                   14970:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14971: 
                   14972:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14973:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14974:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14975:                      '<input type="text" size="5" name="code" value="" /><br />'.
1.1172  ! raeburn  14976:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  14977:             last;
                   14978:         }
                   14979:     }
                   14980:     return $output;
                   14981: }
                   14982: 
                   14983: sub captcha_settings {
                   14984:     my %captcha_params = (
                   14985:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14986:                            www_output_dir => "/captchaspool",
                   14987:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14988:                            numchars       => '5',
                   14989:                          );
                   14990:     return %captcha_params;
                   14991: }
                   14992: 
                   14993: sub check_captcha {
                   14994:     my ($captcha_chk,$captcha_error);
                   14995:     my $code = $env{'form.code'};
                   14996:     my $md5sum = $env{'form.crypt'};
                   14997:     my %captcha_params = &captcha_settings();
                   14998:     my $captcha = Authen::Captcha->new(
                   14999:                       output_folder => $captcha_params{'output_dir'},
                   15000:                       data_folder   => $captcha_params{'db_dir'},
                   15001:                   );
1.1109    raeburn  15002:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  15003:     my %captcha_hash = (
                   15004:                         0       => 'Code not checked (file error)',
                   15005:                        -1      => 'Failed: code expired',
                   15006:                        -2      => 'Failed: invalid code (not in database)',
                   15007:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   15008:     );
                   15009:     if ($captcha_chk != 1) {
                   15010:         $captcha_error = $captcha_hash{$captcha_chk}
                   15011:     }
                   15012:     return ($captcha_chk,$captcha_error);
                   15013: }
                   15014: 
                   15015: sub create_recaptcha {
                   15016:     my ($pubkey) = @_;
1.1153    raeburn  15017:     my $use_ssl;
                   15018:     if ($ENV{'SERVER_PORT'} == 443) {
                   15019:         $use_ssl = 1;
                   15020:     }
1.1094    raeburn  15021:     my $captcha = Captcha::reCAPTCHA->new;
                   15022:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  15023:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1094    raeburn  15024:            &mt('If either word is hard to read, [_1] will replace them.',
1.1133    raeburn  15025:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  15026:            '<br /><br />';
                   15027: }
                   15028: 
                   15029: sub check_recaptcha {
                   15030:     my ($privkey) = @_;
                   15031:     my $captcha_chk;
                   15032:     my $captcha = Captcha::reCAPTCHA->new;
                   15033:     my $captcha_result =
                   15034:         $captcha->check_answer(
                   15035:                                 $privkey,
                   15036:                                 $ENV{'REMOTE_ADDR'},
                   15037:                                 $env{'form.recaptcha_challenge_field'},
                   15038:                                 $env{'form.recaptcha_response_field'},
                   15039:                               );
                   15040:     if ($captcha_result->{is_valid}) {
                   15041:         $captcha_chk = 1;
                   15042:     }
                   15043:     return $captcha_chk;
                   15044: }
                   15045: 
1.1161    raeburn  15046: sub cleanup_html {
                   15047:     my ($incoming) = @_;
                   15048:     my $outgoing;
                   15049:     if ($incoming ne '') {
                   15050:         $outgoing = $incoming;
                   15051:         $outgoing =~ s/;/&#059;/g;
                   15052:         $outgoing =~ s/\#/&#035;/g;
                   15053:         $outgoing =~ s/\&/&#038;/g;
                   15054:         $outgoing =~ s/</&#060;/g;
                   15055:         $outgoing =~ s/>/&#062;/g;
                   15056:         $outgoing =~ s/\(/&#040/g;
                   15057:         $outgoing =~ s/\)/&#041;/g;
                   15058:         $outgoing =~ s/"/&#034;/g;
                   15059:         $outgoing =~ s/'/&#039;/g;
                   15060:         $outgoing =~ s/\$/&#036;/g;
                   15061:         $outgoing =~ s{/}{&#047;}g;
                   15062:         $outgoing =~ s/=/&#061;/g;
                   15063:         $outgoing =~ s/\\/&#092;/g
                   15064:     }
                   15065:     return $outgoing;
                   15066: }
                   15067: 
1.41      ng       15068: =pod
                   15069: 
                   15070: =back
                   15071: 
1.112     bowersj2 15072: =cut
1.41      ng       15073: 
1.112     bowersj2 15074: 1;
                   15075: __END__;
1.41      ng       15076: 

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