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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1122  ! bisitz      4: # $Id: loncommon.pm,v 1.1121 2013/04/11 15:30:37 raeburn 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.572     banghart 1383:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1384: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1385:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1386: 
1.201     raeburn  1387:     my $title = &mt('Get help');
1.436     albertel 1388: 
                   1389:     return <<"END";
                   1390: $banner_link
                   1391:  <a href="$link" title="$title">$text</a>
                   1392: END
                   1393: }
                   1394: 
                   1395: sub help_menu_js {
                   1396:     my ($text) = @_;
1.949     droeschl 1397:     my $stayOnPage = 1;
1.436     albertel 1398:     my $width = 620;
                   1399:     my $height = 600;
1.430     albertel 1400:     my $helptopic=&general_help();
                   1401:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1402:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1403:     my $start_page =
                   1404:         &Apache::loncommon::start_page('Help Menu', undef,
                   1405: 				       {'frameset'    => 1,
                   1406: 					'js_ready'    => 1,
                   1407: 					'add_entries' => {
                   1408: 					    'border' => '0',
1.579     raeburn  1409: 					    'rows'   => "110,*",},});
1.331     albertel 1410:     my $end_page =
                   1411:         &Apache::loncommon::end_page({'frameset' => 1,
                   1412: 				      'js_ready' => 1,});
                   1413: 
1.436     albertel 1414:     my $template .= <<"ENDTEMPLATE";
                   1415: <script type="text/javascript">
1.877     bisitz   1416: // <![CDATA[
1.253     albertel 1417: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1418: var banner_link = '';
1.243     raeburn  1419: function helpMenu(target) {
                   1420:     var caller = this;
                   1421:     if (target == 'open') {
                   1422:         var newWindow = null;
                   1423:         try {
1.262     albertel 1424:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1425:         }
                   1426:         catch(error) {
                   1427:             writeHelp(caller);
                   1428:             return;
                   1429:         }
                   1430:         if (newWindow) {
                   1431:             caller = newWindow;
                   1432:         }
1.193     raeburn  1433:     }
1.243     raeburn  1434:     writeHelp(caller);
                   1435:     return;
                   1436: }
                   1437: function writeHelp(caller) {
1.1072    raeburn  1438:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1.243     raeburn  1439:     caller.document.close()
                   1440:     caller.focus()
1.193     raeburn  1441: }
1.877     bisitz   1442: // END LON-CAPA Internal -->
1.253     albertel 1443: // ]]>
1.436     albertel 1444: </script>
1.193     raeburn  1445: ENDTEMPLATE
                   1446:     return $template;
                   1447: }
                   1448: 
1.172     www      1449: sub help_open_bug {
                   1450:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1451:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1452:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1453:     $text = "" if (not defined $text);
                   1454: 	$stayOnPage=1;
1.184     albertel 1455:     $width = 600 if (not defined $width);
                   1456:     $height = 600 if (not defined $height);
1.172     www      1457: 
                   1458:     $topic=~s/\W+/\+/g;
                   1459:     my $link='';
                   1460:     my $template='';
1.379     albertel 1461:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1462: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1463:     if (!$stayOnPage)
                   1464:     {
                   1465: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1466:     }
                   1467:     else
                   1468:     {
                   1469: 	$link = $url;
                   1470:     }
                   1471:     # Add the text
                   1472:     if ($text ne "")
                   1473:     {
                   1474: 	$template .= 
                   1475:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1476:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1477:     }
                   1478: 
                   1479:     # Add the graphic
1.179     matthew  1480:     my $title = &mt('Report a Bug');
1.215     albertel 1481:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1482:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1483:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1484: ENDTEMPLATE
                   1485:     if ($text ne '') { $template.='</td></tr></table>' };
                   1486:     return $template;
                   1487: 
                   1488: }
                   1489: 
                   1490: sub help_open_faq {
                   1491:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1492:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1493:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1494:     $text = "" if (not defined $text);
                   1495: 	$stayOnPage=1;
                   1496:     $width = 350 if (not defined $width);
                   1497:     $height = 400 if (not defined $height);
                   1498: 
                   1499:     $topic=~s/\W+/\+/g;
                   1500:     my $link='';
                   1501:     my $template='';
                   1502:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1503:     if (!$stayOnPage)
                   1504:     {
                   1505: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1506:     }
                   1507:     else
                   1508:     {
                   1509: 	$link = $url;
                   1510:     }
                   1511: 
                   1512:     # Add the text
                   1513:     if ($text ne "")
                   1514:     {
                   1515: 	$template .= 
1.173     www      1516:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1517:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1518:     }
                   1519: 
                   1520:     # Add the graphic
1.179     matthew  1521:     my $title = &mt('View the FAQ');
1.215     albertel 1522:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1523:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1524:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1525: ENDTEMPLATE
                   1526:     if ($text ne '') { $template.='</td></tr></table>' };
                   1527:     return $template;
                   1528: 
1.44      bowersj2 1529: }
1.37      matthew  1530: 
1.180     matthew  1531: ###############################################################
                   1532: ###############################################################
                   1533: 
1.45      matthew  1534: =pod
                   1535: 
1.648     raeburn  1536: =item * &change_content_javascript():
1.256     matthew  1537: 
                   1538: This and the next function allow you to create small sections of an
                   1539: otherwise static HTML page that you can update on the fly with
                   1540: Javascript, even in Netscape 4.
                   1541: 
                   1542: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1543: must be written to the HTML page once. It will prove the Javascript
                   1544: function "change(name, content)". Calling the change function with the
                   1545: name of the section 
                   1546: you want to update, matching the name passed to C<changable_area>, and
                   1547: the new content you want to put in there, will put the content into
                   1548: that area.
                   1549: 
                   1550: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1551: to contain room for the original contents. You need to "make space"
                   1552: for whatever changes you wish to make, and be B<sure> to check your
                   1553: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1554: it's adequate for updating a one-line status display, but little more.
                   1555: This script will set the space to 100% width, so you only need to
                   1556: worry about height in Netscape 4.
                   1557: 
                   1558: Modern browsers are much less limiting, and if you can commit to the
                   1559: user not using Netscape 4, this feature may be used freely with
                   1560: pretty much any HTML.
                   1561: 
                   1562: =cut
                   1563: 
                   1564: sub change_content_javascript {
                   1565:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1566:     if ($env{'browser.type'} eq 'netscape' &&
                   1567: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1568: 	return (<<NETSCAPE4);
                   1569: 	function change(name, content) {
                   1570: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1571: 	    doc.open();
                   1572: 	    doc.write(content);
                   1573: 	    doc.close();
                   1574: 	}
                   1575: NETSCAPE4
                   1576:     } else {
                   1577: 	# Otherwise, we need to use semi-standards-compliant code
                   1578: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1579: 	# is really scary, and every useful browser supports it
                   1580: 	return (<<DOMBASED);
                   1581: 	function change(name, content) {
                   1582: 	    element = document.getElementById(name);
                   1583: 	    element.innerHTML = content;
                   1584: 	}
                   1585: DOMBASED
                   1586:     }
                   1587: }
                   1588: 
                   1589: =pod
                   1590: 
1.648     raeburn  1591: =item * &changable_area($name,$origContent):
1.256     matthew  1592: 
                   1593: This provides a "changable area" that can be modified on the fly via
                   1594: the Javascript code provided in C<change_content_javascript>. $name is
                   1595: the name you will use to reference the area later; do not repeat the
                   1596: same name on a given HTML page more then once. $origContent is what
                   1597: the area will originally contain, which can be left blank.
                   1598: 
                   1599: =cut
                   1600: 
                   1601: sub changable_area {
                   1602:     my ($name, $origContent) = @_;
                   1603: 
1.258     albertel 1604:     if ($env{'browser.type'} eq 'netscape' &&
                   1605: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1606: 	# If this is netscape 4, we need to use the Layer tag
                   1607: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1608:     } else {
                   1609: 	return "<span id='$name'>$origContent</span>";
                   1610:     }
                   1611: }
                   1612: 
                   1613: =pod
                   1614: 
1.648     raeburn  1615: =item * &viewport_geometry_js 
1.590     raeburn  1616: 
                   1617: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1618: 
                   1619: =cut
                   1620: 
                   1621: 
                   1622: sub viewport_geometry_js { 
                   1623:     return <<"GEOMETRY";
                   1624: var Geometry = {};
                   1625: function init_geometry() {
                   1626:     if (Geometry.init) { return };
                   1627:     Geometry.init=1;
                   1628:     if (window.innerHeight) {
                   1629:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1630:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1631:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1632:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1633:     }
                   1634:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1635:         Geometry.getViewportHeight =
                   1636:             function() { return document.documentElement.clientHeight; };
                   1637:         Geometry.getViewportWidth =
                   1638:             function() { return document.documentElement.clientWidth; };
                   1639: 
                   1640:         Geometry.getHorizontalScroll =
                   1641:             function() { return document.documentElement.scrollLeft; };
                   1642:         Geometry.getVerticalScroll =
                   1643:             function() { return document.documentElement.scrollTop; };
                   1644:     }
                   1645:     else if (document.body.clientHeight) {
                   1646:         Geometry.getViewportHeight =
                   1647:             function() { return document.body.clientHeight; };
                   1648:         Geometry.getViewportWidth =
                   1649:             function() { return document.body.clientWidth; };
                   1650:         Geometry.getHorizontalScroll =
                   1651:             function() { return document.body.scrollLeft; };
                   1652:         Geometry.getVerticalScroll =
                   1653:             function() { return document.body.scrollTop; };
                   1654:     }
                   1655: }
                   1656: 
                   1657: GEOMETRY
                   1658: }
                   1659: 
                   1660: =pod
                   1661: 
1.648     raeburn  1662: =item * &viewport_size_js()
1.590     raeburn  1663: 
                   1664: 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. 
                   1665: 
                   1666: =cut
                   1667: 
                   1668: sub viewport_size_js {
                   1669:     my $geometry = &viewport_geometry_js();
                   1670:     return <<"DIMS";
                   1671: 
                   1672: $geometry
                   1673: 
                   1674: function getViewportDims(width,height) {
                   1675:     init_geometry();
                   1676:     width.value = Geometry.getViewportWidth();
                   1677:     height.value = Geometry.getViewportHeight();
                   1678:     return;
                   1679: }
                   1680: 
                   1681: DIMS
                   1682: }
                   1683: 
                   1684: =pod
                   1685: 
1.648     raeburn  1686: =item * &resize_textarea_js()
1.565     albertel 1687: 
                   1688: emits the needed javascript to resize a textarea to be as big as possible
                   1689: 
                   1690: creates a function resize_textrea that takes two IDs first should be
                   1691: the id of the element to resize, second should be the id of a div that
                   1692: surrounds everything that comes after the textarea, this routine needs
                   1693: to be attached to the <body> for the onload and onresize events.
                   1694: 
1.648     raeburn  1695: =back
1.565     albertel 1696: 
                   1697: =cut
                   1698: 
                   1699: sub resize_textarea_js {
1.590     raeburn  1700:     my $geometry = &viewport_geometry_js();
1.565     albertel 1701:     return <<"RESIZE";
                   1702:     <script type="text/javascript">
1.824     bisitz   1703: // <![CDATA[
1.590     raeburn  1704: $geometry
1.565     albertel 1705: 
1.588     albertel 1706: function getX(element) {
                   1707:     var x = 0;
                   1708:     while (element) {
                   1709: 	x += element.offsetLeft;
                   1710: 	element = element.offsetParent;
                   1711:     }
                   1712:     return x;
                   1713: }
                   1714: function getY(element) {
                   1715:     var y = 0;
                   1716:     while (element) {
                   1717: 	y += element.offsetTop;
                   1718: 	element = element.offsetParent;
                   1719:     }
                   1720:     return y;
                   1721: }
                   1722: 
                   1723: 
1.565     albertel 1724: function resize_textarea(textarea_id,bottom_id) {
                   1725:     init_geometry();
                   1726:     var textarea        = document.getElementById(textarea_id);
                   1727:     //alert(textarea);
                   1728: 
1.588     albertel 1729:     var textarea_top    = getY(textarea);
1.565     albertel 1730:     var textarea_height = textarea.offsetHeight;
                   1731:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1732:     var bottom_top      = getY(bottom);
1.565     albertel 1733:     var bottom_height   = bottom.offsetHeight;
                   1734:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1735:     var fudge           = 23;
1.565     albertel 1736:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1737:     if (new_height < 300) {
                   1738: 	new_height = 300;
                   1739:     }
                   1740:     textarea.style.height=new_height+'px';
                   1741: }
1.824     bisitz   1742: // ]]>
1.565     albertel 1743: </script>
                   1744: RESIZE
                   1745: 
                   1746: }
                   1747: 
                   1748: =pod
                   1749: 
1.256     matthew  1750: =head1 Excel and CSV file utility routines
                   1751: 
                   1752: =over 4
                   1753: 
                   1754: =cut
                   1755: 
                   1756: ###############################################################
                   1757: ###############################################################
                   1758: 
                   1759: =pod
                   1760: 
1.648     raeburn  1761: =item * &csv_translate($text) 
1.37      matthew  1762: 
1.185     www      1763: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1764: format.
                   1765: 
                   1766: =cut
                   1767: 
1.180     matthew  1768: ###############################################################
                   1769: ###############################################################
1.37      matthew  1770: sub csv_translate {
                   1771:     my $text = shift;
                   1772:     $text =~ s/\"/\"\"/g;
1.209     albertel 1773:     $text =~ s/\n/ /g;
1.37      matthew  1774:     return $text;
                   1775: }
1.180     matthew  1776: 
                   1777: ###############################################################
                   1778: ###############################################################
                   1779: 
                   1780: =pod
                   1781: 
1.648     raeburn  1782: =item * &define_excel_formats()
1.180     matthew  1783: 
                   1784: Define some commonly used Excel cell formats.
                   1785: 
                   1786: Currently supported formats:
                   1787: 
                   1788: =over 4
                   1789: 
                   1790: =item header
                   1791: 
                   1792: =item bold
                   1793: 
                   1794: =item h1
                   1795: 
                   1796: =item h2
                   1797: 
                   1798: =item h3
                   1799: 
1.256     matthew  1800: =item h4
                   1801: 
                   1802: =item i
                   1803: 
1.180     matthew  1804: =item date
                   1805: 
                   1806: =back
                   1807: 
                   1808: Inputs: $workbook
                   1809: 
                   1810: Returns: $format, a hash reference.
                   1811: 
1.1057    foxr     1812: 
1.180     matthew  1813: =cut
                   1814: 
                   1815: ###############################################################
                   1816: ###############################################################
                   1817: sub define_excel_formats {
                   1818:     my ($workbook) = @_;
                   1819:     my $format;
                   1820:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1821:                                                 bottom    => 1,
                   1822:                                                 align     => 'center');
                   1823:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1824:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1825:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1826:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1827:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1828:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1829:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1830:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1831:     return $format;
                   1832: }
                   1833: 
                   1834: ###############################################################
                   1835: ###############################################################
1.113     bowersj2 1836: 
                   1837: =pod
                   1838: 
1.648     raeburn  1839: =item * &create_workbook()
1.255     matthew  1840: 
                   1841: Create an Excel worksheet.  If it fails, output message on the
                   1842: request object and return undefs.
                   1843: 
                   1844: Inputs: Apache request object
                   1845: 
                   1846: Returns (undef) on failure, 
                   1847:     Excel worksheet object, scalar with filename, and formats 
                   1848:     from &Apache::loncommon::define_excel_formats on success
                   1849: 
                   1850: =cut
                   1851: 
                   1852: ###############################################################
                   1853: ###############################################################
                   1854: sub create_workbook {
                   1855:     my ($r) = @_;
                   1856:         #
                   1857:     # Create the excel spreadsheet
                   1858:     my $filename = '/prtspool/'.
1.258     albertel 1859:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1860:         time.'_'.rand(1000000000).'.xls';
                   1861:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1862:     if (! defined($workbook)) {
                   1863:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1864:         $r->print(
                   1865:             '<p class="LC_error">'
                   1866:            .&mt('Problems occurred in creating the new Excel file.')
                   1867:            .' '.&mt('This error has been logged.')
                   1868:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1869:            .'</p>'
                   1870:         );
1.255     matthew  1871:         return (undef);
                   1872:     }
                   1873:     #
1.1014    foxr     1874:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1875:     #
                   1876:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1877:     return ($workbook,$filename,$format);
                   1878: }
                   1879: 
                   1880: ###############################################################
                   1881: ###############################################################
                   1882: 
                   1883: =pod
                   1884: 
1.648     raeburn  1885: =item * &create_text_file()
1.113     bowersj2 1886: 
1.542     raeburn  1887: Create a file to write to and eventually make available to the user.
1.256     matthew  1888: If file creation fails, outputs an error message on the request object and 
                   1889: return undefs.
1.113     bowersj2 1890: 
1.256     matthew  1891: Inputs: Apache request object, and file suffix
1.113     bowersj2 1892: 
1.256     matthew  1893: Returns (undef) on failure, 
                   1894:     Filehandle and filename on success.
1.113     bowersj2 1895: 
                   1896: =cut
                   1897: 
1.256     matthew  1898: ###############################################################
                   1899: ###############################################################
                   1900: sub create_text_file {
                   1901:     my ($r,$suffix) = @_;
                   1902:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1903:     my $fh;
                   1904:     my $filename = '/prtspool/'.
1.258     albertel 1905:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1906:         time.'_'.rand(1000000000).'.'.$suffix;
                   1907:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1908:     if (! defined($fh)) {
                   1909:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1910:         $r->print(
                   1911:             '<p class="LC_error">'
                   1912:            .&mt('Problems occurred in creating the output file.')
                   1913:            .' '.&mt('This error has been logged.')
                   1914:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1915:            .'</p>'
                   1916:         );
1.113     bowersj2 1917:     }
1.256     matthew  1918:     return ($fh,$filename)
1.113     bowersj2 1919: }
                   1920: 
                   1921: 
1.256     matthew  1922: =pod 
1.113     bowersj2 1923: 
                   1924: =back
                   1925: 
                   1926: =cut
1.37      matthew  1927: 
                   1928: ###############################################################
1.33      matthew  1929: ##        Home server <option> list generating code          ##
                   1930: ###############################################################
1.35      matthew  1931: 
1.169     www      1932: # ------------------------------------------
                   1933: 
                   1934: sub domain_select {
                   1935:     my ($name,$value,$multiple)=@_;
                   1936:     my %domains=map { 
1.514     albertel 1937: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1938:     } &Apache::lonnet::all_domains();
1.169     www      1939:     if ($multiple) {
                   1940: 	$domains{''}=&mt('Any domain');
1.550     albertel 1941: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1942: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1943:     } else {
1.550     albertel 1944: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1945: 	return &select_form($name,$value,\%domains);
1.169     www      1946:     }
                   1947: }
                   1948: 
1.282     albertel 1949: #-------------------------------------------
                   1950: 
                   1951: =pod
                   1952: 
1.519     raeburn  1953: =head1 Routines for form select boxes
                   1954: 
                   1955: =over 4
                   1956: 
1.648     raeburn  1957: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1958: 
                   1959: Returns a string containing a <select> element int multiple mode
                   1960: 
                   1961: 
                   1962: Args:
                   1963:   $name - name of the <select> element
1.506     raeburn  1964:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1965:   $size - number of rows long the select element is
1.283     albertel 1966:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1967:           (shown text should already have been &mt())
1.506     raeburn  1968:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1969: 
1.282     albertel 1970: =cut
                   1971: 
                   1972: #-------------------------------------------
1.169     www      1973: sub multiple_select_form {
1.284     albertel 1974:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1975:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1976:     my $output='';
1.191     matthew  1977:     if (! defined($size)) {
                   1978:         $size = 4;
1.283     albertel 1979:         if (scalar(keys(%$hash))<4) {
                   1980:             $size = scalar(keys(%$hash));
1.191     matthew  1981:         }
                   1982:     }
1.734     bisitz   1983:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1984:     my @order;
1.506     raeburn  1985:     if (ref($order) eq 'ARRAY')  {
                   1986:         @order = @{$order};
                   1987:     } else {
                   1988:         @order = sort(keys(%$hash));
1.501     banghart 1989:     }
                   1990:     if (exists($$hash{'select_form_order'})) {
                   1991:         @order = @{$$hash{'select_form_order'}};
                   1992:     }
                   1993:         
1.284     albertel 1994:     foreach my $key (@order) {
1.356     albertel 1995:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1996:         $output.='selected="selected" ' if ($selected{$key});
                   1997:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1998:     }
                   1999:     $output.="</select>\n";
                   2000:     return $output;
                   2001: }
                   2002: 
1.88      www      2003: #-------------------------------------------
                   2004: 
                   2005: =pod
                   2006: 
1.970     raeburn  2007: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2008: 
                   2009: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2010: allow a user to select options from a ref to a hash containing:
                   2011: option_name => displayed text. An optional $onchange can include
                   2012: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2013: 
1.88      www      2014: See lonrights.pm for an example invocation and use.
                   2015: 
                   2016: =cut
                   2017: 
                   2018: #-------------------------------------------
                   2019: sub select_form {
1.970     raeburn  2020:     my ($def,$name,$hashref,$onchange) = @_;
                   2021:     return unless (ref($hashref) eq 'HASH');
                   2022:     if ($onchange) {
                   2023:         $onchange = ' onchange="'.$onchange.'"';
                   2024:     }
                   2025:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2026:     my @keys;
1.970     raeburn  2027:     if (exists($hashref->{'select_form_order'})) {
                   2028: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2029:     } else {
1.970     raeburn  2030: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2031:     }
1.356     albertel 2032:     foreach my $key (@keys) {
                   2033:         $selectform.=
                   2034: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2035:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2036:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2037:     }
                   2038:     $selectform.="</select>";
                   2039:     return $selectform;
                   2040: }
                   2041: 
1.475     www      2042: # For display filters
                   2043: 
                   2044: sub display_filter {
1.1074    raeburn  2045:     my ($context) = @_;
1.475     www      2046:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2047:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2048:     my $phraseinput = 'hidden';
                   2049:     my $includeinput = 'hidden';
                   2050:     my ($checked,$includetypestext);
                   2051:     if ($env{'form.displayfilter'} eq 'containing') {
                   2052:         $phraseinput = 'text'; 
                   2053:         if ($context eq 'parmslog') {
                   2054:             $includeinput = 'checkbox';
                   2055:             if ($env{'form.includetypes'}) {
                   2056:                 $checked = ' checked="checked"';
                   2057:             }
                   2058:             $includetypestext = &mt('Include parameter types');
                   2059:         }
                   2060:     } else {
                   2061:         $includetypestext = '&nbsp;';
                   2062:     }
                   2063:     my ($additional,$secondid,$thirdid);
                   2064:     if ($context eq 'parmslog') {
                   2065:         $additional = 
                   2066:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2067:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2068:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2069:             '</label>';
                   2070:         $secondid = 'includetypes';
                   2071:         $thirdid = 'includetypestext';
                   2072:     }
                   2073:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2074:                                                     '$secondid','$thirdid')";
                   2075:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2076: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2077: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2078: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2079:            &mt('Filter: [_1]',
1.477     www      2080: 	   &select_form($env{'form.displayfilter'},
                   2081: 			'displayfilter',
1.970     raeburn  2082: 			{'currentfolder' => 'Current folder/page',
1.477     www      2083: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2084: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2085: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2086:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2087:                          '" />'.$additional;
                   2088: }
                   2089: 
                   2090: sub display_filter_js {
                   2091:     my $includetext = &mt('Include parameter types');
                   2092:     return <<"ENDJS";
                   2093:   
                   2094: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2095:     var firstType = 'hidden';
                   2096:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2097:         firstType = 'text';
                   2098:     }
                   2099:     firstObject = document.getElementById(firstid);
                   2100:     if (typeof(firstObject) == 'object') {
                   2101:         if (firstObject.type != firstType) {
                   2102:             changeInputType(firstObject,firstType);
                   2103:         }
                   2104:     }
                   2105:     if (context == 'parmslog') {
                   2106:         var secondType = 'hidden';
                   2107:         if (firstType == 'text') {
                   2108:             secondType = 'checkbox';
                   2109:         }
                   2110:         secondObject = document.getElementById(secondid);  
                   2111:         if (typeof(secondObject) == 'object') {
                   2112:             if (secondObject.type != secondType) {
                   2113:                 changeInputType(secondObject,secondType);
                   2114:             }
                   2115:         }
                   2116:         var textItem = document.getElementById(thirdid);
                   2117:         var currtext = textItem.innerHTML;
                   2118:         var newtext;
                   2119:         if (firstType == 'text') {
                   2120:             newtext = '$includetext';
                   2121:         } else {
                   2122:             newtext = '&nbsp;';
                   2123:         }
                   2124:         if (currtext != newtext) {
                   2125:             textItem.innerHTML = newtext;
                   2126:         }
                   2127:     }
                   2128:     return;
                   2129: }
                   2130: 
                   2131: function changeInputType(oldObject,newType) {
                   2132:     var newObject = document.createElement('input');
                   2133:     newObject.type = newType;
                   2134:     if (oldObject.size) {
                   2135:         newObject.size = oldObject.size;
                   2136:     }
                   2137:     if (oldObject.value) {
                   2138:         newObject.value = oldObject.value;
                   2139:     }
                   2140:     if (oldObject.name) {
                   2141:         newObject.name = oldObject.name;
                   2142:     }
                   2143:     if (oldObject.id) {
                   2144:         newObject.id = oldObject.id;
                   2145:     }
                   2146:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2147:     return;
                   2148: }
                   2149: 
                   2150: ENDJS
1.475     www      2151: }
                   2152: 
1.167     www      2153: sub gradeleveldescription {
                   2154:     my $gradelevel=shift;
                   2155:     my %gradelevels=(0 => 'Not specified',
                   2156: 		     1 => 'Grade 1',
                   2157: 		     2 => 'Grade 2',
                   2158: 		     3 => 'Grade 3',
                   2159: 		     4 => 'Grade 4',
                   2160: 		     5 => 'Grade 5',
                   2161: 		     6 => 'Grade 6',
                   2162: 		     7 => 'Grade 7',
                   2163: 		     8 => 'Grade 8',
                   2164: 		     9 => 'Grade 9',
                   2165: 		     10 => 'Grade 10',
                   2166: 		     11 => 'Grade 11',
                   2167: 		     12 => 'Grade 12',
                   2168: 		     13 => 'Grade 13',
                   2169: 		     14 => '100 Level',
                   2170: 		     15 => '200 Level',
                   2171: 		     16 => '300 Level',
                   2172: 		     17 => '400 Level',
                   2173: 		     18 => 'Graduate Level');
                   2174:     return &mt($gradelevels{$gradelevel});
                   2175: }
                   2176: 
1.163     www      2177: sub select_level_form {
                   2178:     my ($deflevel,$name)=@_;
                   2179:     unless ($deflevel) { $deflevel=0; }
1.167     www      2180:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2181:     for (my $i=0; $i<=18; $i++) {
                   2182:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2183:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2184:                 ">".&gradeleveldescription($i)."</option>\n";
                   2185:     }
                   2186:     $selectform.="</select>";
                   2187:     return $selectform;
1.163     www      2188: }
1.167     www      2189: 
1.35      matthew  2190: #-------------------------------------------
                   2191: 
1.45      matthew  2192: =pod
                   2193: 
1.1121    raeburn  2194: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2195: 
                   2196: Returns a string containing a <select name='$name' size='1'> form to 
                   2197: allow a user to select the domain to preform an operation in.  
                   2198: See loncreateuser.pm for an example invocation and use.
                   2199: 
1.90      www      2200: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2201: selected");
                   2202: 
1.743     raeburn  2203: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2204: 
1.910     raeburn  2205: 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.
                   2206: 
1.1121    raeburn  2207: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2208: 
                   2209: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2210: 
1.35      matthew  2211: =cut
                   2212: 
                   2213: #-------------------------------------------
1.34      matthew  2214: sub select_dom_form {
1.1121    raeburn  2215:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2216:     if ($onchange) {
1.874     raeburn  2217:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2218:     }
1.1121    raeburn  2219:     my (@domains,%exclude);
1.910     raeburn  2220:     if (ref($incdoms) eq 'ARRAY') {
                   2221:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2222:     } else {
                   2223:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2224:     }
1.90      www      2225:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2226:     if (ref($excdoms) eq 'ARRAY') {
                   2227:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2228:     }
1.743     raeburn  2229:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2230:     foreach my $dom (@domains) {
1.1121    raeburn  2231:         next if ($exclude{$dom});
1.356     albertel 2232:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2233:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2234:         if ($showdomdesc) {
                   2235:             if ($dom ne '') {
                   2236:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2237:                 if ($domdesc ne '') {
                   2238:                     $selectdomain .= ' ('.$domdesc.')';
                   2239:                 }
                   2240:             } 
                   2241:         }
                   2242:         $selectdomain .= "</option>\n";
1.34      matthew  2243:     }
                   2244:     $selectdomain.="</select>";
                   2245:     return $selectdomain;
                   2246: }
                   2247: 
1.35      matthew  2248: #-------------------------------------------
                   2249: 
1.45      matthew  2250: =pod
                   2251: 
1.648     raeburn  2252: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2253: 
1.586     raeburn  2254: input: 4 arguments (two required, two optional) - 
                   2255:     $domain - domain of new user
                   2256:     $name - name of form element
                   2257:     $default - Value of 'default' causes a default item to be first 
                   2258:                             option, and selected by default. 
                   2259:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2260:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2261: output: returns 2 items: 
1.586     raeburn  2262: (a) form element which contains either:
                   2263:    (i) <select name="$name">
                   2264:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2265:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2266:        </select>
                   2267:        form item if there are multiple library servers in $domain, or
                   2268:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2269:        if there is only one library server in $domain.
                   2270: 
                   2271: (b) number of library servers found.
                   2272: 
                   2273: See loncreateuser.pm for example of use.
1.35      matthew  2274: 
                   2275: =cut
                   2276: 
                   2277: #-------------------------------------------
1.586     raeburn  2278: sub home_server_form_item {
                   2279:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2280:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2281:     my $result;
                   2282:     my $numlib = keys(%servers);
                   2283:     if ($numlib > 1) {
                   2284:         $result .= '<select name="'.$name.'" />'."\n";
                   2285:         if ($default) {
1.804     bisitz   2286:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2287:                        '</option>'."\n";
                   2288:         }
                   2289:         foreach my $hostid (sort(keys(%servers))) {
                   2290:             $result.= '<option value="'.$hostid.'">'.
                   2291: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2292:         }
                   2293:         $result .= '</select>'."\n";
                   2294:     } elsif ($numlib == 1) {
                   2295:         my $hostid;
                   2296:         foreach my $item (keys(%servers)) {
                   2297:             $hostid = $item;
                   2298:         }
                   2299:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2300:                    $hostid.'" />';
                   2301:                    if (!$hide) {
                   2302:                        $result .= $hostid.' '.$servers{$hostid};
                   2303:                    }
                   2304:                    $result .= "\n";
                   2305:     } elsif ($default) {
                   2306:         $result .= '<input type="hidden" name="'.$name.
                   2307:                    '" value="default" />';
                   2308:                    if (!$hide) {
                   2309:                        $result .= &mt('default');
                   2310:                    }
                   2311:                    $result .= "\n";
1.33      matthew  2312:     }
1.586     raeburn  2313:     return ($result,$numlib);
1.33      matthew  2314: }
1.112     bowersj2 2315: 
                   2316: =pod
                   2317: 
1.534     albertel 2318: =back 
                   2319: 
1.112     bowersj2 2320: =cut
1.87      matthew  2321: 
                   2322: ###############################################################
1.112     bowersj2 2323: ##                  Decoding User Agent                      ##
1.87      matthew  2324: ###############################################################
                   2325: 
                   2326: =pod
                   2327: 
1.112     bowersj2 2328: =head1 Decoding the User Agent
                   2329: 
                   2330: =over 4
                   2331: 
                   2332: =item * &decode_user_agent()
1.87      matthew  2333: 
                   2334: Inputs: $r
                   2335: 
                   2336: Outputs:
                   2337: 
                   2338: =over 4
                   2339: 
1.112     bowersj2 2340: =item * $httpbrowser
1.87      matthew  2341: 
1.112     bowersj2 2342: =item * $clientbrowser
1.87      matthew  2343: 
1.112     bowersj2 2344: =item * $clientversion
1.87      matthew  2345: 
1.112     bowersj2 2346: =item * $clientmathml
1.87      matthew  2347: 
1.112     bowersj2 2348: =item * $clientunicode
1.87      matthew  2349: 
1.112     bowersj2 2350: =item * $clientos
1.87      matthew  2351: 
                   2352: =back
                   2353: 
1.157     matthew  2354: =back 
                   2355: 
1.87      matthew  2356: =cut
                   2357: 
                   2358: ###############################################################
                   2359: ###############################################################
                   2360: sub decode_user_agent {
1.247     albertel 2361:     my ($r)=@_;
1.87      matthew  2362:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2363:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2364:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2365:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2366:     my $clientbrowser='unknown';
                   2367:     my $clientversion='0';
                   2368:     my $clientmathml='';
                   2369:     my $clientunicode='0';
                   2370:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2371:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2372: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2373: 	    $clientbrowser=$bname;
                   2374:             $httpbrowser=~/$vreg/i;
                   2375: 	    $clientversion=$1;
                   2376:             $clientmathml=($clientversion>=$minv);
                   2377:             $clientunicode=($clientversion>=$univ);
                   2378: 	}
                   2379:     }
                   2380:     my $clientos='unknown';
                   2381:     if (($httpbrowser=~/linux/i) ||
                   2382:         ($httpbrowser=~/unix/i) ||
                   2383:         ($httpbrowser=~/ux/i) ||
                   2384:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2385:     if (($httpbrowser=~/vax/i) ||
                   2386:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2387:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2388:     if (($httpbrowser=~/mac/i) ||
                   2389:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2390:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2391:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   2392:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   2393:             $clientunicode,$clientos,);
                   2394: }
                   2395: 
1.32      matthew  2396: ###############################################################
                   2397: ##    Authentication changing form generation subroutines    ##
                   2398: ###############################################################
                   2399: ##
                   2400: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2401: ## hash, and have reasonable default values.
                   2402: ##
                   2403: ##    formname = the name given in the <form> tag.
1.35      matthew  2404: #-------------------------------------------
                   2405: 
1.45      matthew  2406: =pod
                   2407: 
1.112     bowersj2 2408: =head1 Authentication Routines
                   2409: 
                   2410: =over 4
                   2411: 
1.648     raeburn  2412: =item * &authform_xxxxxx()
1.35      matthew  2413: 
                   2414: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2415: handle some of the conveniences required for authentication forms.  
                   2416: This is not an optimal method, but it works.  
                   2417: 
                   2418: =over 4
                   2419: 
1.112     bowersj2 2420: =item * authform_header
1.35      matthew  2421: 
1.112     bowersj2 2422: =item * authform_authorwarning
1.35      matthew  2423: 
1.112     bowersj2 2424: =item * authform_nochange
1.35      matthew  2425: 
1.112     bowersj2 2426: =item * authform_kerberos
1.35      matthew  2427: 
1.112     bowersj2 2428: =item * authform_internal
1.35      matthew  2429: 
1.112     bowersj2 2430: =item * authform_filesystem
1.35      matthew  2431: 
                   2432: =back
                   2433: 
1.648     raeburn  2434: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2435: 
1.35      matthew  2436: =cut
                   2437: 
                   2438: #-------------------------------------------
1.32      matthew  2439: sub authform_header{  
                   2440:     my %in = (
                   2441:         formname => 'cu',
1.80      albertel 2442:         kerb_def_dom => '',
1.32      matthew  2443:         @_,
                   2444:     );
                   2445:     $in{'formname'} = 'document.' . $in{'formname'};
                   2446:     my $result='';
1.80      albertel 2447: 
                   2448: #---------------------------------------------- Code for upper case translation
                   2449:     my $Javascript_toUpperCase;
                   2450:     unless ($in{kerb_def_dom}) {
                   2451:         $Javascript_toUpperCase =<<"END";
                   2452:         switch (choice) {
                   2453:            case 'krb': currentform.elements[choicearg].value =
                   2454:                currentform.elements[choicearg].value.toUpperCase();
                   2455:                break;
                   2456:            default:
                   2457:         }
                   2458: END
                   2459:     } else {
                   2460:         $Javascript_toUpperCase = "";
                   2461:     }
                   2462: 
1.165     raeburn  2463:     my $radioval = "'nochange'";
1.591     raeburn  2464:     if (defined($in{'curr_authtype'})) {
                   2465:         if ($in{'curr_authtype'} ne '') {
                   2466:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2467:         }
1.174     matthew  2468:     }
1.165     raeburn  2469:     my $argfield = 'null';
1.591     raeburn  2470:     if (defined($in{'mode'})) {
1.165     raeburn  2471:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2472:             if (defined($in{'curr_autharg'})) {
                   2473:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2474:                     $argfield = "'$in{'curr_autharg'}'";
                   2475:                 }
                   2476:             }
                   2477:         }
                   2478:     }
                   2479: 
1.32      matthew  2480:     $result.=<<"END";
                   2481: var current = new Object();
1.165     raeburn  2482: current.radiovalue = $radioval;
                   2483: current.argfield = $argfield;
1.32      matthew  2484: 
                   2485: function changed_radio(choice,currentform) {
                   2486:     var choicearg = choice + 'arg';
                   2487:     // If a radio button in changed, we need to change the argfield
                   2488:     if (current.radiovalue != choice) {
                   2489:         current.radiovalue = choice;
                   2490:         if (current.argfield != null) {
                   2491:             currentform.elements[current.argfield].value = '';
                   2492:         }
                   2493:         if (choice == 'nochange') {
                   2494:             current.argfield = null;
                   2495:         } else {
                   2496:             current.argfield = choicearg;
                   2497:             switch(choice) {
                   2498:                 case 'krb': 
                   2499:                     currentform.elements[current.argfield].value = 
                   2500:                         "$in{'kerb_def_dom'}";
                   2501:                 break;
                   2502:               default:
                   2503:                 break;
                   2504:             }
                   2505:         }
                   2506:     }
                   2507:     return;
                   2508: }
1.22      www      2509: 
1.32      matthew  2510: function changed_text(choice,currentform) {
                   2511:     var choicearg = choice + 'arg';
                   2512:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2513:         $Javascript_toUpperCase
1.32      matthew  2514:         // clear old field
                   2515:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2516:             currentform.elements[current.argfield].value = '';
                   2517:         }
                   2518:         current.argfield = choicearg;
                   2519:     }
                   2520:     set_auth_radio_buttons(choice,currentform);
                   2521:     return;
1.20      www      2522: }
1.32      matthew  2523: 
                   2524: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2525:     var numauthchoices = currentform.login.length;
                   2526:     if (typeof numauthchoices  == "undefined") {
                   2527:         return;
                   2528:     } 
1.32      matthew  2529:     var i=0;
1.986     raeburn  2530:     while (i < numauthchoices) {
1.32      matthew  2531:         if (currentform.login[i].value == newvalue) { break; }
                   2532:         i++;
                   2533:     }
1.986     raeburn  2534:     if (i == numauthchoices) {
1.32      matthew  2535:         return;
                   2536:     }
                   2537:     current.radiovalue = newvalue;
                   2538:     currentform.login[i].checked = true;
                   2539:     return;
                   2540: }
                   2541: END
                   2542:     return $result;
                   2543: }
                   2544: 
1.1106    raeburn  2545: sub authform_authorwarning {
1.32      matthew  2546:     my $result='';
1.144     matthew  2547:     $result='<i>'.
                   2548:         &mt('As a general rule, only authors or co-authors should be '.
                   2549:             'filesystem authenticated '.
                   2550:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2551:     return $result;
                   2552: }
                   2553: 
1.1106    raeburn  2554: sub authform_nochange {
1.32      matthew  2555:     my %in = (
                   2556:               formname => 'document.cu',
                   2557:               kerb_def_dom => 'MSU.EDU',
                   2558:               @_,
                   2559:           );
1.1106    raeburn  2560:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2561:     my $result;
1.1104    raeburn  2562:     if (!$authnum) {
1.1105    raeburn  2563:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2564:     } else {
                   2565:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2566:                   '<input type="radio" name="login" value="nochange" '.
                   2567:                   'checked="checked" onclick="'.
1.281     albertel 2568:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2569: 	    '</label>';
1.586     raeburn  2570:     }
1.32      matthew  2571:     return $result;
                   2572: }
                   2573: 
1.591     raeburn  2574: sub authform_kerberos {
1.32      matthew  2575:     my %in = (
                   2576:               formname => 'document.cu',
                   2577:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2578:               kerb_def_auth => 'krb4',
1.32      matthew  2579:               @_,
                   2580:               );
1.586     raeburn  2581:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2582:         $autharg,$jscall);
1.1106    raeburn  2583:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2584:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2585:        $check5 = ' checked="checked"';
1.80      albertel 2586:     } else {
1.772     bisitz   2587:        $check4 = ' checked="checked"';
1.80      albertel 2588:     }
1.165     raeburn  2589:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2590:     if (defined($in{'curr_authtype'})) {
                   2591:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2592:             $krbcheck = ' checked="checked"';
1.623     raeburn  2593:             if (defined($in{'mode'})) {
                   2594:                 if ($in{'mode'} eq 'modifyuser') {
                   2595:                     $krbcheck = '';
                   2596:                 }
                   2597:             }
1.591     raeburn  2598:             if (defined($in{'curr_kerb_ver'})) {
                   2599:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2600:                     $check5 = ' checked="checked"';
1.591     raeburn  2601:                     $check4 = '';
                   2602:                 } else {
1.772     bisitz   2603:                     $check4 = ' checked="checked"';
1.591     raeburn  2604:                     $check5 = '';
                   2605:                 }
1.586     raeburn  2606:             }
1.591     raeburn  2607:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2608:                 $krbarg = $in{'curr_autharg'};
                   2609:             }
1.586     raeburn  2610:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2611:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2612:                     $result = 
                   2613:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2614:         $in{'curr_autharg'},$krbver);
                   2615:                 } else {
                   2616:                     $result =
                   2617:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2618:                 }
                   2619:                 return $result; 
                   2620:             }
                   2621:         }
                   2622:     } else {
                   2623:         if ($authnum == 1) {
1.784     bisitz   2624:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2625:         }
                   2626:     }
1.586     raeburn  2627:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2628:         return;
1.587     raeburn  2629:     } elsif ($authtype eq '') {
1.591     raeburn  2630:         if (defined($in{'mode'})) {
1.587     raeburn  2631:             if ($in{'mode'} eq 'modifycourse') {
                   2632:                 if ($authnum == 1) {
1.1104    raeburn  2633:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2634:                 }
                   2635:             }
                   2636:         }
1.586     raeburn  2637:     }
                   2638:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2639:     if ($authtype eq '') {
                   2640:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2641:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2642:                     $krbcheck.' />';
                   2643:     }
                   2644:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2645:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2646:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2647:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2648:          $in{'curr_authtype'} eq 'krb4')) {
                   2649:         $result .= &mt
1.144     matthew  2650:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2651:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2652:          '<label>'.$authtype,
1.281     albertel 2653:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2654:              'value="'.$krbarg.'" '.
1.144     matthew  2655:              'onchange="'.$jscall.'" />',
1.281     albertel 2656:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2657:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2658: 	 '</label>');
1.586     raeburn  2659:     } elsif ($can_assign{'krb4'}) {
                   2660:         $result .= &mt
                   2661:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2662:          '[_3] Version 4 [_4]',
                   2663:          '<label>'.$authtype,
                   2664:          '</label><input type="text" size="10" name="krbarg" '.
                   2665:              'value="'.$krbarg.'" '.
                   2666:              'onchange="'.$jscall.'" />',
                   2667:          '<label><input type="hidden" name="krbver" value="4" />',
                   2668:          '</label>');
                   2669:     } elsif ($can_assign{'krb5'}) {
                   2670:         $result .= &mt
                   2671:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2672:          '[_3] Version 5 [_4]',
                   2673:          '<label>'.$authtype,
                   2674:          '</label><input type="text" size="10" name="krbarg" '.
                   2675:              'value="'.$krbarg.'" '.
                   2676:              'onchange="'.$jscall.'" />',
                   2677:          '<label><input type="hidden" name="krbver" value="5" />',
                   2678:          '</label>');
                   2679:     }
1.32      matthew  2680:     return $result;
                   2681: }
                   2682: 
1.1106    raeburn  2683: sub authform_internal {
1.586     raeburn  2684:     my %in = (
1.32      matthew  2685:                 formname => 'document.cu',
                   2686:                 kerb_def_dom => 'MSU.EDU',
                   2687:                 @_,
                   2688:                 );
1.586     raeburn  2689:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2690:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2691:     if (defined($in{'curr_authtype'})) {
                   2692:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2693:             if ($can_assign{'int'}) {
1.772     bisitz   2694:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2695:                 if (defined($in{'mode'})) {
                   2696:                     if ($in{'mode'} eq 'modifyuser') {
                   2697:                         $intcheck = '';
                   2698:                     }
                   2699:                 }
1.591     raeburn  2700:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2701:                     $intarg = $in{'curr_autharg'};
                   2702:                 }
                   2703:             } else {
                   2704:                 $result = &mt('Currently internally authenticated.');
                   2705:                 return $result;
1.165     raeburn  2706:             }
                   2707:         }
1.586     raeburn  2708:     } else {
                   2709:         if ($authnum == 1) {
1.784     bisitz   2710:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2711:         }
                   2712:     }
                   2713:     if (!$can_assign{'int'}) {
                   2714:         return;
1.587     raeburn  2715:     } elsif ($authtype eq '') {
1.591     raeburn  2716:         if (defined($in{'mode'})) {
1.587     raeburn  2717:             if ($in{'mode'} eq 'modifycourse') {
                   2718:                 if ($authnum == 1) {
1.1104    raeburn  2719:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2720:                 }
                   2721:             }
                   2722:         }
1.165     raeburn  2723:     }
1.586     raeburn  2724:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2725:     if ($authtype eq '') {
                   2726:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2727:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2728:     }
1.605     bisitz   2729:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2730:                $intarg.'" onchange="'.$jscall.'" />';
                   2731:     $result = &mt
1.144     matthew  2732:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2733:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2734:     $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  2735:     return $result;
                   2736: }
                   2737: 
1.1104    raeburn  2738: sub authform_local {
1.32      matthew  2739:     my %in = (
                   2740:               formname => 'document.cu',
                   2741:               kerb_def_dom => 'MSU.EDU',
                   2742:               @_,
                   2743:               );
1.586     raeburn  2744:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2745:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2746:     if (defined($in{'curr_authtype'})) {
                   2747:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2748:             if ($can_assign{'loc'}) {
1.772     bisitz   2749:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2750:                 if (defined($in{'mode'})) {
                   2751:                     if ($in{'mode'} eq 'modifyuser') {
                   2752:                         $loccheck = '';
                   2753:                     }
                   2754:                 }
1.591     raeburn  2755:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2756:                     $locarg = $in{'curr_autharg'};
                   2757:                 }
                   2758:             } else {
                   2759:                 $result = &mt('Currently using local (institutional) authentication.');
                   2760:                 return $result;
1.165     raeburn  2761:             }
                   2762:         }
1.586     raeburn  2763:     } else {
                   2764:         if ($authnum == 1) {
1.784     bisitz   2765:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2766:         }
                   2767:     }
                   2768:     if (!$can_assign{'loc'}) {
                   2769:         return;
1.587     raeburn  2770:     } elsif ($authtype eq '') {
1.591     raeburn  2771:         if (defined($in{'mode'})) {
1.587     raeburn  2772:             if ($in{'mode'} eq 'modifycourse') {
                   2773:                 if ($authnum == 1) {
1.1104    raeburn  2774:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2775:                 }
                   2776:             }
                   2777:         }
1.165     raeburn  2778:     }
1.586     raeburn  2779:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2780:     if ($authtype eq '') {
                   2781:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2782:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2783:                     $jscall.'" />';
                   2784:     }
                   2785:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2786:                $locarg.'" onchange="'.$jscall.'" />';
                   2787:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2788:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2789:     return $result;
                   2790: }
                   2791: 
1.1106    raeburn  2792: sub authform_filesystem {
1.32      matthew  2793:     my %in = (
                   2794:               formname => 'document.cu',
                   2795:               kerb_def_dom => 'MSU.EDU',
                   2796:               @_,
                   2797:               );
1.586     raeburn  2798:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2799:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2800:     if (defined($in{'curr_authtype'})) {
                   2801:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2802:             if ($can_assign{'fsys'}) {
1.772     bisitz   2803:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2804:                 if (defined($in{'mode'})) {
                   2805:                     if ($in{'mode'} eq 'modifyuser') {
                   2806:                         $fsyscheck = '';
                   2807:                     }
                   2808:                 }
1.586     raeburn  2809:             } else {
                   2810:                 $result = &mt('Currently Filesystem Authenticated.');
                   2811:                 return $result;
                   2812:             }           
                   2813:         }
                   2814:     } else {
                   2815:         if ($authnum == 1) {
1.784     bisitz   2816:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2817:         }
                   2818:     }
                   2819:     if (!$can_assign{'fsys'}) {
                   2820:         return;
1.587     raeburn  2821:     } elsif ($authtype eq '') {
1.591     raeburn  2822:         if (defined($in{'mode'})) {
1.587     raeburn  2823:             if ($in{'mode'} eq 'modifycourse') {
                   2824:                 if ($authnum == 1) {
1.1104    raeburn  2825:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2826:                 }
                   2827:             }
                   2828:         }
1.586     raeburn  2829:     }
                   2830:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2831:     if ($authtype eq '') {
                   2832:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2833:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2834:                     $jscall.'" />';
                   2835:     }
                   2836:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2837:                ' onchange="'.$jscall.'" />';
                   2838:     $result = &mt
1.144     matthew  2839:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2840:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2841:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2842:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2843:                   'onchange="'.$jscall.'" />');
1.32      matthew  2844:     return $result;
                   2845: }
                   2846: 
1.586     raeburn  2847: sub get_assignable_auth {
                   2848:     my ($dom) = @_;
                   2849:     if ($dom eq '') {
                   2850:         $dom = $env{'request.role.domain'};
                   2851:     }
                   2852:     my %can_assign = (
                   2853:                           krb4 => 1,
                   2854:                           krb5 => 1,
                   2855:                           int  => 1,
                   2856:                           loc  => 1,
                   2857:                      );
                   2858:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2859:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2860:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2861:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2862:             my $context;
                   2863:             if ($env{'request.role'} =~ /^au/) {
                   2864:                 $context = 'author';
                   2865:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2866:                 $context = 'domain';
                   2867:             } elsif ($env{'request.course.id'}) {
                   2868:                 $context = 'course';
                   2869:             }
                   2870:             if ($context) {
                   2871:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2872:                    %can_assign = %{$authhash->{$context}}; 
                   2873:                 }
                   2874:             }
                   2875:         }
                   2876:     }
                   2877:     my $authnum = 0;
                   2878:     foreach my $key (keys(%can_assign)) {
                   2879:         if ($can_assign{$key}) {
                   2880:             $authnum ++;
                   2881:         }
                   2882:     }
                   2883:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2884:         $authnum --;
                   2885:     }
                   2886:     return ($authnum,%can_assign);
                   2887: }
                   2888: 
1.80      albertel 2889: ###############################################################
                   2890: ##    Get Kerberos Defaults for Domain                 ##
                   2891: ###############################################################
                   2892: ##
                   2893: ## Returns default kerberos version and an associated argument
                   2894: ## as listed in file domain.tab. If not listed, provides
                   2895: ## appropriate default domain and kerberos version.
                   2896: ##
                   2897: #-------------------------------------------
                   2898: 
                   2899: =pod
                   2900: 
1.648     raeburn  2901: =item * &get_kerberos_defaults()
1.80      albertel 2902: 
                   2903: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2904: version and domain. If not found, it defaults to version 4 and the 
                   2905: domain of the server.
1.80      albertel 2906: 
1.648     raeburn  2907: =over 4
                   2908: 
1.80      albertel 2909: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2910: 
1.648     raeburn  2911: =back
                   2912: 
                   2913: =back
                   2914: 
1.80      albertel 2915: =cut
                   2916: 
                   2917: #-------------------------------------------
                   2918: sub get_kerberos_defaults {
                   2919:     my $domain=shift;
1.641     raeburn  2920:     my ($krbdef,$krbdefdom);
                   2921:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2922:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2923:         $krbdef = $domdefaults{'auth_def'};
                   2924:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2925:     } else {
1.80      albertel 2926:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2927:         my $krbdefdom=$1;
                   2928:         $krbdefdom=~tr/a-z/A-Z/;
                   2929:         $krbdef = "krb4";
                   2930:     }
                   2931:     return ($krbdef,$krbdefdom);
                   2932: }
1.112     bowersj2 2933: 
1.32      matthew  2934: 
1.46      matthew  2935: ###############################################################
                   2936: ##                Thesaurus Functions                        ##
                   2937: ###############################################################
1.20      www      2938: 
1.46      matthew  2939: =pod
1.20      www      2940: 
1.112     bowersj2 2941: =head1 Thesaurus Functions
                   2942: 
                   2943: =over 4
                   2944: 
1.648     raeburn  2945: =item * &initialize_keywords()
1.46      matthew  2946: 
                   2947: Initializes the package variable %Keywords if it is empty.  Uses the
                   2948: package variable $thesaurus_db_file.
                   2949: 
                   2950: =cut
                   2951: 
                   2952: ###################################################
                   2953: 
                   2954: sub initialize_keywords {
                   2955:     return 1 if (scalar keys(%Keywords));
                   2956:     # If we are here, %Keywords is empty, so fill it up
                   2957:     #   Make sure the file we need exists...
                   2958:     if (! -e $thesaurus_db_file) {
                   2959:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2960:                                  " failed because it does not exist");
                   2961:         return 0;
                   2962:     }
                   2963:     #   Set up the hash as a database
                   2964:     my %thesaurus_db;
                   2965:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2966:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2967:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2968:                                  $thesaurus_db_file);
                   2969:         return 0;
                   2970:     } 
                   2971:     #  Get the average number of appearances of a word.
                   2972:     my $avecount = $thesaurus_db{'average.count'};
                   2973:     #  Put keywords (those that appear > average) into %Keywords
                   2974:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2975:         my ($count,undef) = split /:/,$data;
                   2976:         $Keywords{$word}++ if ($count > $avecount);
                   2977:     }
                   2978:     untie %thesaurus_db;
                   2979:     # Remove special values from %Keywords.
1.356     albertel 2980:     foreach my $value ('total.count','average.count') {
                   2981:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2982:   }
1.46      matthew  2983:     return 1;
                   2984: }
                   2985: 
                   2986: ###################################################
                   2987: 
                   2988: =pod
                   2989: 
1.648     raeburn  2990: =item * &keyword($word)
1.46      matthew  2991: 
                   2992: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2993: than the average number of times in the thesaurus database.  Calls 
                   2994: &initialize_keywords
                   2995: 
                   2996: =cut
                   2997: 
                   2998: ###################################################
1.20      www      2999: 
                   3000: sub keyword {
1.46      matthew  3001:     return if (!&initialize_keywords());
                   3002:     my $word=lc(shift());
                   3003:     $word=~s/\W//g;
                   3004:     return exists($Keywords{$word});
1.20      www      3005: }
1.46      matthew  3006: 
                   3007: ###############################################################
                   3008: 
                   3009: =pod 
1.20      www      3010: 
1.648     raeburn  3011: =item * &get_related_words()
1.46      matthew  3012: 
1.160     matthew  3013: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3014: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3015: will be returned.  The order of the words returned is determined by the
                   3016: database which holds them.
                   3017: 
                   3018: Uses global $thesaurus_db_file.
                   3019: 
1.1057    foxr     3020: 
1.46      matthew  3021: =cut
                   3022: 
                   3023: ###############################################################
                   3024: sub get_related_words {
                   3025:     my $keyword = shift;
                   3026:     my %thesaurus_db;
                   3027:     if (! -e $thesaurus_db_file) {
                   3028:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3029:                                  "failed because the file does not exist");
                   3030:         return ();
                   3031:     }
                   3032:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3033:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3034:         return ();
                   3035:     } 
                   3036:     my @Words=();
1.429     www      3037:     my $count=0;
1.46      matthew  3038:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3039: 	# The first element is the number of times
                   3040: 	# the word appears.  We do not need it now.
1.429     www      3041: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3042: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3043: 	my $threshold=$mostfrequentcount/10;
                   3044:         foreach my $possibleword (@RelatedWords) {
                   3045:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3046:             if ($wordcount>$threshold) {
                   3047: 		push(@Words,$word);
                   3048:                 $count++;
                   3049:                 if ($count>10) { last; }
                   3050: 	    }
1.20      www      3051:         }
                   3052:     }
1.46      matthew  3053:     untie %thesaurus_db;
                   3054:     return @Words;
1.14      harris41 3055: }
1.1090    foxr     3056: ###############################################################
                   3057: #
                   3058: #  Spell checking
                   3059: #
                   3060: 
                   3061: =pod
                   3062: 
                   3063: =head1 Spell checking
                   3064: 
                   3065: =over 4
                   3066: 
                   3067: =item * &check_spelling($wordlist $language)
                   3068: 
                   3069: Takes a string containing words and feeds it to an external
                   3070: spellcheck program via a pipeline. Returns a string containing
                   3071: them mis-spelled words.
                   3072: 
                   3073: Parameters:
                   3074: 
                   3075: =over 4
                   3076: 
                   3077: =item - $wordlist
                   3078: 
                   3079: String that will be fed into the spellcheck program.
                   3080: 
                   3081: =item - $language
                   3082: 
                   3083: Language string that specifies the language for which the spell
                   3084: check will be performed.
                   3085: 
                   3086: =back
                   3087: 
                   3088: =back
                   3089: 
                   3090: Note: This sub assumes that aspell is installed.
                   3091: 
                   3092: 
                   3093: =cut
                   3094: 
1.46      matthew  3095: 
1.112     bowersj2 3096: =pod
                   3097: 
                   3098: =back
                   3099: 
                   3100: =cut
1.61      www      3101: 
1.1090    foxr     3102: sub check_spelling {
                   3103:     my ($wordlist, $language) = @_;
1.1091    foxr     3104:     my @misspellings;
                   3105:     
                   3106:     # Generate the speller and set the langauge.
                   3107:     # if explicitly selected:
1.1090    foxr     3108: 
1.1091    foxr     3109:     my $speller = Text::Aspell->new;
1.1090    foxr     3110:     if ($language) {
1.1091    foxr     3111: 	$speller->set_option('lang', $language);
1.1090    foxr     3112:     }
                   3113: 
1.1091    foxr     3114:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3115: 
1.1091    foxr     3116:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3117: 
1.1091    foxr     3118:     foreach my $word (@words) {
                   3119: 	if(! $speller->check($word)) {
                   3120: 	    push(@misspellings, $word);
1.1090    foxr     3121: 	}
                   3122:     }
1.1091    foxr     3123:     return join(' ', @misspellings);
                   3124:     
1.1090    foxr     3125: }
                   3126: 
1.61      www      3127: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3128: =pod
                   3129: 
1.112     bowersj2 3130: =head1 User Name Functions
                   3131: 
                   3132: =over 4
                   3133: 
1.648     raeburn  3134: =item * &plainname($uname,$udom,$first)
1.81      albertel 3135: 
1.112     bowersj2 3136: Takes a users logon name and returns it as a string in
1.226     albertel 3137: "first middle last generation" form 
                   3138: if $first is set to 'lastname' then it returns it as
                   3139: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3140: 
                   3141: =cut
1.61      www      3142: 
1.295     www      3143: 
1.81      albertel 3144: ###############################################################
1.61      www      3145: sub plainname {
1.226     albertel 3146:     my ($uname,$udom,$first)=@_;
1.537     albertel 3147:     return if (!defined($uname) || !defined($udom));
1.295     www      3148:     my %names=&getnames($uname,$udom);
1.226     albertel 3149:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3150: 					  $names{'middlename'},
                   3151: 					  $names{'lastname'},
                   3152: 					  $names{'generation'},$first);
                   3153:     $name=~s/^\s+//;
1.62      www      3154:     $name=~s/\s+$//;
                   3155:     $name=~s/\s+/ /g;
1.353     albertel 3156:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3157:     return $name;
1.61      www      3158: }
1.66      www      3159: 
                   3160: # -------------------------------------------------------------------- Nickname
1.81      albertel 3161: =pod
                   3162: 
1.648     raeburn  3163: =item * &nickname($uname,$udom)
1.81      albertel 3164: 
                   3165: Gets a users name and returns it as a string as
                   3166: 
                   3167: "&quot;nickname&quot;"
1.66      www      3168: 
1.81      albertel 3169: if the user has a nickname or
                   3170: 
                   3171: "first middle last generation"
                   3172: 
                   3173: if the user does not
                   3174: 
                   3175: =cut
1.66      www      3176: 
                   3177: sub nickname {
                   3178:     my ($uname,$udom)=@_;
1.537     albertel 3179:     return if (!defined($uname) || !defined($udom));
1.295     www      3180:     my %names=&getnames($uname,$udom);
1.68      albertel 3181:     my $name=$names{'nickname'};
1.66      www      3182:     if ($name) {
                   3183:        $name='&quot;'.$name.'&quot;'; 
                   3184:     } else {
                   3185:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3186: 	     $names{'lastname'}.' '.$names{'generation'};
                   3187:        $name=~s/\s+$//;
                   3188:        $name=~s/\s+/ /g;
                   3189:     }
                   3190:     return $name;
                   3191: }
                   3192: 
1.295     www      3193: sub getnames {
                   3194:     my ($uname,$udom)=@_;
1.537     albertel 3195:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3196:     if ($udom eq 'public' && $uname eq 'public') {
                   3197: 	return ('lastname' => &mt('Public'));
                   3198:     }
1.295     www      3199:     my $id=$uname.':'.$udom;
                   3200:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3201:     if ($cached) {
                   3202: 	return %{$names};
                   3203:     } else {
                   3204: 	my %loadnames=&Apache::lonnet::get('environment',
                   3205:                     ['firstname','middlename','lastname','generation','nickname'],
                   3206: 					 $udom,$uname);
                   3207: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3208: 	return %loadnames;
                   3209:     }
                   3210: }
1.61      www      3211: 
1.542     raeburn  3212: # -------------------------------------------------------------------- getemails
1.648     raeburn  3213: 
1.542     raeburn  3214: =pod
                   3215: 
1.648     raeburn  3216: =item * &getemails($uname,$udom)
1.542     raeburn  3217: 
                   3218: Gets a user's email information and returns it as a hash with keys:
                   3219: notification, critnotification, permanentemail
                   3220: 
                   3221: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3222: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3223:  
1.648     raeburn  3224: 
1.542     raeburn  3225: =cut
                   3226: 
1.648     raeburn  3227: 
1.466     albertel 3228: sub getemails {
                   3229:     my ($uname,$udom)=@_;
                   3230:     if ($udom eq 'public' && $uname eq 'public') {
                   3231: 	return;
                   3232:     }
1.467     www      3233:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3234:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3235:     my $id=$uname.':'.$udom;
                   3236:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3237:     if ($cached) {
                   3238: 	return %{$names};
                   3239:     } else {
                   3240: 	my %loadnames=&Apache::lonnet::get('environment',
                   3241:                     			   ['notification','critnotification',
                   3242: 					    'permanentemail'],
                   3243: 					   $udom,$uname);
                   3244: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3245: 	return %loadnames;
                   3246:     }
                   3247: }
                   3248: 
1.551     albertel 3249: sub flush_email_cache {
                   3250:     my ($uname,$udom)=@_;
                   3251:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3252:     if (!$uname) { $uname=$env{'user.name'};   }
                   3253:     return if ($udom eq 'public' && $uname eq 'public');
                   3254:     my $id=$uname.':'.$udom;
                   3255:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3256: }
                   3257: 
1.728     raeburn  3258: # -------------------------------------------------------------------- getlangs
                   3259: 
                   3260: =pod
                   3261: 
                   3262: =item * &getlangs($uname,$udom)
                   3263: 
                   3264: Gets a user's language preference and returns it as a hash with key:
                   3265: language.
                   3266: 
                   3267: =cut
                   3268: 
                   3269: 
                   3270: sub getlangs {
                   3271:     my ($uname,$udom) = @_;
                   3272:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3273:     if (!$uname) { $uname=$env{'user.name'};   }
                   3274:     my $id=$uname.':'.$udom;
                   3275:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3276:     if ($cached) {
                   3277:         return %{$langs};
                   3278:     } else {
                   3279:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3280:                                            $udom,$uname);
                   3281:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3282:         return %loadlangs;
                   3283:     }
                   3284: }
                   3285: 
                   3286: sub flush_langs_cache {
                   3287:     my ($uname,$udom)=@_;
                   3288:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3289:     if (!$uname) { $uname=$env{'user.name'};   }
                   3290:     return if ($udom eq 'public' && $uname eq 'public');
                   3291:     my $id=$uname.':'.$udom;
                   3292:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3293: }
                   3294: 
1.61      www      3295: # ------------------------------------------------------------------ Screenname
1.81      albertel 3296: 
                   3297: =pod
                   3298: 
1.648     raeburn  3299: =item * &screenname($uname,$udom)
1.81      albertel 3300: 
                   3301: Gets a users screenname and returns it as a string
                   3302: 
                   3303: =cut
1.61      www      3304: 
                   3305: sub screenname {
                   3306:     my ($uname,$udom)=@_;
1.258     albertel 3307:     if ($uname eq $env{'user.name'} &&
                   3308: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3309:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3310:     return $names{'screenname'};
1.62      www      3311: }
                   3312: 
1.212     albertel 3313: 
1.802     bisitz   3314: # ------------------------------------------------------------- Confirm Wrapper
                   3315: =pod
                   3316: 
                   3317: =item confirmwrapper
                   3318: 
                   3319: Wrap messages about completion of operation in box
                   3320: 
                   3321: =cut
                   3322: 
                   3323: sub confirmwrapper {
                   3324:     my ($message)=@_;
                   3325:     if ($message) {
                   3326:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3327:                .$message."\n"
                   3328:                .'</div>'."\n";
                   3329:     } else {
                   3330:         return $message;
                   3331:     }
                   3332: }
                   3333: 
1.62      www      3334: # ------------------------------------------------------------- Message Wrapper
                   3335: 
                   3336: sub messagewrapper {
1.369     www      3337:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3338:     return 
1.441     albertel 3339:         '<a href="/adm/email?compose=individual&amp;'.
                   3340:         'recname='.$username.'&amp;recdom='.$domain.
                   3341: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3342:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3343: }
1.802     bisitz   3344: 
1.74      www      3345: # --------------------------------------------------------------- Notes Wrapper
                   3346: 
                   3347: sub noteswrapper {
                   3348:     my ($link,$un,$do)=@_;
                   3349:     return 
1.896     amueller 3350: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3351: }
1.802     bisitz   3352: 
1.62      www      3353: # ------------------------------------------------------------- Aboutme Wrapper
                   3354: 
                   3355: sub aboutmewrapper {
1.1070    raeburn  3356:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3357:     if (!defined($username)  && !defined($domain)) {
                   3358:         return;
                   3359:     }
1.1096    raeburn  3360:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3361: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3362: }
                   3363: 
                   3364: # ------------------------------------------------------------ Syllabus Wrapper
                   3365: 
                   3366: sub syllabuswrapper {
1.707     bisitz   3367:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3368:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3369: }
1.14      harris41 3370: 
1.802     bisitz   3371: # -----------------------------------------------------------------------------
                   3372: 
1.208     matthew  3373: sub track_student_link {
1.887     raeburn  3374:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3375:     my $link ="/adm/trackstudent?";
1.208     matthew  3376:     my $title = 'View recent activity';
                   3377:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3378:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3379:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3380:         $title .= ' of this student';
1.268     albertel 3381:     } 
1.208     matthew  3382:     if (defined($target) && $target !~ /^\s*$/) {
                   3383:         $target = qq{target="$target"};
                   3384:     } else {
                   3385:         $target = '';
                   3386:     }
1.268     albertel 3387:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3388:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3389:     $title = &mt($title);
                   3390:     $linktext = &mt($linktext);
1.448     albertel 3391:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3392: 	&help_open_topic('View_recent_activity');
1.208     matthew  3393: }
                   3394: 
1.781     raeburn  3395: sub slot_reservations_link {
                   3396:     my ($linktext,$sname,$sdom,$target) = @_;
                   3397:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3398:     my $title = 'View slot reservation history';
                   3399:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3400:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3401:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3402:         $title .= ' of this student';
                   3403:     }
                   3404:     if (defined($target) && $target !~ /^\s*$/) {
                   3405:         $target = qq{target="$target"};
                   3406:     } else {
                   3407:         $target = '';
                   3408:     }
                   3409:     $title = &mt($title);
                   3410:     $linktext = &mt($linktext);
                   3411:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3412: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3413: 
                   3414: }
                   3415: 
1.508     www      3416: # ===================================================== Display a student photo
                   3417: 
                   3418: 
1.509     albertel 3419: sub student_image_tag {
1.508     www      3420:     my ($domain,$user)=@_;
                   3421:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3422:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3423: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3424:     } else {
                   3425: 	return '';
                   3426:     }
                   3427: }
                   3428: 
1.112     bowersj2 3429: =pod
                   3430: 
                   3431: =back
                   3432: 
                   3433: =head1 Access .tab File Data
                   3434: 
                   3435: =over 4
                   3436: 
1.648     raeburn  3437: =item * &languageids() 
1.112     bowersj2 3438: 
                   3439: returns list of all language ids
                   3440: 
                   3441: =cut
                   3442: 
1.14      harris41 3443: sub languageids {
1.16      harris41 3444:     return sort(keys(%language));
1.14      harris41 3445: }
                   3446: 
1.112     bowersj2 3447: =pod
                   3448: 
1.648     raeburn  3449: =item * &languagedescription() 
1.112     bowersj2 3450: 
                   3451: returns description of a specified language id
                   3452: 
                   3453: =cut
                   3454: 
1.14      harris41 3455: sub languagedescription {
1.125     www      3456:     my $code=shift;
                   3457:     return  ($supported_language{$code}?'* ':'').
                   3458:             $language{$code}.
1.126     www      3459: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3460: }
                   3461: 
1.1048    foxr     3462: =pod
                   3463: 
                   3464: =item * &plainlanguagedescription
                   3465: 
                   3466: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3467: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3468: 
                   3469: =cut
                   3470: 
1.145     www      3471: sub plainlanguagedescription {
                   3472:     my $code=shift;
                   3473:     return $language{$code};
                   3474: }
                   3475: 
1.1048    foxr     3476: =pod
                   3477: 
                   3478: =item * &supportedlanguagecode
                   3479: 
                   3480: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3481: code.
                   3482: 
                   3483: =cut
                   3484: 
1.145     www      3485: sub supportedlanguagecode {
                   3486:     my $code=shift;
                   3487:     return $supported_language{$code};
1.97      www      3488: }
                   3489: 
1.112     bowersj2 3490: =pod
                   3491: 
1.1048    foxr     3492: =item * &latexlanguage()
                   3493: 
                   3494: Given a language key code returns the correspondnig language to use
                   3495: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3496: is no supported hyphenation for the language code.
                   3497: 
                   3498: =cut
                   3499: 
                   3500: sub latexlanguage {
                   3501:     my $code = shift;
                   3502:     return $latex_language{$code};
                   3503: }
                   3504: 
                   3505: =pod
                   3506: 
                   3507: =item * &latexhyphenation()
                   3508: 
                   3509: Same as above but what's supplied is the language as it might be stored
                   3510: in the metadata.
                   3511: 
                   3512: =cut
                   3513: 
                   3514: sub latexhyphenation {
                   3515:     my $key = shift;
                   3516:     return $latex_language_bykey{$key};
                   3517: }
                   3518: 
                   3519: =pod
                   3520: 
1.648     raeburn  3521: =item * &copyrightids() 
1.112     bowersj2 3522: 
                   3523: returns list of all copyrights
                   3524: 
                   3525: =cut
                   3526: 
                   3527: sub copyrightids {
                   3528:     return sort(keys(%cprtag));
                   3529: }
                   3530: 
                   3531: =pod
                   3532: 
1.648     raeburn  3533: =item * &copyrightdescription() 
1.112     bowersj2 3534: 
                   3535: returns description of a specified copyright id
                   3536: 
                   3537: =cut
                   3538: 
                   3539: sub copyrightdescription {
1.166     www      3540:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3541: }
1.197     matthew  3542: 
                   3543: =pod
                   3544: 
1.648     raeburn  3545: =item * &source_copyrightids() 
1.192     taceyjo1 3546: 
                   3547: returns list of all source copyrights
                   3548: 
                   3549: =cut
                   3550: 
                   3551: sub source_copyrightids {
                   3552:     return sort(keys(%scprtag));
                   3553: }
                   3554: 
                   3555: =pod
                   3556: 
1.648     raeburn  3557: =item * &source_copyrightdescription() 
1.192     taceyjo1 3558: 
                   3559: returns description of a specified source copyright id
                   3560: 
                   3561: =cut
                   3562: 
                   3563: sub source_copyrightdescription {
                   3564:     return &mt($scprtag{shift(@_)});
                   3565: }
1.112     bowersj2 3566: 
                   3567: =pod
                   3568: 
1.648     raeburn  3569: =item * &filecategories() 
1.112     bowersj2 3570: 
                   3571: returns list of all file categories
                   3572: 
                   3573: =cut
                   3574: 
                   3575: sub filecategories {
                   3576:     return sort(keys(%category_extensions));
                   3577: }
                   3578: 
                   3579: =pod
                   3580: 
1.648     raeburn  3581: =item * &filecategorytypes() 
1.112     bowersj2 3582: 
                   3583: returns list of file types belonging to a given file
                   3584: category
                   3585: 
                   3586: =cut
                   3587: 
                   3588: sub filecategorytypes {
1.356     albertel 3589:     my ($cat) = @_;
                   3590:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3591: }
                   3592: 
                   3593: =pod
                   3594: 
1.648     raeburn  3595: =item * &fileembstyle() 
1.112     bowersj2 3596: 
                   3597: returns embedding style for a specified file type
                   3598: 
                   3599: =cut
                   3600: 
                   3601: sub fileembstyle {
                   3602:     return $fe{lc(shift(@_))};
1.169     www      3603: }
                   3604: 
1.351     www      3605: sub filemimetype {
                   3606:     return $fm{lc(shift(@_))};
                   3607: }
                   3608: 
1.169     www      3609: 
                   3610: sub filecategoryselect {
                   3611:     my ($name,$value)=@_;
1.189     matthew  3612:     return &select_form($value,$name,
1.970     raeburn  3613:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3614: }
                   3615: 
                   3616: =pod
                   3617: 
1.648     raeburn  3618: =item * &filedescription() 
1.112     bowersj2 3619: 
                   3620: returns description for a specified file type
                   3621: 
                   3622: =cut
                   3623: 
                   3624: sub filedescription {
1.188     matthew  3625:     my $file_description = $fd{lc(shift())};
                   3626:     $file_description =~ s:([\[\]]):~$1:g;
                   3627:     return &mt($file_description);
1.112     bowersj2 3628: }
                   3629: 
                   3630: =pod
                   3631: 
1.648     raeburn  3632: =item * &filedescriptionex() 
1.112     bowersj2 3633: 
                   3634: returns description for a specified file type with
                   3635: extra formatting
                   3636: 
                   3637: =cut
                   3638: 
                   3639: sub filedescriptionex {
                   3640:     my $ex=shift;
1.188     matthew  3641:     my $file_description = $fd{lc($ex)};
                   3642:     $file_description =~ s:([\[\]]):~$1:g;
                   3643:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3644: }
                   3645: 
                   3646: # End of .tab access
                   3647: =pod
                   3648: 
                   3649: =back
                   3650: 
                   3651: =cut
                   3652: 
                   3653: # ------------------------------------------------------------------ File Types
                   3654: sub fileextensions {
                   3655:     return sort(keys(%fe));
                   3656: }
                   3657: 
1.97      www      3658: # ----------------------------------------------------------- Display Languages
                   3659: # returns a hash with all desired display languages
                   3660: #
                   3661: 
                   3662: sub display_languages {
                   3663:     my %languages=();
1.695     raeburn  3664:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3665: 	$languages{$lang}=1;
1.97      www      3666:     }
                   3667:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3668:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3669: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3670: 	    $languages{$lang}=1;
1.97      www      3671:         }
                   3672:     }
                   3673:     return %languages;
1.14      harris41 3674: }
                   3675: 
1.582     albertel 3676: sub languages {
                   3677:     my ($possible_langs) = @_;
1.695     raeburn  3678:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3679:     if (!ref($possible_langs)) {
                   3680: 	if( wantarray ) {
                   3681: 	    return @preferred_langs;
                   3682: 	} else {
                   3683: 	    return $preferred_langs[0];
                   3684: 	}
                   3685:     }
                   3686:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3687:     my @preferred_possibilities;
                   3688:     foreach my $preferred_lang (@preferred_langs) {
                   3689: 	if (exists($possibilities{$preferred_lang})) {
                   3690: 	    push(@preferred_possibilities, $preferred_lang);
                   3691: 	}
                   3692:     }
                   3693:     if( wantarray ) {
                   3694: 	return @preferred_possibilities;
                   3695:     }
                   3696:     return $preferred_possibilities[0];
                   3697: }
                   3698: 
1.742     raeburn  3699: sub user_lang {
                   3700:     my ($touname,$toudom,$fromcid) = @_;
                   3701:     my @userlangs;
                   3702:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3703:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3704:                     $env{'course.'.$fromcid.'.languages'}));
                   3705:     } else {
                   3706:         my %langhash = &getlangs($touname,$toudom);
                   3707:         if ($langhash{'languages'} ne '') {
                   3708:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3709:         } else {
                   3710:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3711:             if ($domdefs{'lang_def'} ne '') {
                   3712:                 @userlangs = ($domdefs{'lang_def'});
                   3713:             }
                   3714:         }
                   3715:     }
                   3716:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3717:     my $user_lh = Apache::localize->get_handle(@languages);
                   3718:     return $user_lh;
                   3719: }
                   3720: 
                   3721: 
1.112     bowersj2 3722: ###############################################################
                   3723: ##               Student Answer Attempts                     ##
                   3724: ###############################################################
                   3725: 
                   3726: =pod
                   3727: 
                   3728: =head1 Alternate Problem Views
                   3729: 
                   3730: =over 4
                   3731: 
1.648     raeburn  3732: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3733:     $getattempt, $regexp, $gradesub)
                   3734: 
                   3735: Return string with previous attempt on problem. Arguments:
                   3736: 
                   3737: =over 4
                   3738: 
                   3739: =item * $symb: Problem, including path
                   3740: 
                   3741: =item * $username: username of the desired student
                   3742: 
                   3743: =item * $domain: domain of the desired student
1.14      harris41 3744: 
1.112     bowersj2 3745: =item * $course: Course ID
1.14      harris41 3746: 
1.112     bowersj2 3747: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3748:     something
1.14      harris41 3749: 
1.112     bowersj2 3750: =item * $regexp: if string matches this regexp, the string will be
                   3751:     sent to $gradesub
1.14      harris41 3752: 
1.112     bowersj2 3753: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3754: 
1.112     bowersj2 3755: =back
1.14      harris41 3756: 
1.112     bowersj2 3757: The output string is a table containing all desired attempts, if any.
1.16      harris41 3758: 
1.112     bowersj2 3759: =cut
1.1       albertel 3760: 
                   3761: sub get_previous_attempt {
1.43      ng       3762:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3763:   my $prevattempts='';
1.43      ng       3764:   no strict 'refs';
1.1       albertel 3765:   if ($symb) {
1.3       albertel 3766:     my (%returnhash)=
                   3767:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3768:     if ($returnhash{'version'}) {
                   3769:       my %lasthash=();
                   3770:       my $version;
                   3771:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3772:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3773: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3774:         }
1.1       albertel 3775:       }
1.596     albertel 3776:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3777:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3778:       my (%typeparts,%lasthidden);
1.945     raeburn  3779:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3780:       foreach my $key (sort(keys(%lasthash))) {
                   3781: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3782: 	if ($#parts > 0) {
1.31      albertel 3783: 	  my $data=$parts[-1];
1.989     raeburn  3784:           next if ($data eq 'foilorder');
1.31      albertel 3785: 	  pop(@parts);
1.1010    www      3786:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3787:           if ($data eq 'type') {
                   3788:               unless ($showsurv) {
                   3789:                   my $id = join(',',@parts);
                   3790:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3791:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3792:                       $lasthidden{$ign.'.'.$id} = 1;
                   3793:                   }
1.945     raeburn  3794:               }
1.1010    www      3795:           } 
1.31      albertel 3796: 	} else {
1.41      ng       3797: 	  if ($#parts == 0) {
                   3798: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3799: 	  } else {
                   3800: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3801: 	  }
1.31      albertel 3802: 	}
1.16      harris41 3803:       }
1.596     albertel 3804:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3805:       if ($getattempt eq '') {
                   3806: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3807:             my @hidden;
                   3808:             if (%typeparts) {
                   3809:                 foreach my $id (keys(%typeparts)) {
                   3810:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3811:                         push(@hidden,$id);
                   3812:                     }
                   3813:                 }
                   3814:             }
                   3815:             $prevattempts.=&start_data_table_row().
                   3816:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3817:             if (@hidden) {
                   3818:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3819:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3820:                     my $hide;
                   3821:                     foreach my $id (@hidden) {
                   3822:                         if ($key =~ /^\Q$id\E/) {
                   3823:                             $hide = 1;
                   3824:                             last;
                   3825:                         }
                   3826:                     }
                   3827:                     if ($hide) {
                   3828:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3829:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3830:                             my $value = &format_previous_attempt_value($key,
                   3831:                                              $returnhash{$version.':'.$key});
                   3832:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3833:                         } else {
                   3834:                             $prevattempts.='<td>&nbsp;</td>';
                   3835:                         }
                   3836:                     } else {
                   3837:                         if ($key =~ /\./) {
                   3838:                             my $value = &format_previous_attempt_value($key,
                   3839:                                               $returnhash{$version.':'.$key});
                   3840:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3841:                         } else {
                   3842:                             $prevattempts.='<td>&nbsp;</td>';
                   3843:                         }
                   3844:                     }
                   3845:                 }
                   3846:             } else {
                   3847: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3848:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3849: 		    my $value = &format_previous_attempt_value($key,
                   3850: 			            $returnhash{$version.':'.$key});
                   3851: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3852: 	        }
                   3853:             }
                   3854: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3855: 	 }
1.1       albertel 3856:       }
1.945     raeburn  3857:       my @currhidden = keys(%lasthidden);
1.596     albertel 3858:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3859:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3860:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3861:           if (%typeparts) {
                   3862:               my $hidden;
                   3863:               foreach my $id (@currhidden) {
                   3864:                   if ($key =~ /^\Q$id\E/) {
                   3865:                       $hidden = 1;
                   3866:                       last;
                   3867:                   }
                   3868:               }
                   3869:               if ($hidden) {
                   3870:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3871:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3872:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3873:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3874:                           $value = &$gradesub($value);
                   3875:                       }
                   3876:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3877:                   } else {
                   3878:                       $prevattempts.='<td>&nbsp;</td>';
                   3879:                   }
                   3880:               } else {
                   3881:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3882:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3883:                       $value = &$gradesub($value);
                   3884:                   }
                   3885:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3886:               }
                   3887:           } else {
                   3888: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3889: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3890:                   $value = &$gradesub($value);
                   3891:               }
                   3892: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3893:           }
1.16      harris41 3894:       }
1.596     albertel 3895:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3896:     } else {
1.596     albertel 3897:       $prevattempts=
                   3898: 	  &start_data_table().&start_data_table_row().
                   3899: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3900: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3901:     }
                   3902:   } else {
1.596     albertel 3903:     $prevattempts=
                   3904: 	  &start_data_table().&start_data_table_row().
                   3905: 	  '<td>'.&mt('No data.').'</td>'.
                   3906: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3907:   }
1.10      albertel 3908: }
                   3909: 
1.581     albertel 3910: sub format_previous_attempt_value {
                   3911:     my ($key,$value) = @_;
1.1011    www      3912:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3913: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3914:     } elsif (ref($value) eq 'ARRAY') {
                   3915: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3916:     } elsif ($key =~ /answerstring$/) {
                   3917:         my %answers = &Apache::lonnet::str2hash($value);
                   3918:         my @anskeys = sort(keys(%answers));
                   3919:         if (@anskeys == 1) {
                   3920:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3921:             if ($answer =~ m{\0}) {
                   3922:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3923:             }
                   3924:             my $tag_internal_answer_name = 'INTERNAL';
                   3925:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3926:                 $value = $answer; 
                   3927:             } else {
                   3928:                 $value = $anskeys[0].'='.$answer;
                   3929:             }
                   3930:         } else {
                   3931:             foreach my $ans (@anskeys) {
                   3932:                 my $answer = $answers{$ans};
1.1001    raeburn  3933:                 if ($answer =~ m{\0}) {
                   3934:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3935:                 }
                   3936:                 $value .=  $ans.'='.$answer.'<br />';;
                   3937:             } 
                   3938:         }
1.581     albertel 3939:     } else {
                   3940: 	$value = &unescape($value);
                   3941:     }
                   3942:     return $value;
                   3943: }
                   3944: 
                   3945: 
1.107     albertel 3946: sub relative_to_absolute {
                   3947:     my ($url,$output)=@_;
                   3948:     my $parser=HTML::TokeParser->new(\$output);
                   3949:     my $token;
                   3950:     my $thisdir=$url;
                   3951:     my @rlinks=();
                   3952:     while ($token=$parser->get_token) {
                   3953: 	if ($token->[0] eq 'S') {
                   3954: 	    if ($token->[1] eq 'a') {
                   3955: 		if ($token->[2]->{'href'}) {
                   3956: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3957: 		}
                   3958: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3959: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3960: 	    } elsif ($token->[1] eq 'base') {
                   3961: 		$thisdir=$token->[2]->{'href'};
                   3962: 	    }
                   3963: 	}
                   3964:     }
                   3965:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3966:     foreach my $link (@rlinks) {
1.726     raeburn  3967: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3968: 		($link=~/^\//) ||
                   3969: 		($link=~/^javascript:/i) ||
                   3970: 		($link=~/^mailto:/i) ||
                   3971: 		($link=~/^\#/)) {
                   3972: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3973: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3974: 	}
                   3975:     }
                   3976: # -------------------------------------------------- Deal with Applet codebases
                   3977:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3978:     return $output;
                   3979: }
                   3980: 
1.112     bowersj2 3981: =pod
                   3982: 
1.648     raeburn  3983: =item * &get_student_view()
1.112     bowersj2 3984: 
                   3985: show a snapshot of what student was looking at
                   3986: 
                   3987: =cut
                   3988: 
1.10      albertel 3989: sub get_student_view {
1.186     albertel 3990:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3991:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3992:   my (%form);
1.10      albertel 3993:   my @elements=('symb','courseid','domain','username');
                   3994:   foreach my $element (@elements) {
1.186     albertel 3995:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3996:   }
1.186     albertel 3997:   if (defined($moreenv)) {
                   3998:       %form=(%form,%{$moreenv});
                   3999:   }
1.236     albertel 4000:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4001:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4002:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4003:   $userview=~s/\<body[^\>]*\>//gi;
                   4004:   $userview=~s/\<\/body\>//gi;
                   4005:   $userview=~s/\<html\>//gi;
                   4006:   $userview=~s/\<\/html\>//gi;
                   4007:   $userview=~s/\<head\>//gi;
                   4008:   $userview=~s/\<\/head\>//gi;
                   4009:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4010:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4011:   if (wantarray) {
                   4012:      return ($userview,$response);
                   4013:   } else {
                   4014:      return $userview;
                   4015:   }
                   4016: }
                   4017: 
                   4018: sub get_student_view_with_retries {
                   4019:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4020: 
                   4021:     my $ok = 0;                 # True if we got a good response.
                   4022:     my $content;
                   4023:     my $response;
                   4024: 
                   4025:     # Try to get the student_view done. within the retries count:
                   4026:     
                   4027:     do {
                   4028:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4029:          $ok      = $response->is_success;
                   4030:          if (!$ok) {
                   4031:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4032:          }
                   4033:          $retries--;
                   4034:     } while (!$ok && ($retries > 0));
                   4035:     
                   4036:     if (!$ok) {
                   4037:        $content = '';          # On error return an empty content.
                   4038:     }
1.651     www      4039:     if (wantarray) {
                   4040:        return ($content, $response);
                   4041:     } else {
                   4042:        return $content;
                   4043:     }
1.11      albertel 4044: }
                   4045: 
1.112     bowersj2 4046: =pod
                   4047: 
1.648     raeburn  4048: =item * &get_student_answers() 
1.112     bowersj2 4049: 
                   4050: show a snapshot of how student was answering problem
                   4051: 
                   4052: =cut
                   4053: 
1.11      albertel 4054: sub get_student_answers {
1.100     sakharuk 4055:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4056:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4057:   my (%moreenv);
1.11      albertel 4058:   my @elements=('symb','courseid','domain','username');
                   4059:   foreach my $element (@elements) {
1.186     albertel 4060:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4061:   }
1.186     albertel 4062:   $moreenv{'grade_target'}='answer';
                   4063:   %moreenv=(%form,%moreenv);
1.497     raeburn  4064:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4065:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4066:   return $userview;
1.1       albertel 4067: }
1.116     albertel 4068: 
                   4069: =pod
                   4070: 
                   4071: =item * &submlink()
                   4072: 
1.242     albertel 4073: Inputs: $text $uname $udom $symb $target
1.116     albertel 4074: 
                   4075: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4076: 
                   4077: =cut
                   4078: 
                   4079: ###############################################
                   4080: sub submlink {
1.242     albertel 4081:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4082:     if (!($uname && $udom)) {
                   4083: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4084: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4085: 	if (!$symb) { $symb=$cursymb; }
                   4086:     }
1.254     matthew  4087:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4088:     $symb=&escape($symb);
1.960     bisitz   4089:     if ($target) { $target=" target=\"$target\""; }
                   4090:     return
                   4091:         '<a href="/adm/grades?command=submission'.
                   4092:         '&amp;symb='.$symb.
                   4093:         '&amp;student='.$uname.
                   4094:         '&amp;userdom='.$udom.'"'.
                   4095:         $target.'>'.$text.'</a>';
1.242     albertel 4096: }
                   4097: ##############################################
                   4098: 
                   4099: =pod
                   4100: 
                   4101: =item * &pgrdlink()
                   4102: 
                   4103: Inputs: $text $uname $udom $symb $target
                   4104: 
                   4105: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4106: 
                   4107: =cut
                   4108: 
                   4109: ###############################################
                   4110: sub pgrdlink {
                   4111:     my $link=&submlink(@_);
                   4112:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4113:     return $link;
                   4114: }
                   4115: ##############################################
                   4116: 
                   4117: =pod
                   4118: 
                   4119: =item * &pprmlink()
                   4120: 
                   4121: Inputs: $text $uname $udom $symb $target
                   4122: 
                   4123: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4124: student and a specific resource
1.242     albertel 4125: 
                   4126: =cut
                   4127: 
                   4128: ###############################################
                   4129: sub pprmlink {
                   4130:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4131:     if (!($uname && $udom)) {
                   4132: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4133: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4134: 	if (!$symb) { $symb=$cursymb; }
                   4135:     }
1.254     matthew  4136:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4137:     $symb=&escape($symb);
1.242     albertel 4138:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4139:     return '<a href="/adm/parmset?command=set&amp;'.
                   4140: 	'symb='.$symb.'&amp;uname='.$uname.
                   4141: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4142: }
                   4143: ##############################################
1.37      matthew  4144: 
1.112     bowersj2 4145: =pod
                   4146: 
                   4147: =back
                   4148: 
                   4149: =cut
                   4150: 
1.37      matthew  4151: ###############################################
1.51      www      4152: 
                   4153: 
                   4154: sub timehash {
1.687     raeburn  4155:     my ($thistime) = @_;
                   4156:     my $timezone = &Apache::lonlocal::gettimezone();
                   4157:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4158:                      ->set_time_zone($timezone);
                   4159:     my $wday = $dt->day_of_week();
                   4160:     if ($wday == 7) { $wday = 0; }
                   4161:     return ( 'second' => $dt->second(),
                   4162:              'minute' => $dt->minute(),
                   4163:              'hour'   => $dt->hour(),
                   4164:              'day'     => $dt->day_of_month(),
                   4165:              'month'   => $dt->month(),
                   4166:              'year'    => $dt->year(),
                   4167:              'weekday' => $wday,
                   4168:              'dayyear' => $dt->day_of_year(),
                   4169:              'dlsav'   => $dt->is_dst() );
1.51      www      4170: }
                   4171: 
1.370     www      4172: sub utc_string {
                   4173:     my ($date)=@_;
1.371     www      4174:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4175: }
                   4176: 
1.51      www      4177: sub maketime {
                   4178:     my %th=@_;
1.687     raeburn  4179:     my ($epoch_time,$timezone,$dt);
                   4180:     $timezone = &Apache::lonlocal::gettimezone();
                   4181:     eval {
                   4182:         $dt = DateTime->new( year   => $th{'year'},
                   4183:                              month  => $th{'month'},
                   4184:                              day    => $th{'day'},
                   4185:                              hour   => $th{'hour'},
                   4186:                              minute => $th{'minute'},
                   4187:                              second => $th{'second'},
                   4188:                              time_zone => $timezone,
                   4189:                          );
                   4190:     };
                   4191:     if (!$@) {
                   4192:         $epoch_time = $dt->epoch;
                   4193:         if ($epoch_time) {
                   4194:             return $epoch_time;
                   4195:         }
                   4196:     }
1.51      www      4197:     return POSIX::mktime(
                   4198:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4199:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4200: }
                   4201: 
                   4202: #########################################
1.51      www      4203: 
                   4204: sub findallcourses {
1.482     raeburn  4205:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4206:     my %roles;
                   4207:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4208:     my %courses;
1.51      www      4209:     my $now=time;
1.482     raeburn  4210:     if (!defined($uname)) {
                   4211:         $uname = $env{'user.name'};
                   4212:     }
                   4213:     if (!defined($udom)) {
                   4214:         $udom = $env{'user.domain'};
                   4215:     }
                   4216:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4217:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4218:         if (!%roles) {
                   4219:             %roles = (
                   4220:                        cc => 1,
1.907     raeburn  4221:                        co => 1,
1.482     raeburn  4222:                        in => 1,
                   4223:                        ep => 1,
                   4224:                        ta => 1,
                   4225:                        cr => 1,
                   4226:                        st => 1,
                   4227:              );
                   4228:         }
                   4229:         foreach my $entry (keys(%roleshash)) {
                   4230:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4231:             if ($trole =~ /^cr/) { 
                   4232:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4233:             } else {
                   4234:                 next if (!exists($roles{$trole}));
                   4235:             }
                   4236:             if ($tend) {
                   4237:                 next if ($tend < $now);
                   4238:             }
                   4239:             if ($tstart) {
                   4240:                 next if ($tstart > $now);
                   4241:             }
1.1058    raeburn  4242:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4243:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4244:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4245:             if ($secpart eq '') {
                   4246:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4247:                 $sec = 'none';
1.1058    raeburn  4248:                 $value .= $cnum.'/';
1.482     raeburn  4249:             } else {
                   4250:                 $cnum = $cnumpart;
                   4251:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4252:                 $value .= $cnum.'/'.$sec;
                   4253:             }
                   4254:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4255:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4256:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4257:                 }
                   4258:             } else {
                   4259:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4260:             }
1.482     raeburn  4261:         }
                   4262:     } else {
                   4263:         foreach my $key (keys(%env)) {
1.483     albertel 4264: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4265:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4266: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4267: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4268: 	        next if (%roles && !exists($roles{$role}));
                   4269: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4270:                 my $active=1;
                   4271:                 if ($starttime) {
                   4272: 		    if ($now<$starttime) { $active=0; }
                   4273:                 }
                   4274:                 if ($endtime) {
                   4275:                     if ($now>$endtime) { $active=0; }
                   4276:                 }
                   4277:                 if ($active) {
1.1058    raeburn  4278:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4279:                     if ($sec eq '') {
                   4280:                         $sec = 'none';
1.1058    raeburn  4281:                     } else {
                   4282:                         $value .= $sec;
                   4283:                     }
                   4284:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4285:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4286:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4287:                         }
                   4288:                     } else {
                   4289:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4290:                     }
1.474     raeburn  4291:                 }
                   4292:             }
1.51      www      4293:         }
                   4294:     }
1.474     raeburn  4295:     return %courses;
1.51      www      4296: }
1.37      matthew  4297: 
1.54      www      4298: ###############################################
1.474     raeburn  4299: 
                   4300: sub blockcheck {
1.1062    raeburn  4301:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4302: 
                   4303:     if (!defined($udom)) {
                   4304:         $udom = $env{'user.domain'};
                   4305:     }
                   4306:     if (!defined($uname)) {
                   4307:         $uname = $env{'user.name'};
                   4308:     }
                   4309: 
                   4310:     # If uname and udom are for a course, check for blocks in the course.
                   4311: 
                   4312:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4313:         my ($startblock,$endblock,$triggerblock) = 
                   4314:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4315:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4316:     }
1.474     raeburn  4317: 
1.502     raeburn  4318:     my $startblock = 0;
                   4319:     my $endblock = 0;
1.1062    raeburn  4320:     my $triggerblock = '';
1.482     raeburn  4321:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4322: 
1.490     raeburn  4323:     # If uname is for a user, and activity is course-specific, i.e.,
                   4324:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4325: 
1.490     raeburn  4326:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4327:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4328:         foreach my $key (keys(%live_courses)) {
                   4329:             if ($key ne $env{'request.course.id'}) {
                   4330:                 delete($live_courses{$key});
                   4331:             }
                   4332:         }
                   4333:     }
                   4334: 
                   4335:     my $otheruser = 0;
                   4336:     my %own_courses;
                   4337:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4338:         # Resource belongs to user other than current user.
                   4339:         $otheruser = 1;
                   4340:         # Gather courses for current user
                   4341:         %own_courses = 
                   4342:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4343:     }
                   4344: 
                   4345:     # Gather active course roles - course coordinator, instructor, 
                   4346:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4347: 
                   4348:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4349:         my ($cdom,$cnum);
                   4350:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4351:             $cdom = $env{'course.'.$course.'.domain'};
                   4352:             $cnum = $env{'course.'.$course.'.num'};
                   4353:         } else {
1.490     raeburn  4354:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4355:         }
                   4356:         my $no_ownblock = 0;
                   4357:         my $no_userblock = 0;
1.533     raeburn  4358:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4359:             # Check if current user has 'evb' priv for this
                   4360:             if (defined($own_courses{$course})) {
                   4361:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4362:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4363:                     if ($sec ne 'none') {
                   4364:                         $checkrole .= '/'.$sec;
                   4365:                     }
                   4366:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4367:                         $no_ownblock = 1;
                   4368:                         last;
                   4369:                     }
                   4370:                 }
                   4371:             }
                   4372:             # if they have 'evb' priv and are currently not playing student
                   4373:             next if (($no_ownblock) &&
                   4374:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4375:         }
1.474     raeburn  4376:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4377:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4378:             if ($sec ne 'none') {
1.482     raeburn  4379:                 $checkrole .= '/'.$sec;
1.474     raeburn  4380:             }
1.490     raeburn  4381:             if ($otheruser) {
                   4382:                 # Resource belongs to user other than current user.
                   4383:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4384:                 my (%allroles,%userroles);
                   4385:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4386:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4387:                         my ($trole,$tdom,$tnum,$tsec);
                   4388:                         if ($entry =~ /^cr/) {
                   4389:                             ($trole,$tdom,$tnum,$tsec) = 
                   4390:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4391:                         } else {
                   4392:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4393:                         }
                   4394:                         my ($spec,$area,$trest);
                   4395:                         $area = '/'.$tdom.'/'.$tnum;
                   4396:                         $trest = $tnum;
                   4397:                         if ($tsec ne '') {
                   4398:                             $area .= '/'.$tsec;
                   4399:                             $trest .= '/'.$tsec;
                   4400:                         }
                   4401:                         $spec = $trole.'.'.$area;
                   4402:                         if ($trole =~ /^cr/) {
                   4403:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4404:                                                               $tdom,$spec,$trest,$area);
                   4405:                         } else {
                   4406:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4407:                                                                 $tdom,$spec,$trest,$area);
                   4408:                         }
                   4409:                     }
                   4410:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4411:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4412:                         if ($1) {
                   4413:                             $no_userblock = 1;
                   4414:                             last;
                   4415:                         }
1.486     raeburn  4416:                     }
                   4417:                 }
1.490     raeburn  4418:             } else {
                   4419:                 # Resource belongs to current user
                   4420:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4421:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4422:                     $no_ownblock = 1;
                   4423:                     last;
                   4424:                 }
1.474     raeburn  4425:             }
                   4426:         }
                   4427:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4428:         next if (($no_ownblock) &&
1.491     albertel 4429:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4430:         next if ($no_userblock);
1.474     raeburn  4431: 
1.866     kalberla 4432:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4433:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4434:         
1.1062    raeburn  4435:         my ($start,$end,$trigger) = 
                   4436:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4437:         if (($start != 0) && 
                   4438:             (($startblock == 0) || ($startblock > $start))) {
                   4439:             $startblock = $start;
1.1062    raeburn  4440:             if ($trigger ne '') {
                   4441:                 $triggerblock = $trigger;
                   4442:             }
1.502     raeburn  4443:         }
                   4444:         if (($end != 0)  &&
                   4445:             (($endblock == 0) || ($endblock < $end))) {
                   4446:             $endblock = $end;
1.1062    raeburn  4447:             if ($trigger ne '') {
                   4448:                 $triggerblock = $trigger;
                   4449:             }
1.502     raeburn  4450:         }
1.490     raeburn  4451:     }
1.1062    raeburn  4452:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4453: }
                   4454: 
                   4455: sub get_blocks {
1.1062    raeburn  4456:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4457:     my $startblock = 0;
                   4458:     my $endblock = 0;
1.1062    raeburn  4459:     my $triggerblock = '';
1.490     raeburn  4460:     my $course = $cdom.'_'.$cnum;
                   4461:     $setters->{$course} = {};
                   4462:     $setters->{$course}{'staff'} = [];
                   4463:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4464:     $setters->{$course}{'triggers'} = [];
                   4465:     my (@blockers,%triggered);
                   4466:     my $now = time;
                   4467:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4468:     if ($activity eq 'docs') {
                   4469:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4470:         foreach my $block (@blockers) {
                   4471:             if ($block =~ /^firstaccess____(.+)$/) {
                   4472:                 my $item = $1;
                   4473:                 my $type = 'map';
                   4474:                 my $timersymb = $item;
                   4475:                 if ($item eq 'course') {
                   4476:                     $type = 'course';
                   4477:                 } elsif ($item =~ /___\d+___/) {
                   4478:                     $type = 'resource';
                   4479:                 } else {
                   4480:                     $timersymb = &Apache::lonnet::symbread($item);
                   4481:                 }
                   4482:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4483:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4484:                 $triggered{$block} = {
                   4485:                                        start => $start,
                   4486:                                        end   => $end,
                   4487:                                        type  => $type,
                   4488:                                      };
                   4489:             }
                   4490:         }
                   4491:     } else {
                   4492:         foreach my $block (keys(%commblocks)) {
                   4493:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4494:                 my ($start,$end) = ($1,$2);
                   4495:                 if ($start <= time && $end >= time) {
                   4496:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4497:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4498:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4499:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4500:                                     push(@blockers,$block);
                   4501:                                 }
                   4502:                             }
                   4503:                         }
                   4504:                     }
                   4505:                 }
                   4506:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4507:                 my $item = $1;
                   4508:                 my $timersymb = $item; 
                   4509:                 my $type = 'map';
                   4510:                 if ($item eq 'course') {
                   4511:                     $type = 'course';
                   4512:                 } elsif ($item =~ /___\d+___/) {
                   4513:                     $type = 'resource';
                   4514:                 } else {
                   4515:                     $timersymb = &Apache::lonnet::symbread($item);
                   4516:                 }
                   4517:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4518:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4519:                 if ($start && $end) {
                   4520:                     if (($start <= time) && ($end >= time)) {
                   4521:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4522:                             push(@blockers,$block);
                   4523:                             $triggered{$block} = {
                   4524:                                                    start => $start,
                   4525:                                                    end   => $end,
                   4526:                                                    type  => $type,
                   4527:                                                  };
                   4528:                         }
                   4529:                     }
1.490     raeburn  4530:                 }
1.1062    raeburn  4531:             }
                   4532:         }
                   4533:     }
                   4534:     foreach my $blocker (@blockers) {
                   4535:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4536:             &parse_block_record($commblocks{$blocker});
                   4537:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4538:         my ($start,$end,$triggertype);
                   4539:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4540:             ($start,$end) = ($1,$2);
                   4541:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4542:             $start = $triggered{$blocker}{'start'};
                   4543:             $end = $triggered{$blocker}{'end'};
                   4544:             $triggertype = $triggered{$blocker}{'type'};
                   4545:         }
                   4546:         if ($start) {
                   4547:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4548:             if ($triggertype) {
                   4549:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4550:             } else {
                   4551:                 push(@{$$setters{$course}{'triggers'}},0);
                   4552:             }
                   4553:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4554:                 $startblock = $start;
                   4555:                 if ($triggertype) {
                   4556:                     $triggerblock = $blocker;
1.474     raeburn  4557:                 }
                   4558:             }
1.1062    raeburn  4559:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4560:                $endblock = $end;
                   4561:                if ($triggertype) {
                   4562:                    $triggerblock = $blocker;
                   4563:                }
                   4564:             }
1.474     raeburn  4565:         }
                   4566:     }
1.1062    raeburn  4567:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4568: }
                   4569: 
                   4570: sub parse_block_record {
                   4571:     my ($record) = @_;
                   4572:     my ($setuname,$setudom,$title,$blocks);
                   4573:     if (ref($record) eq 'HASH') {
                   4574:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4575:         $title = &unescape($record->{'event'});
                   4576:         $blocks = $record->{'blocks'};
                   4577:     } else {
                   4578:         my @data = split(/:/,$record,3);
                   4579:         if (scalar(@data) eq 2) {
                   4580:             $title = $data[1];
                   4581:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4582:         } else {
                   4583:             ($setuname,$setudom,$title) = @data;
                   4584:         }
                   4585:         $blocks = { 'com' => 'on' };
                   4586:     }
                   4587:     return ($setuname,$setudom,$title,$blocks);
                   4588: }
                   4589: 
1.854     kalberla 4590: sub blocking_status {
1.1062    raeburn  4591:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4592:     my %setters;
1.890     droeschl 4593: 
1.1061    raeburn  4594: # check for active blocking
1.1062    raeburn  4595:     my ($startblock,$endblock,$triggerblock) = 
                   4596:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4597:     my $blocked = 0;
                   4598:     if ($startblock && $endblock) {
                   4599:         $blocked = 1;
                   4600:     }
1.890     droeschl 4601: 
1.1061    raeburn  4602: # caller just wants to know whether a block is active
                   4603:     if (!wantarray) { return $blocked; }
                   4604: 
                   4605: # build a link to a popup window containing the details
                   4606:     my $querystring  = "?activity=$activity";
                   4607: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4608:     if ($activity eq 'port') {
                   4609:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4610:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4611:     } elsif ($activity eq 'docs') {
                   4612:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4613:     }
1.1061    raeburn  4614: 
                   4615:     my $output .= <<'END_MYBLOCK';
                   4616: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4617:     var options = "width=" + w + ",height=" + h + ",";
                   4618:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4619:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4620:     var newWin = window.open(url, wdwName, options);
                   4621:     newWin.focus();
                   4622: }
1.890     droeschl 4623: END_MYBLOCK
1.854     kalberla 4624: 
1.1061    raeburn  4625:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4626:   
1.1061    raeburn  4627:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4628:     my $text = &mt('Communication Blocked');
                   4629:     if ($activity eq 'docs') {
                   4630:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4631:     } elsif ($activity eq 'printout') {
                   4632:         $text = &mt('Printing Blocked');
1.1062    raeburn  4633:     }
1.1061    raeburn  4634:     $output .= <<"END_BLOCK";
1.867     kalberla 4635: <div class='LC_comblock'>
1.869     kalberla 4636:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4637:   title='$text'>
                   4638:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4639:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4640:   title='$text'>$text</a>
1.867     kalberla 4641: </div>
                   4642: 
                   4643: END_BLOCK
1.474     raeburn  4644: 
1.1061    raeburn  4645:     return ($blocked, $output);
1.854     kalberla 4646: }
1.490     raeburn  4647: 
1.60      matthew  4648: ###############################################
                   4649: 
1.682     raeburn  4650: sub check_ip_acc {
                   4651:     my ($acc)=@_;
                   4652:     &Apache::lonxml::debug("acc is $acc");
                   4653:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4654:         return 1;
                   4655:     }
                   4656:     my $allowed=0;
                   4657:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4658: 
                   4659:     my $name;
                   4660:     foreach my $pattern (split(',',$acc)) {
                   4661:         $pattern =~ s/^\s*//;
                   4662:         $pattern =~ s/\s*$//;
                   4663:         if ($pattern =~ /\*$/) {
                   4664:             #35.8.*
                   4665:             $pattern=~s/\*//;
                   4666:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4667:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4668:             #35.8.3.[34-56]
                   4669:             my $low=$2;
                   4670:             my $high=$3;
                   4671:             $pattern=$1;
                   4672:             if ($ip =~ /^\Q$pattern\E/) {
                   4673:                 my $last=(split(/\./,$ip))[3];
                   4674:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4675:             }
                   4676:         } elsif ($pattern =~ /^\*/) {
                   4677:             #*.msu.edu
                   4678:             $pattern=~s/\*//;
                   4679:             if (!defined($name)) {
                   4680:                 use Socket;
                   4681:                 my $netaddr=inet_aton($ip);
                   4682:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4683:             }
                   4684:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4685:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4686:             #127.0.0.1
                   4687:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4688:         } else {
                   4689:             #some.name.com
                   4690:             if (!defined($name)) {
                   4691:                 use Socket;
                   4692:                 my $netaddr=inet_aton($ip);
                   4693:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4694:             }
                   4695:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4696:         }
                   4697:         if ($allowed) { last; }
                   4698:     }
                   4699:     return $allowed;
                   4700: }
                   4701: 
                   4702: ###############################################
                   4703: 
1.60      matthew  4704: =pod
                   4705: 
1.112     bowersj2 4706: =head1 Domain Template Functions
                   4707: 
                   4708: =over 4
                   4709: 
                   4710: =item * &determinedomain()
1.60      matthew  4711: 
                   4712: Inputs: $domain (usually will be undef)
                   4713: 
1.63      www      4714: Returns: Determines which domain should be used for designs
1.60      matthew  4715: 
                   4716: =cut
1.54      www      4717: 
1.60      matthew  4718: ###############################################
1.63      www      4719: sub determinedomain {
                   4720:     my $domain=shift;
1.531     albertel 4721:     if (! $domain) {
1.60      matthew  4722:         # Determine domain if we have not been given one
1.893     raeburn  4723:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4724:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4725:         if ($env{'request.role.domain'}) { 
                   4726:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4727:         }
                   4728:     }
1.63      www      4729:     return $domain;
                   4730: }
                   4731: ###############################################
1.517     raeburn  4732: 
1.518     albertel 4733: sub devalidate_domconfig_cache {
                   4734:     my ($udom)=@_;
                   4735:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4736: }
                   4737: 
                   4738: # ---------------------- Get domain configuration for a domain
                   4739: sub get_domainconf {
                   4740:     my ($udom) = @_;
                   4741:     my $cachetime=1800;
                   4742:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4743:     if (defined($cached)) { return %{$result}; }
                   4744: 
                   4745:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4746: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4747:     my (%designhash,%legacy);
1.518     albertel 4748:     if (keys(%domconfig) > 0) {
                   4749:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4750:             if (keys(%{$domconfig{'login'}})) {
                   4751:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4752:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4753:                         if ($key eq 'loginvia') {
                   4754:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4755:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4756:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4757:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4758:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4759:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4760:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4761: 
                   4762:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4763:                                             } else {
1.1013    raeburn  4764:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4765:                                             }
                   4766:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4767:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4768:                                             }
1.946     raeburn  4769:                                         }
                   4770:                                     }
                   4771:                                 }
                   4772:                             }
                   4773:                         } else {
                   4774:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4775:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4776:                                     $domconfig{'login'}{$key}{$img};
                   4777:                             }
1.699     raeburn  4778:                         }
                   4779:                     } else {
                   4780:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4781:                     }
1.632     raeburn  4782:                 }
                   4783:             } else {
                   4784:                 $legacy{'login'} = 1;
1.518     albertel 4785:             }
1.632     raeburn  4786:         } else {
                   4787:             $legacy{'login'} = 1;
1.518     albertel 4788:         }
                   4789:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4790:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4791:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4792:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4793:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4794:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4795:                         }
1.518     albertel 4796:                     }
                   4797:                 }
1.632     raeburn  4798:             } else {
                   4799:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4800:             }
1.632     raeburn  4801:         } else {
                   4802:             $legacy{'rolecolors'} = 1;
1.518     albertel 4803:         }
1.948     raeburn  4804:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4805:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4806:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4807:             }
                   4808:         }
1.632     raeburn  4809:         if (keys(%legacy) > 0) {
                   4810:             my %legacyhash = &get_legacy_domconf($udom);
                   4811:             foreach my $item (keys(%legacyhash)) {
                   4812:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4813:                     if ($legacy{'login'}) { 
                   4814:                         $designhash{$item} = $legacyhash{$item};
                   4815:                     }
                   4816:                 } else {
                   4817:                     if ($legacy{'rolecolors'}) {
                   4818:                         $designhash{$item} = $legacyhash{$item};
                   4819:                     }
1.518     albertel 4820:                 }
                   4821:             }
                   4822:         }
1.632     raeburn  4823:     } else {
                   4824:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4825:     }
                   4826:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4827: 				  $cachetime);
                   4828:     return %designhash;
                   4829: }
                   4830: 
1.632     raeburn  4831: sub get_legacy_domconf {
                   4832:     my ($udom) = @_;
                   4833:     my %legacyhash;
                   4834:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4835:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4836:     if (-e $designfile) {
                   4837:         if ( open (my $fh,"<$designfile") ) {
                   4838:             while (my $line = <$fh>) {
                   4839:                 next if ($line =~ /^\#/);
                   4840:                 chomp($line);
                   4841:                 my ($key,$val)=(split(/\=/,$line));
                   4842:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4843:             }
                   4844:             close($fh);
                   4845:         }
                   4846:     }
1.1026    raeburn  4847:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4848:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4849:     }
                   4850:     return %legacyhash;
                   4851: }
                   4852: 
1.63      www      4853: =pod
                   4854: 
1.112     bowersj2 4855: =item * &domainlogo()
1.63      www      4856: 
                   4857: Inputs: $domain (usually will be undef)
                   4858: 
                   4859: Returns: A link to a domain logo, if the domain logo exists.
                   4860: If the domain logo does not exist, a description of the domain.
                   4861: 
                   4862: =cut
1.112     bowersj2 4863: 
1.63      www      4864: ###############################################
                   4865: sub domainlogo {
1.517     raeburn  4866:     my $domain = &determinedomain(shift);
1.518     albertel 4867:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4868:     # See if there is a logo
                   4869:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4870:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4871:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4872: 	    if ($imgsrc =~ m{^/res/}) {
                   4873: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4874: 		&Apache::lonnet::repcopy($local_name);
                   4875: 	    }
                   4876: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4877:         } 
                   4878:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4879:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4880:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4881:     } else {
1.60      matthew  4882:         return '';
1.59      www      4883:     }
                   4884: }
1.63      www      4885: ##############################################
                   4886: 
                   4887: =pod
                   4888: 
1.112     bowersj2 4889: =item * &designparm()
1.63      www      4890: 
                   4891: Inputs: $which parameter; $domain (usually will be undef)
                   4892: 
                   4893: Returns: value of designparamter $which
                   4894: 
                   4895: =cut
1.112     bowersj2 4896: 
1.397     albertel 4897: 
1.400     albertel 4898: ##############################################
1.397     albertel 4899: sub designparm {
                   4900:     my ($which,$domain)=@_;
                   4901:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4902:         return $env{'environment.color.'.$which};
1.96      www      4903:     }
1.63      www      4904:     $domain=&determinedomain($domain);
1.1016    raeburn  4905:     my %domdesign;
                   4906:     unless ($domain eq 'public') {
                   4907:         %domdesign = &get_domainconf($domain);
                   4908:     }
1.520     raeburn  4909:     my $output;
1.517     raeburn  4910:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4911:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4912:     } else {
1.520     raeburn  4913:         $output = $defaultdesign{$which};
                   4914:     }
                   4915:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4916:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4917:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4918:             if ($output =~ m{^/res/}) {
                   4919:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4920:                 &Apache::lonnet::repcopy($local_name);
                   4921:             }
1.520     raeburn  4922:             $output = &lonhttpdurl($output);
                   4923:         }
1.63      www      4924:     }
1.520     raeburn  4925:     return $output;
1.63      www      4926: }
1.59      www      4927: 
1.822     bisitz   4928: ##############################################
                   4929: =pod
                   4930: 
1.832     bisitz   4931: =item * &authorspace()
                   4932: 
1.1028    raeburn  4933: Inputs: $url (usually will be undef).
1.832     bisitz   4934: 
1.1028    raeburn  4935: Returns: Path to Construction Space containing the resource or 
                   4936:          directory being viewed (or for which action is being taken). 
                   4937:          If $url is provided, and begins /priv/<domain>/<uname>
                   4938:          the path will be that portion of the $context argument.
                   4939:          Otherwise the path will be for the author space of the current
                   4940:          user when the current role is author, or for that of the 
                   4941:          co-author/assistant co-author space when the current role 
                   4942:          is co-author or assistant co-author.
1.832     bisitz   4943: 
                   4944: =cut
                   4945: 
                   4946: sub authorspace {
1.1028    raeburn  4947:     my ($url) = @_;
                   4948:     if ($url ne '') {
                   4949:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4950:            return $1;
                   4951:         }
                   4952:     }
1.832     bisitz   4953:     my $caname = '';
1.1024    www      4954:     my $cadom = '';
1.1028    raeburn  4955:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4956:         ($cadom,$caname) =
1.832     bisitz   4957:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4958:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4959:         $caname = $env{'user.name'};
1.1024    www      4960:         $cadom = $env{'user.domain'};
1.832     bisitz   4961:     }
1.1028    raeburn  4962:     if (($caname ne '') && ($cadom ne '')) {
                   4963:         return "/priv/$cadom/$caname/";
                   4964:     }
                   4965:     return;
1.832     bisitz   4966: }
                   4967: 
                   4968: ##############################################
                   4969: =pod
                   4970: 
1.822     bisitz   4971: =item * &head_subbox()
                   4972: 
                   4973: Inputs: $content (contains HTML code with page functions, etc.)
                   4974: 
                   4975: Returns: HTML div with $content
                   4976:          To be included in page header
                   4977: 
                   4978: =cut
                   4979: 
                   4980: sub head_subbox {
                   4981:     my ($content)=@_;
                   4982:     my $output =
1.993     raeburn  4983:         '<div class="LC_head_subbox">'
1.822     bisitz   4984:        .$content
                   4985:        .'</div>'
                   4986: }
                   4987: 
                   4988: ##############################################
                   4989: =pod
                   4990: 
                   4991: =item * &CSTR_pageheader()
                   4992: 
1.1026    raeburn  4993: Input: (optional) filename from which breadcrumb trail is built.
                   4994:        In most cases no input as needed, as $env{'request.filename'}
                   4995:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4996: 
                   4997: Returns: HTML div with CSTR path and recent box
                   4998:          To be included on Construction Space pages
                   4999: 
                   5000: =cut
                   5001: 
                   5002: sub CSTR_pageheader {
1.1026    raeburn  5003:     my ($trailfile) = @_;
                   5004:     if ($trailfile eq '') {
                   5005:         $trailfile = $env{'request.filename'};
                   5006:     }
                   5007: 
                   5008: # this is for resources; directories have customtitle, and crumbs
                   5009: # and select recent are created in lonpubdir.pm
                   5010: 
                   5011:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5012:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5013:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5014:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5015:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5016: 
                   5017:     my $parentpath = '';
                   5018:     my $lastitem = '';
                   5019:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5020:         $parentpath = $1;
                   5021:         $lastitem = $2;
                   5022:     } else {
                   5023:         $lastitem = $thisdisfn;
                   5024:     }
1.921     bisitz   5025: 
                   5026:     my $output =
1.822     bisitz   5027:          '<div>'
                   5028:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
                   5029:         .'<b>'.&mt('Construction Space:').'</b> '
                   5030:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5031:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5032:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5033: 
                   5034:     if ($lastitem) {
                   5035:         $output .=
                   5036:              '<span class="LC_filename">'
                   5037:             .$lastitem
                   5038:             .'</span>';
                   5039:     }
                   5040:     $output .=
                   5041:          '<br />'
1.822     bisitz   5042:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5043:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5044:         .'</form>'
                   5045:         .&Apache::lonmenu::constspaceform()
                   5046:         .'</div>';
1.921     bisitz   5047: 
                   5048:     return $output;
1.822     bisitz   5049: }
                   5050: 
1.60      matthew  5051: ###############################################
                   5052: ###############################################
                   5053: 
                   5054: =pod
                   5055: 
1.112     bowersj2 5056: =back
                   5057: 
1.549     albertel 5058: =head1 HTML Helpers
1.112     bowersj2 5059: 
                   5060: =over 4
                   5061: 
                   5062: =item * &bodytag()
1.60      matthew  5063: 
                   5064: Returns a uniform header for LON-CAPA web pages.
                   5065: 
                   5066: Inputs: 
                   5067: 
1.112     bowersj2 5068: =over 4
                   5069: 
                   5070: =item * $title, A title to be displayed on the page.
                   5071: 
                   5072: =item * $function, the current role (can be undef).
                   5073: 
                   5074: =item * $addentries, extra parameters for the <body> tag.
                   5075: 
                   5076: =item * $bodyonly, if defined, only return the <body> tag.
                   5077: 
                   5078: =item * $domain, if defined, force a given domain.
                   5079: 
                   5080: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5081:             text interface only)
1.60      matthew  5082: 
1.814     bisitz   5083: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5084:                      navigational links
1.317     albertel 5085: 
1.338     albertel 5086: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5087: 
1.460     albertel 5088: =item * $args, optional argument valid values are
                   5089:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5090:             inherit_jsmath -> when creating popup window in a page,
                   5091:                               should it have jsmath forced on by the
                   5092:                               current page
1.460     albertel 5093: 
1.1096    raeburn  5094: =item * $advtoolsref, optional argument, ref to an array containing
                   5095:             inlineremote items to be added in "Functions" menu below
                   5096:             breadcrumbs.
                   5097: 
1.112     bowersj2 5098: =back
                   5099: 
1.60      matthew  5100: Returns: A uniform header for LON-CAPA web pages.  
                   5101: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5102: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5103: other decorations will be returned.
                   5104: 
                   5105: =cut
                   5106: 
1.54      www      5107: sub bodytag {
1.831     bisitz   5108:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5109:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5110: 
1.954     raeburn  5111:     my $public;
                   5112:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5113:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5114:         $public = 1;
                   5115:     }
1.460     albertel 5116:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 5117: 
1.183     matthew  5118:     $function = &get_users_function() if (!$function);
1.339     albertel 5119:     my $img =    &designparm($function.'.img',$domain);
                   5120:     my $font =   &designparm($function.'.font',$domain);
                   5121:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5122: 
1.803     bisitz   5123:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5124: 		   'bgcolor' => $pgbg,
1.339     albertel 5125: 		   'text'    => $font,
                   5126:                    'alink'   => &designparm($function.'.alink',$domain),
                   5127: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5128: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5129:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5130: 
1.63      www      5131:  # role and realm
1.378     raeburn  5132:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5133:     if ($role  eq 'ca') {
1.479     albertel 5134:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5135:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5136:     } 
1.55      www      5137: # realm
1.258     albertel 5138:     if ($env{'request.course.id'}) {
1.378     raeburn  5139:         if ($env{'request.role'} !~ /^cr/) {
                   5140:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5141:         }
1.898     raeburn  5142:         if ($env{'request.course.sec'}) {
                   5143:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5144:         }   
1.359     albertel 5145: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5146:     } else {
                   5147:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5148:     }
1.433     albertel 5149: 
1.359     albertel 5150:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5151: 
1.438     albertel 5152:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5153: 
1.101     www      5154: # construct main body tag
1.359     albertel 5155:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5156: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5157: 
1.530     albertel 5158:     if ($bodyonly) {
1.60      matthew  5159:         return $bodytag;
1.798     tempelho 5160:     } 
1.359     albertel 5161: 
1.410     albertel 5162:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.954     raeburn  5163:     if ($public) {
1.433     albertel 5164: 	undef($role);
1.434     albertel 5165:     } else {
1.1070    raeburn  5166: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5167:                                 undef,'LC_menubuttons_link');
1.433     albertel 5168:     }
1.359     albertel 5169:     
1.762     bisitz   5170:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5171:     #
                   5172:     # Extra info if you are the DC
                   5173:     my $dc_info = '';
                   5174:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5175:                         $env{'course.'.$env{'request.course.id'}.
                   5176:                                  '.domain'}.'/'})) {
                   5177:         my $cid = $env{'request.course.id'};
1.917     raeburn  5178:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5179:         $dc_info =~ s/\s+$//;
1.359     albertel 5180:     }
                   5181: 
1.898     raeburn  5182:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5183:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5184: 
1.916     droeschl 5185:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
                   5186:             return $bodytag; 
                   5187:         } 
1.903     droeschl 5188: 
                   5189:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5190: 
                   5191:         #    if ($env{'request.state'} eq 'construct') {
                   5192:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5193:         #    }
                   5194: 
1.359     albertel 5195: 
                   5196: 
1.916     droeschl 5197:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5198:              if ($dc_info) {
                   5199:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5200:              }
1.916     droeschl 5201:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
                   5202:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5203:             return $bodytag;
                   5204:         }
1.894     droeschl 5205: 
1.927     raeburn  5206:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   5207:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
                   5208:         }
1.916     droeschl 5209: 
1.903     droeschl 5210:         $bodytag .= Apache::lonhtmlcommon::scripttag(
                   5211:             Apache::lonmenu::utilityfunctions(), 'start');
1.816     bisitz   5212: 
1.903     droeschl 5213:         $bodytag .= Apache::lonmenu::primary_menu();
1.852     droeschl 5214: 
1.917     raeburn  5215:         if ($dc_info) {
                   5216:             $dc_info = &dc_courseid_toggle($dc_info);
                   5217:         }
                   5218:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5219: 
1.903     droeschl 5220:         #don't show menus for public users
1.954     raeburn  5221:         if (!$public){
1.903     droeschl 5222:             $bodytag .= Apache::lonmenu::secondary_menu();
                   5223:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5224:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5225:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5226:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5227:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5228:             } elsif ($forcereg) {
                   5229:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5230:                                                             $args->{'group'});
                   5231:             } else {
                   5232:                 $bodytag .= 
                   5233:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5234:                                                         $forcereg,$args->{'group'},
                   5235:                                                         $args->{'bread_crumbs'},
                   5236:                                                         $advtoolsref);
1.920     raeburn  5237:             }
1.903     droeschl 5238:         }else{
                   5239:             # this is to seperate menu from content when there's no secondary
                   5240:             # menu. Especially needed for public accessible ressources.
                   5241:             $bodytag .= '<hr style="clear:both" />';
                   5242:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5243:         }
1.903     droeschl 5244: 
1.235     raeburn  5245:         return $bodytag;
1.182     matthew  5246: }
                   5247: 
1.917     raeburn  5248: sub dc_courseid_toggle {
                   5249:     my ($dc_info) = @_;
1.980     raeburn  5250:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5251:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5252:            &mt('(More ...)').'</a></span>'.
                   5253:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5254: }
                   5255: 
1.330     albertel 5256: sub make_attr_string {
                   5257:     my ($register,$attr_ref) = @_;
                   5258: 
                   5259:     if ($attr_ref && !ref($attr_ref)) {
                   5260: 	die("addentries Must be a hash ref ".
                   5261: 	    join(':',caller(1))." ".
                   5262: 	    join(':',caller(0))." ");
                   5263:     }
                   5264: 
                   5265:     if ($register) {
1.339     albertel 5266: 	my ($on_load,$on_unload);
                   5267: 	foreach my $key (keys(%{$attr_ref})) {
                   5268: 	    if      (lc($key) eq 'onload') {
                   5269: 		$on_load.=$attr_ref->{$key}.';';
                   5270: 		delete($attr_ref->{$key});
                   5271: 
                   5272: 	    } elsif (lc($key) eq 'onunload') {
                   5273: 		$on_unload.=$attr_ref->{$key}.';';
                   5274: 		delete($attr_ref->{$key});
                   5275: 	    }
                   5276: 	}
1.953     droeschl 5277: 	$attr_ref->{'onload'}  = $on_load;
                   5278: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5279:     }
1.339     albertel 5280: 
1.330     albertel 5281:     my $attr_string;
                   5282:     foreach my $attr (keys(%$attr_ref)) {
                   5283: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5284:     }
                   5285:     return $attr_string;
                   5286: }
                   5287: 
                   5288: 
1.182     matthew  5289: ###############################################
1.251     albertel 5290: ###############################################
                   5291: 
                   5292: =pod
                   5293: 
                   5294: =item * &endbodytag()
                   5295: 
                   5296: Returns a uniform footer for LON-CAPA web pages.
                   5297: 
1.635     raeburn  5298: Inputs: 1 - optional reference to an args hash
                   5299: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5300: a 'Continue' link is not displayed if the page contains an
                   5301: internal redirect in the <head></head> section,
                   5302: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5303: 
                   5304: =cut
                   5305: 
                   5306: sub endbodytag {
1.635     raeburn  5307:     my ($args) = @_;
1.1080    raeburn  5308:     my $endbodytag;
                   5309:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5310:         $endbodytag='</body>';
                   5311:     }
1.269     albertel 5312:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5313:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5314:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5315: 	    $endbodytag=
                   5316: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5317: 	        &mt('Continue').'</a>'.
                   5318: 	        $endbodytag;
                   5319:         }
1.315     albertel 5320:     }
1.251     albertel 5321:     return $endbodytag;
                   5322: }
                   5323: 
1.352     albertel 5324: =pod
                   5325: 
                   5326: =item * &standard_css()
                   5327: 
                   5328: Returns a style sheet
                   5329: 
                   5330: Inputs: (all optional)
                   5331:             domain         -> force to color decorate a page for a specific
                   5332:                                domain
                   5333:             function       -> force usage of a specific rolish color scheme
                   5334:             bgcolor        -> override the default page bgcolor
                   5335: 
                   5336: =cut
                   5337: 
1.343     albertel 5338: sub standard_css {
1.345     albertel 5339:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5340:     $function  = &get_users_function() if (!$function);
                   5341:     my $img    = &designparm($function.'.img',   $domain);
                   5342:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5343:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5344:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5345: #second colour for later usage
1.345     albertel 5346:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5347:     my $pgbg_or_bgcolor =
                   5348: 	         $bgcolor ||
1.352     albertel 5349: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5350:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5351:     my $alink  = &designparm($function.'.alink', $domain);
                   5352:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5353:     my $link   = &designparm($function.'.link',  $domain);
                   5354: 
1.602     albertel 5355:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5356:     my $mono                 = 'monospace';
1.850     bisitz   5357:     my $data_table_head      = $sidebg;
                   5358:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5359:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5360:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5361:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5362:     my $mail_new             = '#FFBB77';
                   5363:     my $mail_new_hover       = '#DD9955';
                   5364:     my $mail_read            = '#BBBB77';
                   5365:     my $mail_read_hover      = '#999944';
                   5366:     my $mail_replied         = '#AAAA88';
                   5367:     my $mail_replied_hover   = '#888855';
                   5368:     my $mail_other           = '#99BBBB';
                   5369:     my $mail_other_hover     = '#669999';
1.391     albertel 5370:     my $table_header         = '#DDDDDD';
1.489     raeburn  5371:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5372:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5373:     my $button_hover         = '#BF2317';
1.392     albertel 5374: 
1.608     albertel 5375:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5376:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5377:                                              : '0 3px 0 4px';
1.448     albertel 5378: 
1.523     albertel 5379: 
1.343     albertel 5380:     return <<END;
1.947     droeschl 5381: 
                   5382: /* needed for iframe to allow 100% height in FF */
                   5383: body, html { 
                   5384:     margin: 0;
                   5385:     padding: 0 0.5%;
                   5386:     height: 99%; /* to avoid scrollbars */
                   5387: }
                   5388: 
1.795     www      5389: body {
1.911     bisitz   5390:   font-family: $sans;
                   5391:   line-height:130%;
                   5392:   font-size:0.83em;
                   5393:   color:$font;
1.795     www      5394: }
                   5395: 
1.959     onken    5396: a:focus,
                   5397: a:focus img {
1.795     www      5398:   color: red;
                   5399: }
1.698     harmsja  5400: 
1.911     bisitz   5401: form, .inline {
                   5402:   display: inline;
1.795     www      5403: }
1.721     harmsja  5404: 
1.795     www      5405: .LC_right {
1.911     bisitz   5406:   text-align:right;
1.795     www      5407: }
                   5408: 
                   5409: .LC_middle {
1.911     bisitz   5410:   vertical-align:middle;
1.795     www      5411: }
1.721     harmsja  5412: 
1.911     bisitz   5413: .LC_400Box {
                   5414:   width:400px;
                   5415: }
1.721     harmsja  5416: 
1.947     droeschl 5417: .LC_iframecontainer {
                   5418:     width: 98%;
                   5419:     margin: 0;
                   5420:     position: fixed;
                   5421:     top: 8.5em;
                   5422:     bottom: 0;
                   5423: }
                   5424: 
                   5425: .LC_iframecontainer iframe{
                   5426:     border: none;
                   5427:     width: 100%;
                   5428:     height: 100%;
                   5429: }
                   5430: 
1.778     bisitz   5431: .LC_filename {
                   5432:   font-family: $mono;
                   5433:   white-space:pre;
1.921     bisitz   5434:   font-size: 120%;
1.778     bisitz   5435: }
                   5436: 
                   5437: .LC_fileicon {
                   5438:   border: none;
                   5439:   height: 1.3em;
                   5440:   vertical-align: text-bottom;
                   5441:   margin-right: 0.3em;
                   5442:   text-decoration:none;
                   5443: }
                   5444: 
1.1008    www      5445: .LC_setting {
                   5446:   text-decoration:underline;
                   5447: }
                   5448: 
1.350     albertel 5449: .LC_error {
                   5450:   color: red;
                   5451: }
1.795     www      5452: 
1.1097    bisitz   5453: .LC_warning {
                   5454:   color: darkorange;
                   5455: }
                   5456: 
1.457     albertel 5457: .LC_diff_removed {
1.733     bisitz   5458:   color: red;
1.394     albertel 5459: }
1.532     albertel 5460: 
                   5461: .LC_info,
1.457     albertel 5462: .LC_success,
                   5463: .LC_diff_added {
1.350     albertel 5464:   color: green;
                   5465: }
1.795     www      5466: 
1.802     bisitz   5467: div.LC_confirm_box {
                   5468:   background-color: #FAFAFA;
                   5469:   border: 1px solid $lg_border_color;
                   5470:   margin-right: 0;
                   5471:   padding: 5px;
                   5472: }
                   5473: 
                   5474: div.LC_confirm_box .LC_error img,
                   5475: div.LC_confirm_box .LC_success img {
                   5476:   vertical-align: middle;
                   5477: }
                   5478: 
1.440     albertel 5479: .LC_icon {
1.771     droeschl 5480:   border: none;
1.790     droeschl 5481:   vertical-align: middle;
1.771     droeschl 5482: }
                   5483: 
1.543     albertel 5484: .LC_docs_spacer {
                   5485:   width: 25px;
                   5486:   height: 1px;
1.771     droeschl 5487:   border: none;
1.543     albertel 5488: }
1.346     albertel 5489: 
1.532     albertel 5490: .LC_internal_info {
1.735     bisitz   5491:   color: #999999;
1.532     albertel 5492: }
                   5493: 
1.794     www      5494: .LC_discussion {
1.1050    www      5495:   background: $data_table_dark;
1.911     bisitz   5496:   border: 1px solid black;
                   5497:   margin: 2px;
1.794     www      5498: }
                   5499: 
                   5500: .LC_disc_action_left {
1.1050    www      5501:   background: $sidebg;
1.911     bisitz   5502:   text-align: left;
1.1050    www      5503:   padding: 4px;
                   5504:   margin: 2px;
1.794     www      5505: }
                   5506: 
                   5507: .LC_disc_action_right {
1.1050    www      5508:   background: $sidebg;
1.911     bisitz   5509:   text-align: right;
1.1050    www      5510:   padding: 4px;
                   5511:   margin: 2px;
1.794     www      5512: }
                   5513: 
                   5514: .LC_disc_new_item {
1.911     bisitz   5515:   background: white;
                   5516:   border: 2px solid red;
1.1050    www      5517:   margin: 4px;
                   5518:   padding: 4px;
1.794     www      5519: }
                   5520: 
                   5521: .LC_disc_old_item {
1.911     bisitz   5522:   background: white;
1.1050    www      5523:   margin: 4px;
                   5524:   padding: 4px;
1.794     www      5525: }
                   5526: 
1.458     albertel 5527: table.LC_pastsubmission {
                   5528:   border: 1px solid black;
                   5529:   margin: 2px;
                   5530: }
                   5531: 
1.924     bisitz   5532: table#LC_menubuttons {
1.345     albertel 5533:   width: 100%;
                   5534:   background: $pgbg;
1.392     albertel 5535:   border: 2px;
1.402     albertel 5536:   border-collapse: separate;
1.803     bisitz   5537:   padding: 0;
1.345     albertel 5538: }
1.392     albertel 5539: 
1.801     tempelho 5540: table#LC_title_bar a {
                   5541:   color: $fontmenu;
                   5542: }
1.836     bisitz   5543: 
1.807     droeschl 5544: table#LC_title_bar {
1.819     tempelho 5545:   clear: both;
1.836     bisitz   5546:   display: none;
1.807     droeschl 5547: }
                   5548: 
1.795     www      5549: table#LC_title_bar,
1.933     droeschl 5550: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5551: table#LC_title_bar.LC_with_remote {
1.359     albertel 5552:   width: 100%;
1.392     albertel 5553:   border-color: $pgbg;
                   5554:   border-style: solid;
                   5555:   border-width: $border;
1.379     albertel 5556:   background: $pgbg;
1.801     tempelho 5557:   color: $fontmenu;
1.392     albertel 5558:   border-collapse: collapse;
1.803     bisitz   5559:   padding: 0;
1.819     tempelho 5560:   margin: 0;
1.359     albertel 5561: }
1.795     www      5562: 
1.933     droeschl 5563: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5564:     margin: 0;
                   5565:     padding: 0;
1.933     droeschl 5566:     position: relative;
                   5567:     list-style: none;
1.913     droeschl 5568: }
1.933     droeschl 5569: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5570:     display: inline;
                   5571: }
1.933     droeschl 5572: 
                   5573: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5574:     padding: 0;
1.933     droeschl 5575:     margin: 0;
                   5576:     float: left;
1.913     droeschl 5577: }
1.933     droeschl 5578: .LC_breadcrumb_tools_tools {
                   5579:     padding: 0;
                   5580:     margin: 0;
1.913     droeschl 5581:     float: right;
                   5582: }
                   5583: 
1.359     albertel 5584: table#LC_title_bar td {
                   5585:   background: $tabbg;
                   5586: }
1.795     www      5587: 
1.911     bisitz   5588: table#LC_menubuttons img {
1.803     bisitz   5589:   border: none;
1.346     albertel 5590: }
1.795     www      5591: 
1.842     droeschl 5592: .LC_breadcrumbs_component {
1.911     bisitz   5593:   float: right;
                   5594:   margin: 0 1em;
1.357     albertel 5595: }
1.842     droeschl 5596: .LC_breadcrumbs_component img {
1.911     bisitz   5597:   vertical-align: middle;
1.777     tempelho 5598: }
1.795     www      5599: 
1.383     albertel 5600: td.LC_table_cell_checkbox {
                   5601:   text-align: center;
                   5602: }
1.795     www      5603: 
                   5604: .LC_fontsize_small {
1.911     bisitz   5605:   font-size: 70%;
1.705     tempelho 5606: }
                   5607: 
1.844     bisitz   5608: #LC_breadcrumbs {
1.911     bisitz   5609:   clear:both;
                   5610:   background: $sidebg;
                   5611:   border-bottom: 1px solid $lg_border_color;
                   5612:   line-height: 2.5em;
1.933     droeschl 5613:   overflow: hidden;
1.911     bisitz   5614:   margin: 0;
                   5615:   padding: 0;
1.995     raeburn  5616:   text-align: left;
1.819     tempelho 5617: }
1.862     bisitz   5618: 
1.1098    bisitz   5619: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5620:   clear:both;
                   5621:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5622:   border: 1px solid $sidebg;
1.1098    bisitz   5623:   margin: 0 0 10px 0;
1.966     bisitz   5624:   padding: 3px;
1.995     raeburn  5625:   text-align: left;
1.822     bisitz   5626: }
                   5627: 
1.795     www      5628: .LC_fontsize_medium {
1.911     bisitz   5629:   font-size: 85%;
1.705     tempelho 5630: }
                   5631: 
1.795     www      5632: .LC_fontsize_large {
1.911     bisitz   5633:   font-size: 120%;
1.705     tempelho 5634: }
                   5635: 
1.346     albertel 5636: .LC_menubuttons_inline_text {
                   5637:   color: $font;
1.698     harmsja  5638:   font-size: 90%;
1.701     harmsja  5639:   padding-left:3px;
1.346     albertel 5640: }
                   5641: 
1.934     droeschl 5642: .LC_menubuttons_inline_text img{
                   5643:   vertical-align: middle;
                   5644: }
                   5645: 
1.1051    www      5646: li.LC_menubuttons_inline_text img {
1.951     onken    5647:   cursor:pointer;
1.1002    droeschl 5648:   text-decoration: none;
1.951     onken    5649: }
                   5650: 
1.526     www      5651: .LC_menubuttons_link {
                   5652:   text-decoration: none;
                   5653: }
1.795     www      5654: 
1.522     albertel 5655: .LC_menubuttons_category {
1.521     www      5656:   color: $font;
1.526     www      5657:   background: $pgbg;
1.521     www      5658:   font-size: larger;
                   5659:   font-weight: bold;
                   5660: }
                   5661: 
1.346     albertel 5662: td.LC_menubuttons_text {
1.911     bisitz   5663:   color: $font;
1.346     albertel 5664: }
1.706     harmsja  5665: 
1.346     albertel 5666: .LC_current_location {
                   5667:   background: $tabbg;
                   5668: }
1.795     www      5669: 
1.938     bisitz   5670: table.LC_data_table {
1.347     albertel 5671:   border: 1px solid #000000;
1.402     albertel 5672:   border-collapse: separate;
1.426     albertel 5673:   border-spacing: 1px;
1.610     albertel 5674:   background: $pgbg;
1.347     albertel 5675: }
1.795     www      5676: 
1.422     albertel 5677: .LC_data_table_dense {
                   5678:   font-size: small;
                   5679: }
1.795     www      5680: 
1.507     raeburn  5681: table.LC_nested_outer {
                   5682:   border: 1px solid #000000;
1.589     raeburn  5683:   border-collapse: collapse;
1.803     bisitz   5684:   border-spacing: 0;
1.507     raeburn  5685:   width: 100%;
                   5686: }
1.795     www      5687: 
1.879     raeburn  5688: table.LC_innerpickbox,
1.507     raeburn  5689: table.LC_nested {
1.803     bisitz   5690:   border: none;
1.589     raeburn  5691:   border-collapse: collapse;
1.803     bisitz   5692:   border-spacing: 0;
1.507     raeburn  5693:   width: 100%;
                   5694: }
1.795     www      5695: 
1.911     bisitz   5696: table.LC_data_table tr th,
                   5697: table.LC_calendar tr th,
1.879     raeburn  5698: table.LC_prior_tries tr th,
                   5699: table.LC_innerpickbox tr th {
1.349     albertel 5700:   font-weight: bold;
                   5701:   background-color: $data_table_head;
1.801     tempelho 5702:   color:$fontmenu;
1.701     harmsja  5703:   font-size:90%;
1.347     albertel 5704: }
1.795     www      5705: 
1.879     raeburn  5706: table.LC_innerpickbox tr th,
                   5707: table.LC_innerpickbox tr td {
                   5708:   vertical-align: top;
                   5709: }
                   5710: 
1.711     raeburn  5711: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5712:   background-color: #CCCCCC;
1.711     raeburn  5713:   font-weight: bold;
                   5714:   text-align: left;
                   5715: }
1.795     www      5716: 
1.912     bisitz   5717: table.LC_data_table tr.LC_odd_row > td {
                   5718:   background-color: $data_table_light;
                   5719:   padding: 2px;
                   5720:   vertical-align: top;
                   5721: }
                   5722: 
1.809     bisitz   5723: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5724:   background-color: $data_table_light;
1.912     bisitz   5725:   vertical-align: top;
                   5726: }
                   5727: 
                   5728: table.LC_data_table tr.LC_even_row > td {
                   5729:   background-color: $data_table_dark;
1.425     albertel 5730:   padding: 2px;
1.900     bisitz   5731:   vertical-align: top;
1.347     albertel 5732: }
1.795     www      5733: 
1.809     bisitz   5734: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5735:   background-color: $data_table_dark;
1.900     bisitz   5736:   vertical-align: top;
1.347     albertel 5737: }
1.795     www      5738: 
1.425     albertel 5739: table.LC_data_table tr.LC_data_table_highlight td {
                   5740:   background-color: $data_table_darker;
                   5741: }
1.795     www      5742: 
1.639     raeburn  5743: table.LC_data_table tr td.LC_leftcol_header {
                   5744:   background-color: $data_table_head;
                   5745:   font-weight: bold;
                   5746: }
1.795     www      5747: 
1.451     albertel 5748: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5749: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5750:   font-weight: bold;
                   5751:   font-style: italic;
                   5752:   text-align: center;
                   5753:   padding: 8px;
1.347     albertel 5754: }
1.795     www      5755: 
1.1114    raeburn  5756: table.LC_data_table tr.LC_empty_row td,
                   5757: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5758:   background-color: $sidebg;
                   5759: }
                   5760: 
                   5761: table.LC_nested tr.LC_empty_row td {
                   5762:   background-color: #FFFFFF;
                   5763: }
                   5764: 
1.890     droeschl 5765: table.LC_caption {
                   5766: }
                   5767: 
1.507     raeburn  5768: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5769:   padding: 4ex
                   5770: }
1.795     www      5771: 
1.507     raeburn  5772: table.LC_nested_outer tr th {
                   5773:   font-weight: bold;
1.801     tempelho 5774:   color:$fontmenu;
1.507     raeburn  5775:   background-color: $data_table_head;
1.701     harmsja  5776:   font-size: small;
1.507     raeburn  5777:   border-bottom: 1px solid #000000;
                   5778: }
1.795     www      5779: 
1.507     raeburn  5780: table.LC_nested_outer tr td.LC_subheader {
                   5781:   background-color: $data_table_head;
                   5782:   font-weight: bold;
                   5783:   font-size: small;
                   5784:   border-bottom: 1px solid #000000;
                   5785:   text-align: right;
1.451     albertel 5786: }
1.795     www      5787: 
1.507     raeburn  5788: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5789:   background-color: #CCCCCC;
1.451     albertel 5790:   font-weight: bold;
                   5791:   font-size: small;
1.507     raeburn  5792:   text-align: center;
                   5793: }
1.795     www      5794: 
1.589     raeburn  5795: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5796: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5797:   text-align: left;
1.451     albertel 5798: }
1.795     www      5799: 
1.507     raeburn  5800: table.LC_nested td {
1.735     bisitz   5801:   background-color: #FFFFFF;
1.451     albertel 5802:   font-size: small;
1.507     raeburn  5803: }
1.795     www      5804: 
1.507     raeburn  5805: table.LC_nested_outer tr th.LC_right_item,
                   5806: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5807: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5808: table.LC_nested tr td.LC_right_item {
1.451     albertel 5809:   text-align: right;
                   5810: }
                   5811: 
1.507     raeburn  5812: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5813:   background-color: #EEEEEE;
1.451     albertel 5814: }
                   5815: 
1.473     raeburn  5816: table.LC_createuser {
                   5817: }
                   5818: 
                   5819: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5820:   font-size: small;
1.473     raeburn  5821: }
                   5822: 
                   5823: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5824:   background-color: #CCCCCC;
1.473     raeburn  5825:   font-weight: bold;
                   5826:   text-align: center;
                   5827: }
                   5828: 
1.349     albertel 5829: table.LC_calendar {
                   5830:   border: 1px solid #000000;
                   5831:   border-collapse: collapse;
1.917     raeburn  5832:   width: 98%;
1.349     albertel 5833: }
1.795     www      5834: 
1.349     albertel 5835: table.LC_calendar_pickdate {
                   5836:   font-size: xx-small;
                   5837: }
1.795     www      5838: 
1.349     albertel 5839: table.LC_calendar tr td {
                   5840:   border: 1px solid #000000;
                   5841:   vertical-align: top;
1.917     raeburn  5842:   width: 14%;
1.349     albertel 5843: }
1.795     www      5844: 
1.349     albertel 5845: table.LC_calendar tr td.LC_calendar_day_empty {
                   5846:   background-color: $data_table_dark;
                   5847: }
1.795     www      5848: 
1.779     bisitz   5849: table.LC_calendar tr td.LC_calendar_day_current {
                   5850:   background-color: $data_table_highlight;
1.777     tempelho 5851: }
1.795     www      5852: 
1.938     bisitz   5853: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5854:   background-color: $mail_new;
                   5855: }
1.795     www      5856: 
1.938     bisitz   5857: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5858:   background-color: $mail_new_hover;
                   5859: }
1.795     www      5860: 
1.938     bisitz   5861: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5862:   background-color: $mail_read;
                   5863: }
1.795     www      5864: 
1.938     bisitz   5865: /*
                   5866: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5867:   background-color: $mail_read_hover;
                   5868: }
1.938     bisitz   5869: */
1.795     www      5870: 
1.938     bisitz   5871: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5872:   background-color: $mail_replied;
                   5873: }
1.795     www      5874: 
1.938     bisitz   5875: /*
                   5876: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5877:   background-color: $mail_replied_hover;
                   5878: }
1.938     bisitz   5879: */
1.795     www      5880: 
1.938     bisitz   5881: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5882:   background-color: $mail_other;
                   5883: }
1.795     www      5884: 
1.938     bisitz   5885: /*
                   5886: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5887:   background-color: $mail_other_hover;
                   5888: }
1.938     bisitz   5889: */
1.494     raeburn  5890: 
1.777     tempelho 5891: table.LC_data_table tr > td.LC_browser_file,
                   5892: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5893:   background: #AAEE77;
1.389     albertel 5894: }
1.795     www      5895: 
1.777     tempelho 5896: table.LC_data_table tr > td.LC_browser_file_locked,
                   5897: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5898:   background: #FFAA99;
1.387     albertel 5899: }
1.795     www      5900: 
1.777     tempelho 5901: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5902:   background: #888888;
1.779     bisitz   5903: }
1.795     www      5904: 
1.777     tempelho 5905: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5906: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5907:   background: #F8F866;
1.777     tempelho 5908: }
1.795     www      5909: 
1.696     bisitz   5910: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5911:   background: #E0E8FF;
1.387     albertel 5912: }
1.696     bisitz   5913: 
1.707     bisitz   5914: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5915:   /* background: #77FF77; */
1.707     bisitz   5916: }
1.795     www      5917: 
1.707     bisitz   5918: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5919:   border-right: 8px solid #FFFF77;
1.707     bisitz   5920: }
1.795     www      5921: 
1.707     bisitz   5922: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5923:   border-right: 8px solid #FFAA77;
1.707     bisitz   5924: }
1.795     www      5925: 
1.707     bisitz   5926: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5927:   border-right: 8px solid #FF7777;
1.707     bisitz   5928: }
1.795     www      5929: 
1.707     bisitz   5930: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5931:   border-right: 8px solid #AAFF77;
1.707     bisitz   5932: }
1.795     www      5933: 
1.707     bisitz   5934: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5935:   border-right: 8px solid #11CC55;
1.707     bisitz   5936: }
                   5937: 
1.388     albertel 5938: span.LC_current_location {
1.701     harmsja  5939:   font-size:larger;
1.388     albertel 5940:   background: $pgbg;
                   5941: }
1.387     albertel 5942: 
1.1029    www      5943: span.LC_current_nav_location {
                   5944:   font-weight:bold;
                   5945:   background: $sidebg;
                   5946: }
                   5947: 
1.395     albertel 5948: span.LC_parm_menu_item {
                   5949:   font-size: larger;
                   5950: }
1.795     www      5951: 
1.395     albertel 5952: span.LC_parm_scope_all {
                   5953:   color: red;
                   5954: }
1.795     www      5955: 
1.395     albertel 5956: span.LC_parm_scope_folder {
                   5957:   color: green;
                   5958: }
1.795     www      5959: 
1.395     albertel 5960: span.LC_parm_scope_resource {
                   5961:   color: orange;
                   5962: }
1.795     www      5963: 
1.395     albertel 5964: span.LC_parm_part {
                   5965:   color: blue;
                   5966: }
1.795     www      5967: 
1.911     bisitz   5968: span.LC_parm_folder,
                   5969: span.LC_parm_symb {
1.395     albertel 5970:   font-size: x-small;
                   5971:   font-family: $mono;
                   5972:   color: #AAAAAA;
                   5973: }
                   5974: 
1.977     bisitz   5975: ul.LC_parm_parmlist li {
                   5976:   display: inline-block;
                   5977:   padding: 0.3em 0.8em;
                   5978:   vertical-align: top;
                   5979:   width: 150px;
                   5980:   border-top:1px solid $lg_border_color;
                   5981: }
                   5982: 
1.795     www      5983: td.LC_parm_overview_level_menu,
                   5984: td.LC_parm_overview_map_menu,
                   5985: td.LC_parm_overview_parm_selectors,
                   5986: td.LC_parm_overview_restrictions  {
1.396     albertel 5987:   border: 1px solid black;
                   5988:   border-collapse: collapse;
                   5989: }
1.795     www      5990: 
1.396     albertel 5991: table.LC_parm_overview_restrictions td {
                   5992:   border-width: 1px 4px 1px 4px;
                   5993:   border-style: solid;
                   5994:   border-color: $pgbg;
                   5995:   text-align: center;
                   5996: }
1.795     www      5997: 
1.396     albertel 5998: table.LC_parm_overview_restrictions th {
                   5999:   background: $tabbg;
                   6000:   border-width: 1px 4px 1px 4px;
                   6001:   border-style: solid;
                   6002:   border-color: $pgbg;
                   6003: }
1.795     www      6004: 
1.398     albertel 6005: table#LC_helpmenu {
1.803     bisitz   6006:   border: none;
1.398     albertel 6007:   height: 55px;
1.803     bisitz   6008:   border-spacing: 0;
1.398     albertel 6009: }
                   6010: 
                   6011: table#LC_helpmenu fieldset legend {
                   6012:   font-size: larger;
                   6013: }
1.795     www      6014: 
1.397     albertel 6015: table#LC_helpmenu_links {
                   6016:   width: 100%;
                   6017:   border: 1px solid black;
                   6018:   background: $pgbg;
1.803     bisitz   6019:   padding: 0;
1.397     albertel 6020:   border-spacing: 1px;
                   6021: }
1.795     www      6022: 
1.397     albertel 6023: table#LC_helpmenu_links tr td {
                   6024:   padding: 1px;
                   6025:   background: $tabbg;
1.399     albertel 6026:   text-align: center;
                   6027:   font-weight: bold;
1.397     albertel 6028: }
1.396     albertel 6029: 
1.795     www      6030: table#LC_helpmenu_links a:link,
                   6031: table#LC_helpmenu_links a:visited,
1.397     albertel 6032: table#LC_helpmenu_links a:active {
                   6033:   text-decoration: none;
                   6034:   color: $font;
                   6035: }
1.795     www      6036: 
1.397     albertel 6037: table#LC_helpmenu_links a:hover {
                   6038:   text-decoration: underline;
                   6039:   color: $vlink;
                   6040: }
1.396     albertel 6041: 
1.417     albertel 6042: .LC_chrt_popup_exists {
                   6043:   border: 1px solid #339933;
                   6044:   margin: -1px;
                   6045: }
1.795     www      6046: 
1.417     albertel 6047: .LC_chrt_popup_up {
                   6048:   border: 1px solid yellow;
                   6049:   margin: -1px;
                   6050: }
1.795     www      6051: 
1.417     albertel 6052: .LC_chrt_popup {
                   6053:   border: 1px solid #8888FF;
                   6054:   background: #CCCCFF;
                   6055: }
1.795     www      6056: 
1.421     albertel 6057: table.LC_pick_box {
                   6058:   border-collapse: separate;
                   6059:   background: white;
                   6060:   border: 1px solid black;
                   6061:   border-spacing: 1px;
                   6062: }
1.795     www      6063: 
1.421     albertel 6064: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6065:   background: $sidebg;
1.421     albertel 6066:   font-weight: bold;
1.900     bisitz   6067:   text-align: left;
1.740     bisitz   6068:   vertical-align: top;
1.421     albertel 6069:   width: 184px;
                   6070:   padding: 8px;
                   6071: }
1.795     www      6072: 
1.579     raeburn  6073: table.LC_pick_box td.LC_pick_box_value {
                   6074:   text-align: left;
                   6075:   padding: 8px;
                   6076: }
1.795     www      6077: 
1.579     raeburn  6078: table.LC_pick_box td.LC_pick_box_select {
                   6079:   text-align: left;
                   6080:   padding: 8px;
                   6081: }
1.795     www      6082: 
1.424     albertel 6083: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6084:   padding: 0;
1.421     albertel 6085:   height: 1px;
                   6086:   background: black;
                   6087: }
1.795     www      6088: 
1.421     albertel 6089: table.LC_pick_box td.LC_pick_box_submit {
                   6090:   text-align: right;
                   6091: }
1.795     www      6092: 
1.579     raeburn  6093: table.LC_pick_box td.LC_evenrow_value {
                   6094:   text-align: left;
                   6095:   padding: 8px;
                   6096:   background-color: $data_table_light;
                   6097: }
1.795     www      6098: 
1.579     raeburn  6099: table.LC_pick_box td.LC_oddrow_value {
                   6100:   text-align: left;
                   6101:   padding: 8px;
                   6102:   background-color: $data_table_light;
                   6103: }
1.795     www      6104: 
1.579     raeburn  6105: span.LC_helpform_receipt_cat {
                   6106:   font-weight: bold;
                   6107: }
1.795     www      6108: 
1.424     albertel 6109: table.LC_group_priv_box {
                   6110:   background: white;
                   6111:   border: 1px solid black;
                   6112:   border-spacing: 1px;
                   6113: }
1.795     www      6114: 
1.424     albertel 6115: table.LC_group_priv_box td.LC_pick_box_title {
                   6116:   background: $tabbg;
                   6117:   font-weight: bold;
                   6118:   text-align: right;
                   6119:   width: 184px;
                   6120: }
1.795     www      6121: 
1.424     albertel 6122: table.LC_group_priv_box td.LC_groups_fixed {
                   6123:   background: $data_table_light;
                   6124:   text-align: center;
                   6125: }
1.795     www      6126: 
1.424     albertel 6127: table.LC_group_priv_box td.LC_groups_optional {
                   6128:   background: $data_table_dark;
                   6129:   text-align: center;
                   6130: }
1.795     www      6131: 
1.424     albertel 6132: table.LC_group_priv_box td.LC_groups_functionality {
                   6133:   background: $data_table_darker;
                   6134:   text-align: center;
                   6135:   font-weight: bold;
                   6136: }
1.795     www      6137: 
1.424     albertel 6138: table.LC_group_priv td {
                   6139:   text-align: left;
1.803     bisitz   6140:   padding: 0;
1.424     albertel 6141: }
                   6142: 
                   6143: .LC_navbuttons {
                   6144:   margin: 2ex 0ex 2ex 0ex;
                   6145: }
1.795     www      6146: 
1.423     albertel 6147: .LC_topic_bar {
                   6148:   font-weight: bold;
                   6149:   background: $tabbg;
1.918     wenzelju 6150:   margin: 1em 0em 1em 2em;
1.805     bisitz   6151:   padding: 3px;
1.918     wenzelju 6152:   font-size: 1.2em;
1.423     albertel 6153: }
1.795     www      6154: 
1.423     albertel 6155: .LC_topic_bar span {
1.918     wenzelju 6156:   left: 0.5em;
                   6157:   position: absolute;
1.423     albertel 6158:   vertical-align: middle;
1.918     wenzelju 6159:   font-size: 1.2em;
1.423     albertel 6160: }
1.795     www      6161: 
1.423     albertel 6162: table.LC_course_group_status {
                   6163:   margin: 20px;
                   6164: }
1.795     www      6165: 
1.423     albertel 6166: table.LC_status_selector td {
                   6167:   vertical-align: top;
                   6168:   text-align: center;
1.424     albertel 6169:   padding: 4px;
                   6170: }
1.795     www      6171: 
1.599     albertel 6172: div.LC_feedback_link {
1.616     albertel 6173:   clear: both;
1.829     kalberla 6174:   background: $sidebg;
1.779     bisitz   6175:   width: 100%;
1.829     kalberla 6176:   padding-bottom: 10px;
                   6177:   border: 1px $tabbg solid;
1.833     kalberla 6178:   height: 22px;
                   6179:   line-height: 22px;
                   6180:   padding-top: 5px;
                   6181: }
                   6182: 
                   6183: div.LC_feedback_link img {
                   6184:   height: 22px;
1.867     kalberla 6185:   vertical-align:middle;
1.829     kalberla 6186: }
                   6187: 
1.911     bisitz   6188: div.LC_feedback_link a {
1.829     kalberla 6189:   text-decoration: none;
1.489     raeburn  6190: }
1.795     www      6191: 
1.867     kalberla 6192: div.LC_comblock {
1.911     bisitz   6193:   display:inline;
1.867     kalberla 6194:   color:$font;
                   6195:   font-size:90%;
                   6196: }
                   6197: 
                   6198: div.LC_feedback_link div.LC_comblock {
                   6199:   padding-left:5px;
                   6200: }
                   6201: 
                   6202: div.LC_feedback_link div.LC_comblock a {
                   6203:   color:$font;
                   6204: }
                   6205: 
1.489     raeburn  6206: span.LC_feedback_link {
1.858     bisitz   6207:   /* background: $feedback_link_bg; */
1.599     albertel 6208:   font-size: larger;
                   6209: }
1.795     www      6210: 
1.599     albertel 6211: span.LC_message_link {
1.858     bisitz   6212:   /* background: $feedback_link_bg; */
1.599     albertel 6213:   font-size: larger;
                   6214:   position: absolute;
                   6215:   right: 1em;
1.489     raeburn  6216: }
1.421     albertel 6217: 
1.515     albertel 6218: table.LC_prior_tries {
1.524     albertel 6219:   border: 1px solid #000000;
                   6220:   border-collapse: separate;
                   6221:   border-spacing: 1px;
1.515     albertel 6222: }
1.523     albertel 6223: 
1.515     albertel 6224: table.LC_prior_tries td {
1.524     albertel 6225:   padding: 2px;
1.515     albertel 6226: }
1.523     albertel 6227: 
                   6228: .LC_answer_correct {
1.795     www      6229:   background: lightgreen;
                   6230:   color: darkgreen;
                   6231:   padding: 6px;
1.523     albertel 6232: }
1.795     www      6233: 
1.523     albertel 6234: .LC_answer_charged_try {
1.797     www      6235:   background: #FFAAAA;
1.795     www      6236:   color: darkred;
                   6237:   padding: 6px;
1.523     albertel 6238: }
1.795     www      6239: 
1.779     bisitz   6240: .LC_answer_not_charged_try,
1.523     albertel 6241: .LC_answer_no_grade,
                   6242: .LC_answer_late {
1.795     www      6243:   background: lightyellow;
1.523     albertel 6244:   color: black;
1.795     www      6245:   padding: 6px;
1.523     albertel 6246: }
1.795     www      6247: 
1.523     albertel 6248: .LC_answer_previous {
1.795     www      6249:   background: lightblue;
                   6250:   color: darkblue;
                   6251:   padding: 6px;
1.523     albertel 6252: }
1.795     www      6253: 
1.779     bisitz   6254: .LC_answer_no_message {
1.777     tempelho 6255:   background: #FFFFFF;
                   6256:   color: black;
1.795     www      6257:   padding: 6px;
1.779     bisitz   6258: }
1.795     www      6259: 
1.779     bisitz   6260: .LC_answer_unknown {
                   6261:   background: orange;
                   6262:   color: black;
1.795     www      6263:   padding: 6px;
1.777     tempelho 6264: }
1.795     www      6265: 
1.529     albertel 6266: span.LC_prior_numerical,
                   6267: span.LC_prior_string,
                   6268: span.LC_prior_custom,
                   6269: span.LC_prior_reaction,
                   6270: span.LC_prior_math {
1.925     bisitz   6271:   font-family: $mono;
1.523     albertel 6272:   white-space: pre;
                   6273: }
                   6274: 
1.525     albertel 6275: span.LC_prior_string {
1.925     bisitz   6276:   font-family: $mono;
1.525     albertel 6277:   white-space: pre;
                   6278: }
                   6279: 
1.523     albertel 6280: table.LC_prior_option {
                   6281:   width: 100%;
                   6282:   border-collapse: collapse;
                   6283: }
1.795     www      6284: 
1.911     bisitz   6285: table.LC_prior_rank,
1.795     www      6286: table.LC_prior_match {
1.528     albertel 6287:   border-collapse: collapse;
                   6288: }
1.795     www      6289: 
1.528     albertel 6290: table.LC_prior_option tr td,
                   6291: table.LC_prior_rank tr td,
                   6292: table.LC_prior_match tr td {
1.524     albertel 6293:   border: 1px solid #000000;
1.515     albertel 6294: }
                   6295: 
1.855     bisitz   6296: .LC_nobreak {
1.544     albertel 6297:   white-space: nowrap;
1.519     raeburn  6298: }
                   6299: 
1.576     raeburn  6300: span.LC_cusr_emph {
                   6301:   font-style: italic;
                   6302: }
                   6303: 
1.633     raeburn  6304: span.LC_cusr_subheading {
                   6305:   font-weight: normal;
                   6306:   font-size: 85%;
                   6307: }
                   6308: 
1.861     bisitz   6309: div.LC_docs_entry_move {
1.859     bisitz   6310:   border: 1px solid #BBBBBB;
1.545     albertel 6311:   background: #DDDDDD;
1.861     bisitz   6312:   width: 22px;
1.859     bisitz   6313:   padding: 1px;
                   6314:   margin: 0;
1.545     albertel 6315: }
                   6316: 
1.861     bisitz   6317: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6318: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6319:   font-size: x-small;
                   6320: }
1.795     www      6321: 
1.861     bisitz   6322: .LC_docs_entry_parameter {
                   6323:   white-space: nowrap;
                   6324: }
                   6325: 
1.544     albertel 6326: .LC_docs_copy {
1.545     albertel 6327:   color: #000099;
1.544     albertel 6328: }
1.795     www      6329: 
1.544     albertel 6330: .LC_docs_cut {
1.545     albertel 6331:   color: #550044;
1.544     albertel 6332: }
1.795     www      6333: 
1.544     albertel 6334: .LC_docs_rename {
1.545     albertel 6335:   color: #009900;
1.544     albertel 6336: }
1.795     www      6337: 
1.544     albertel 6338: .LC_docs_remove {
1.545     albertel 6339:   color: #990000;
                   6340: }
                   6341: 
1.547     albertel 6342: .LC_docs_reinit_warn,
                   6343: .LC_docs_ext_edit {
                   6344:   font-size: x-small;
                   6345: }
                   6346: 
1.545     albertel 6347: table.LC_docs_adddocs td,
                   6348: table.LC_docs_adddocs th {
                   6349:   border: 1px solid #BBBBBB;
                   6350:   padding: 4px;
                   6351:   background: #DDDDDD;
1.543     albertel 6352: }
                   6353: 
1.584     albertel 6354: table.LC_sty_begin {
                   6355:   background: #BBFFBB;
                   6356: }
1.795     www      6357: 
1.584     albertel 6358: table.LC_sty_end {
                   6359:   background: #FFBBBB;
                   6360: }
                   6361: 
1.589     raeburn  6362: table.LC_double_column {
1.803     bisitz   6363:   border-width: 0;
1.589     raeburn  6364:   border-collapse: collapse;
                   6365:   width: 100%;
                   6366:   padding: 2px;
                   6367: }
                   6368: 
                   6369: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6370:   top: 2px;
1.589     raeburn  6371:   left: 2px;
                   6372:   width: 47%;
                   6373:   vertical-align: top;
                   6374: }
                   6375: 
                   6376: table.LC_double_column tr td.LC_right_col {
                   6377:   top: 2px;
1.779     bisitz   6378:   right: 2px;
1.589     raeburn  6379:   width: 47%;
                   6380:   vertical-align: top;
                   6381: }
                   6382: 
1.591     raeburn  6383: div.LC_left_float {
                   6384:   float: left;
                   6385:   padding-right: 5%;
1.597     albertel 6386:   padding-bottom: 4px;
1.591     raeburn  6387: }
                   6388: 
                   6389: div.LC_clear_float_header {
1.597     albertel 6390:   padding-bottom: 2px;
1.591     raeburn  6391: }
                   6392: 
                   6393: div.LC_clear_float_footer {
1.597     albertel 6394:   padding-top: 10px;
1.591     raeburn  6395:   clear: both;
                   6396: }
                   6397: 
1.597     albertel 6398: div.LC_grade_show_user {
1.941     bisitz   6399: /*  border-left: 5px solid $sidebg; */
                   6400:   border-top: 5px solid #000000;
                   6401:   margin: 50px 0 0 0;
1.936     bisitz   6402:   padding: 15px 0 5px 10px;
1.597     albertel 6403: }
1.795     www      6404: 
1.936     bisitz   6405: div.LC_grade_show_user_odd_row {
1.941     bisitz   6406: /*  border-left: 5px solid #000000; */
                   6407: }
                   6408: 
                   6409: div.LC_grade_show_user div.LC_Box {
                   6410:   margin-right: 50px;
1.597     albertel 6411: }
                   6412: 
                   6413: div.LC_grade_submissions,
                   6414: div.LC_grade_message_center,
1.936     bisitz   6415: div.LC_grade_info_links {
1.597     albertel 6416:   margin: 5px;
                   6417:   width: 99%;
                   6418:   background: #FFFFFF;
                   6419: }
1.795     www      6420: 
1.597     albertel 6421: div.LC_grade_submissions_header,
1.936     bisitz   6422: div.LC_grade_message_center_header {
1.705     tempelho 6423:   font-weight: bold;
                   6424:   font-size: large;
1.597     albertel 6425: }
1.795     www      6426: 
1.597     albertel 6427: div.LC_grade_submissions_body,
1.936     bisitz   6428: div.LC_grade_message_center_body {
1.597     albertel 6429:   border: 1px solid black;
                   6430:   width: 99%;
                   6431:   background: #FFFFFF;
                   6432: }
1.795     www      6433: 
1.613     albertel 6434: table.LC_scantron_action {
                   6435:   width: 100%;
                   6436: }
1.795     www      6437: 
1.613     albertel 6438: table.LC_scantron_action tr th {
1.698     harmsja  6439:   font-weight:bold;
                   6440:   font-style:normal;
1.613     albertel 6441: }
1.795     www      6442: 
1.779     bisitz   6443: .LC_edit_problem_header,
1.614     albertel 6444: div.LC_edit_problem_footer {
1.705     tempelho 6445:   font-weight: normal;
                   6446:   font-size:  medium;
1.602     albertel 6447:   margin: 2px;
1.1060    bisitz   6448:   background-color: $sidebg;
1.600     albertel 6449: }
1.795     www      6450: 
1.600     albertel 6451: div.LC_edit_problem_header,
1.602     albertel 6452: div.LC_edit_problem_header div,
1.614     albertel 6453: div.LC_edit_problem_footer,
                   6454: div.LC_edit_problem_footer div,
1.602     albertel 6455: div.LC_edit_problem_editxml_header,
                   6456: div.LC_edit_problem_editxml_header div {
1.600     albertel 6457:   margin-top: 5px;
                   6458: }
1.795     www      6459: 
1.600     albertel 6460: div.LC_edit_problem_header_title {
1.705     tempelho 6461:   font-weight: bold;
                   6462:   font-size: larger;
1.602     albertel 6463:   background: $tabbg;
                   6464:   padding: 3px;
1.1060    bisitz   6465:   margin: 0 0 5px 0;
1.602     albertel 6466: }
1.795     www      6467: 
1.602     albertel 6468: table.LC_edit_problem_header_title {
                   6469:   width: 100%;
1.600     albertel 6470:   background: $tabbg;
1.602     albertel 6471: }
                   6472: 
                   6473: div.LC_edit_problem_discards {
                   6474:   float: left;
                   6475:   padding-bottom: 5px;
                   6476: }
1.795     www      6477: 
1.602     albertel 6478: div.LC_edit_problem_saves {
                   6479:   float: right;
                   6480:   padding-bottom: 5px;
1.600     albertel 6481: }
1.795     www      6482: 
1.911     bisitz   6483: img.stift {
1.803     bisitz   6484:   border-width: 0;
                   6485:   vertical-align: middle;
1.677     riegler  6486: }
1.680     riegler  6487: 
1.923     bisitz   6488: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6489:   vertical-align: top;
1.777     tempelho 6490: }
1.795     www      6491: 
1.716     raeburn  6492: div.LC_createcourse {
1.911     bisitz   6493:   margin: 10px 10px 10px 10px;
1.716     raeburn  6494: }
                   6495: 
1.917     raeburn  6496: .LC_dccid {
                   6497:   margin: 0.2em 0 0 0;
                   6498:   padding: 0;
                   6499:   font-size: 90%;
                   6500:   display:none;
                   6501: }
                   6502: 
1.897     wenzelju 6503: ol.LC_primary_menu a:hover,
1.721     harmsja  6504: ol#LC_MenuBreadcrumbs a:hover,
                   6505: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6506: ul#LC_secondary_menu a:hover,
1.721     harmsja  6507: .LC_FormSectionClearButton input:hover
1.795     www      6508: ul.LC_TabContent   li:hover a {
1.952     onken    6509:   color:$button_hover;
1.911     bisitz   6510:   text-decoration:none;
1.693     droeschl 6511: }
                   6512: 
1.779     bisitz   6513: h1 {
1.911     bisitz   6514:   padding: 0;
                   6515:   line-height:130%;
1.693     droeschl 6516: }
1.698     harmsja  6517: 
1.911     bisitz   6518: h2,
                   6519: h3,
                   6520: h4,
                   6521: h5,
                   6522: h6 {
                   6523:   margin: 5px 0 5px 0;
                   6524:   padding: 0;
                   6525:   line-height:130%;
1.693     droeschl 6526: }
1.795     www      6527: 
                   6528: .LC_hcell {
1.911     bisitz   6529:   padding:3px 15px 3px 15px;
                   6530:   margin: 0;
                   6531:   background-color:$tabbg;
                   6532:   color:$fontmenu;
                   6533:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6534: }
1.795     www      6535: 
1.840     bisitz   6536: .LC_Box > .LC_hcell {
1.911     bisitz   6537:   margin: 0 -10px 10px -10px;
1.835     bisitz   6538: }
                   6539: 
1.721     harmsja  6540: .LC_noBorder {
1.911     bisitz   6541:   border: 0;
1.698     harmsja  6542: }
1.693     droeschl 6543: 
1.721     harmsja  6544: .LC_FormSectionClearButton input {
1.911     bisitz   6545:   background-color:transparent;
                   6546:   border: none;
                   6547:   cursor:pointer;
                   6548:   text-decoration:underline;
1.693     droeschl 6549: }
1.763     bisitz   6550: 
                   6551: .LC_help_open_topic {
1.911     bisitz   6552:   color: #FFFFFF;
                   6553:   background-color: #EEEEFF;
                   6554:   margin: 1px;
                   6555:   padding: 4px;
                   6556:   border: 1px solid #000033;
                   6557:   white-space: nowrap;
                   6558:   /* vertical-align: middle; */
1.759     neumanie 6559: }
1.693     droeschl 6560: 
1.911     bisitz   6561: dl,
                   6562: ul,
                   6563: div,
                   6564: fieldset {
                   6565:   margin: 10px 10px 10px 0;
                   6566:   /* overflow: hidden; */
1.693     droeschl 6567: }
1.795     www      6568: 
1.838     bisitz   6569: fieldset > legend {
1.911     bisitz   6570:   font-weight: bold;
                   6571:   padding: 0 5px 0 5px;
1.838     bisitz   6572: }
                   6573: 
1.813     bisitz   6574: #LC_nav_bar {
1.911     bisitz   6575:   float: left;
1.995     raeburn  6576:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6577:   margin: 0 0 2px 0;
1.807     droeschl 6578: }
                   6579: 
1.916     droeschl 6580: #LC_realm {
                   6581:   margin: 0.2em 0 0 0;
                   6582:   padding: 0;
                   6583:   font-weight: bold;
                   6584:   text-align: center;
1.995     raeburn  6585:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6586: }
                   6587: 
1.911     bisitz   6588: #LC_nav_bar em {
                   6589:   font-weight: bold;
                   6590:   font-style: normal;
1.807     droeschl 6591: }
                   6592: 
1.897     wenzelju 6593: ol.LC_primary_menu {
1.911     bisitz   6594:   float: right;
1.934     droeschl 6595:   margin: 0;
1.1076    raeburn  6596:   padding: 0;
1.995     raeburn  6597:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6598: }
                   6599: 
1.852     droeschl 6600: ol#LC_PathBreadcrumbs {
1.911     bisitz   6601:   margin: 0;
1.693     droeschl 6602: }
                   6603: 
1.897     wenzelju 6604: ol.LC_primary_menu li {
1.1076    raeburn  6605:   color: RGB(80, 80, 80);
                   6606:   vertical-align: middle;
                   6607:   text-align: left;
                   6608:   list-style: none;
                   6609:   float: left;
                   6610: }
                   6611: 
                   6612: ol.LC_primary_menu li a {
                   6613:   display: block;
                   6614:   margin: 0;
                   6615:   padding: 0 5px 0 10px;
                   6616:   text-decoration: none;
                   6617: }
                   6618: 
                   6619: ol.LC_primary_menu li ul {
                   6620:   display: none;
                   6621:   width: 10em;
                   6622:   background-color: $data_table_light;
                   6623: }
                   6624: 
                   6625: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6626:   display: block;
                   6627:   position: absolute;
                   6628:   margin: 0;
                   6629:   padding: 0;
1.1078    raeburn  6630:   z-index: 2;
1.1076    raeburn  6631: }
                   6632: 
                   6633: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6634:   font-size: 90%;
1.911     bisitz   6635:   vertical-align: top;
1.1076    raeburn  6636:   float: none;
1.1079    raeburn  6637:   border-left: 1px solid black;
                   6638:   border-right: 1px solid black;
1.1076    raeburn  6639: }
                   6640: 
                   6641: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1078    raeburn  6642:   background-color:$data_table_light;
1.1076    raeburn  6643: }
                   6644: 
                   6645: ol.LC_primary_menu li li a:hover {
                   6646:    color:$button_hover;
                   6647:    background-color:$data_table_dark;
1.693     droeschl 6648: }
                   6649: 
1.897     wenzelju 6650: ol.LC_primary_menu li img {
1.911     bisitz   6651:   vertical-align: bottom;
1.934     droeschl 6652:   height: 1.1em;
1.1077    raeburn  6653:   margin: 0.2em 0 0 0;
1.693     droeschl 6654: }
                   6655: 
1.897     wenzelju 6656: ol.LC_primary_menu a {
1.911     bisitz   6657:   color: RGB(80, 80, 80);
                   6658:   text-decoration: none;
1.693     droeschl 6659: }
1.795     www      6660: 
1.949     droeschl 6661: ol.LC_primary_menu a.LC_new_message {
                   6662:   font-weight:bold;
                   6663:   color: darkred;
                   6664: }
                   6665: 
1.975     raeburn  6666: ol.LC_docs_parameters {
                   6667:   margin-left: 0;
                   6668:   padding: 0;
                   6669:   list-style: none;
                   6670: }
                   6671: 
                   6672: ol.LC_docs_parameters li {
                   6673:   margin: 0;
                   6674:   padding-right: 20px;
                   6675:   display: inline;
                   6676: }
                   6677: 
1.976     raeburn  6678: ol.LC_docs_parameters li:before {
                   6679:   content: "\\002022 \\0020";
                   6680: }
                   6681: 
                   6682: li.LC_docs_parameters_title {
                   6683:   font-weight: bold;
                   6684: }
                   6685: 
                   6686: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6687:   content: "";
                   6688: }
                   6689: 
1.897     wenzelju 6690: ul#LC_secondary_menu {
1.1107    raeburn  6691:   clear: right;
1.911     bisitz   6692:   color: $fontmenu;
                   6693:   background: $tabbg;
                   6694:   list-style: none;
                   6695:   padding: 0;
                   6696:   margin: 0;
                   6697:   width: 100%;
1.995     raeburn  6698:   text-align: left;
1.1107    raeburn  6699:   float: left;
1.808     droeschl 6700: }
                   6701: 
1.897     wenzelju 6702: ul#LC_secondary_menu li {
1.911     bisitz   6703:   font-weight: bold;
                   6704:   line-height: 1.8em;
1.1107    raeburn  6705:   border-right: 1px solid black;
                   6706:   float: left;
                   6707: }
                   6708: 
                   6709: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6710:   background-color: $data_table_light;
                   6711: }
                   6712: 
                   6713: ul#LC_secondary_menu li a {
1.911     bisitz   6714:   padding: 0 0.8em;
1.1107    raeburn  6715: }
                   6716: 
                   6717: ul#LC_secondary_menu li ul {
                   6718:   display: none;
                   6719: }
                   6720: 
                   6721: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6722:   display: block;
                   6723:   position: absolute;
                   6724:   margin: 0;
                   6725:   padding: 0;
                   6726:   list-style:none;
                   6727:   float: none;
                   6728:   background-color: $data_table_light;
                   6729:   z-index: 2;
                   6730:   margin-left: -1px;
                   6731: }
                   6732: 
                   6733: ul#LC_secondary_menu li ul li {
                   6734:   font-size: 90%;
                   6735:   vertical-align: top;
                   6736:   border-left: 1px solid black;
1.911     bisitz   6737:   border-right: 1px solid black;
1.1119    raeburn  6738:   background-color: $data_table_light;
1.1107    raeburn  6739:   list-style:none;
                   6740:   float: none;
                   6741: }
                   6742: 
                   6743: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6744:   background-color: $data_table_dark;
1.807     droeschl 6745: }
                   6746: 
1.847     tempelho 6747: ul.LC_TabContent {
1.911     bisitz   6748:   display:block;
                   6749:   background: $sidebg;
                   6750:   border-bottom: solid 1px $lg_border_color;
                   6751:   list-style:none;
1.1020    raeburn  6752:   margin: -1px -10px 0 -10px;
1.911     bisitz   6753:   padding: 0;
1.693     droeschl 6754: }
                   6755: 
1.795     www      6756: ul.LC_TabContent li,
                   6757: ul.LC_TabContentBigger li {
1.911     bisitz   6758:   float:left;
1.741     harmsja  6759: }
1.795     www      6760: 
1.897     wenzelju 6761: ul#LC_secondary_menu li a {
1.911     bisitz   6762:   color: $fontmenu;
                   6763:   text-decoration: none;
1.693     droeschl 6764: }
1.795     www      6765: 
1.721     harmsja  6766: ul.LC_TabContent {
1.952     onken    6767:   min-height:20px;
1.721     harmsja  6768: }
1.795     www      6769: 
                   6770: ul.LC_TabContent li {
1.911     bisitz   6771:   vertical-align:middle;
1.959     onken    6772:   padding: 0 16px 0 10px;
1.911     bisitz   6773:   background-color:$tabbg;
                   6774:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6775:   border-left: solid 1px $font;
1.721     harmsja  6776: }
1.795     www      6777: 
1.847     tempelho 6778: ul.LC_TabContent .right {
1.911     bisitz   6779:   float:right;
1.847     tempelho 6780: }
                   6781: 
1.911     bisitz   6782: ul.LC_TabContent li a,
                   6783: ul.LC_TabContent li {
                   6784:   color:rgb(47,47,47);
                   6785:   text-decoration:none;
                   6786:   font-size:95%;
                   6787:   font-weight:bold;
1.952     onken    6788:   min-height:20px;
                   6789: }
                   6790: 
1.959     onken    6791: ul.LC_TabContent li a:hover,
                   6792: ul.LC_TabContent li a:focus {
1.952     onken    6793:   color: $button_hover;
1.959     onken    6794:   background:none;
                   6795:   outline:none;
1.952     onken    6796: }
                   6797: 
                   6798: ul.LC_TabContent li:hover {
                   6799:   color: $button_hover;
                   6800:   cursor:pointer;
1.721     harmsja  6801: }
1.795     www      6802: 
1.911     bisitz   6803: ul.LC_TabContent li.active {
1.952     onken    6804:   color: $font;
1.911     bisitz   6805:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6806:   border-bottom:solid 1px #FFFFFF;
                   6807:   cursor: default;
1.744     ehlerst  6808: }
1.795     www      6809: 
1.959     onken    6810: ul.LC_TabContent li.active a {
                   6811:   color:$font;
                   6812:   background:#FFFFFF;
                   6813:   outline: none;
                   6814: }
1.1047    raeburn  6815: 
                   6816: ul.LC_TabContent li.goback {
                   6817:   float: left;
                   6818:   border-left: none;
                   6819: }
                   6820: 
1.870     tempelho 6821: #maincoursedoc {
1.911     bisitz   6822:   clear:both;
1.870     tempelho 6823: }
                   6824: 
                   6825: ul.LC_TabContentBigger {
1.911     bisitz   6826:   display:block;
                   6827:   list-style:none;
                   6828:   padding: 0;
1.870     tempelho 6829: }
                   6830: 
1.795     www      6831: ul.LC_TabContentBigger li {
1.911     bisitz   6832:   vertical-align:bottom;
                   6833:   height: 30px;
                   6834:   font-size:110%;
                   6835:   font-weight:bold;
                   6836:   color: #737373;
1.841     tempelho 6837: }
                   6838: 
1.957     onken    6839: ul.LC_TabContentBigger li.active {
                   6840:   position: relative;
                   6841:   top: 1px;
                   6842: }
                   6843: 
1.870     tempelho 6844: ul.LC_TabContentBigger li a {
1.911     bisitz   6845:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6846:   height: 30px;
                   6847:   line-height: 30px;
                   6848:   text-align: center;
                   6849:   display: block;
                   6850:   text-decoration: none;
1.958     onken    6851:   outline: none;  
1.741     harmsja  6852: }
1.795     www      6853: 
1.870     tempelho 6854: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6855:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6856:   color:$font;
1.744     ehlerst  6857: }
1.795     www      6858: 
1.870     tempelho 6859: ul.LC_TabContentBigger li b {
1.911     bisitz   6860:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6861:   display: block;
                   6862:   float: left;
                   6863:   padding: 0 30px;
1.957     onken    6864:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6865: }
                   6866: 
1.956     onken    6867: ul.LC_TabContentBigger li:hover b {
                   6868:   color:$button_hover;
                   6869: }
                   6870: 
1.870     tempelho 6871: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6872:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6873:   color:$font;
1.957     onken    6874:   border: 0;
1.741     harmsja  6875: }
1.693     droeschl 6876: 
1.870     tempelho 6877: 
1.862     bisitz   6878: ul.LC_CourseBreadcrumbs {
                   6879:   background: $sidebg;
1.1020    raeburn  6880:   height: 2em;
1.862     bisitz   6881:   padding-left: 10px;
1.1020    raeburn  6882:   margin: 0;
1.862     bisitz   6883:   list-style-position: inside;
                   6884: }
                   6885: 
1.911     bisitz   6886: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6887: ol#LC_PathBreadcrumbs {
1.911     bisitz   6888:   padding-left: 10px;
                   6889:   margin: 0;
1.933     droeschl 6890:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6891: }
                   6892: 
1.911     bisitz   6893: ol#LC_MenuBreadcrumbs li,
                   6894: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6895: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6896:   display: inline;
1.933     droeschl 6897:   white-space: normal;  
1.693     droeschl 6898: }
                   6899: 
1.823     bisitz   6900: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6901: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6902:   text-decoration: none;
                   6903:   font-size:90%;
1.693     droeschl 6904: }
1.795     www      6905: 
1.969     droeschl 6906: ol#LC_MenuBreadcrumbs h1 {
                   6907:   display: inline;
                   6908:   font-size: 90%;
                   6909:   line-height: 2.5em;
                   6910:   margin: 0;
                   6911:   padding: 0;
                   6912: }
                   6913: 
1.795     www      6914: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6915:   text-decoration:none;
                   6916:   font-size:100%;
                   6917:   font-weight:bold;
1.693     droeschl 6918: }
1.795     www      6919: 
1.840     bisitz   6920: .LC_Box {
1.911     bisitz   6921:   border: solid 1px $lg_border_color;
                   6922:   padding: 0 10px 10px 10px;
1.746     neumanie 6923: }
1.795     www      6924: 
1.1020    raeburn  6925: .LC_DocsBox {
                   6926:   border: solid 1px $lg_border_color;
                   6927:   padding: 0 0 10px 10px;
                   6928: }
                   6929: 
1.795     www      6930: .LC_AboutMe_Image {
1.911     bisitz   6931:   float:left;
                   6932:   margin-right:10px;
1.747     neumanie 6933: }
1.795     www      6934: 
                   6935: .LC_Clear_AboutMe_Image {
1.911     bisitz   6936:   clear:left;
1.747     neumanie 6937: }
1.795     www      6938: 
1.721     harmsja  6939: dl.LC_ListStyleClean dt {
1.911     bisitz   6940:   padding-right: 5px;
                   6941:   display: table-header-group;
1.693     droeschl 6942: }
                   6943: 
1.721     harmsja  6944: dl.LC_ListStyleClean dd {
1.911     bisitz   6945:   display: table-row;
1.693     droeschl 6946: }
                   6947: 
1.721     harmsja  6948: .LC_ListStyleClean,
                   6949: .LC_ListStyleSimple,
                   6950: .LC_ListStyleNormal,
1.795     www      6951: .LC_ListStyleSpecial {
1.911     bisitz   6952:   /* display:block; */
                   6953:   list-style-position: inside;
                   6954:   list-style-type: none;
                   6955:   overflow: hidden;
                   6956:   padding: 0;
1.693     droeschl 6957: }
                   6958: 
1.721     harmsja  6959: .LC_ListStyleSimple li,
                   6960: .LC_ListStyleSimple dd,
                   6961: .LC_ListStyleNormal li,
                   6962: .LC_ListStyleNormal dd,
                   6963: .LC_ListStyleSpecial li,
1.795     www      6964: .LC_ListStyleSpecial dd {
1.911     bisitz   6965:   margin: 0;
                   6966:   padding: 5px 5px 5px 10px;
                   6967:   clear: both;
1.693     droeschl 6968: }
                   6969: 
1.721     harmsja  6970: .LC_ListStyleClean li,
                   6971: .LC_ListStyleClean dd {
1.911     bisitz   6972:   padding-top: 0;
                   6973:   padding-bottom: 0;
1.693     droeschl 6974: }
                   6975: 
1.721     harmsja  6976: .LC_ListStyleSimple dd,
1.795     www      6977: .LC_ListStyleSimple li {
1.911     bisitz   6978:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6979: }
                   6980: 
1.721     harmsja  6981: .LC_ListStyleSpecial li,
                   6982: .LC_ListStyleSpecial dd {
1.911     bisitz   6983:   list-style-type: none;
                   6984:   background-color: RGB(220, 220, 220);
                   6985:   margin-bottom: 4px;
1.693     droeschl 6986: }
                   6987: 
1.721     harmsja  6988: table.LC_SimpleTable {
1.911     bisitz   6989:   margin:5px;
                   6990:   border:solid 1px $lg_border_color;
1.795     www      6991: }
1.693     droeschl 6992: 
1.721     harmsja  6993: table.LC_SimpleTable tr {
1.911     bisitz   6994:   padding: 0;
                   6995:   border:solid 1px $lg_border_color;
1.693     droeschl 6996: }
1.795     www      6997: 
                   6998: table.LC_SimpleTable thead {
1.911     bisitz   6999:   background:rgb(220,220,220);
1.693     droeschl 7000: }
                   7001: 
1.721     harmsja  7002: div.LC_columnSection {
1.911     bisitz   7003:   display: block;
                   7004:   clear: both;
                   7005:   overflow: hidden;
                   7006:   margin: 0;
1.693     droeschl 7007: }
                   7008: 
1.721     harmsja  7009: div.LC_columnSection>* {
1.911     bisitz   7010:   float: left;
                   7011:   margin: 10px 20px 10px 0;
                   7012:   overflow:hidden;
1.693     droeschl 7013: }
1.721     harmsja  7014: 
1.795     www      7015: table em {
1.911     bisitz   7016:   font-weight: bold;
                   7017:   font-style: normal;
1.748     schulted 7018: }
1.795     www      7019: 
1.779     bisitz   7020: table.LC_tableBrowseRes,
1.795     www      7021: table.LC_tableOfContent {
1.911     bisitz   7022:   border:none;
                   7023:   border-spacing: 1px;
                   7024:   padding: 3px;
                   7025:   background-color: #FFFFFF;
                   7026:   font-size: 90%;
1.753     droeschl 7027: }
1.789     droeschl 7028: 
1.911     bisitz   7029: table.LC_tableOfContent {
                   7030:   border-collapse: collapse;
1.789     droeschl 7031: }
                   7032: 
1.771     droeschl 7033: table.LC_tableBrowseRes a,
1.768     schulted 7034: table.LC_tableOfContent a {
1.911     bisitz   7035:   background-color: transparent;
                   7036:   text-decoration: none;
1.753     droeschl 7037: }
                   7038: 
1.795     www      7039: table.LC_tableOfContent img {
1.911     bisitz   7040:   border: none;
                   7041:   height: 1.3em;
                   7042:   vertical-align: text-bottom;
                   7043:   margin-right: 0.3em;
1.753     droeschl 7044: }
1.757     schulted 7045: 
1.795     www      7046: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7047:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7048: }
                   7049: 
1.795     www      7050: a#LC_content_toolbar_everything {
1.911     bisitz   7051:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7052: }
                   7053: 
1.795     www      7054: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7055:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7056: }
                   7057: 
1.795     www      7058: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7059:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7060: }
                   7061: 
1.795     www      7062: a#LC_content_toolbar_changefolder {
1.911     bisitz   7063:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7064: }
                   7065: 
1.795     www      7066: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7067:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7068: }
                   7069: 
1.1043    raeburn  7070: a#LC_content_toolbar_edittoplevel {
                   7071:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7072: }
                   7073: 
1.795     www      7074: ul#LC_toolbar li a:hover {
1.911     bisitz   7075:   background-position: bottom center;
1.757     schulted 7076: }
                   7077: 
1.795     www      7078: ul#LC_toolbar {
1.911     bisitz   7079:   padding: 0;
                   7080:   margin: 2px;
                   7081:   list-style:none;
                   7082:   position:relative;
                   7083:   background-color:white;
1.1082    raeburn  7084:   overflow: auto;
1.757     schulted 7085: }
                   7086: 
1.795     www      7087: ul#LC_toolbar li {
1.911     bisitz   7088:   border:1px solid white;
                   7089:   padding: 0;
                   7090:   margin: 0;
                   7091:   float: left;
                   7092:   display:inline;
                   7093:   vertical-align:middle;
1.1082    raeburn  7094:   white-space: nowrap;
1.911     bisitz   7095: }
1.757     schulted 7096: 
1.783     amueller 7097: 
1.795     www      7098: a.LC_toolbarItem {
1.911     bisitz   7099:   display:block;
                   7100:   padding: 0;
                   7101:   margin: 0;
                   7102:   height: 32px;
                   7103:   width: 32px;
                   7104:   color:white;
                   7105:   border: none;
                   7106:   background-repeat:no-repeat;
                   7107:   background-color:transparent;
1.757     schulted 7108: }
                   7109: 
1.915     droeschl 7110: ul.LC_funclist {
                   7111:     margin: 0;
                   7112:     padding: 0.5em 1em 0.5em 0;
                   7113: }
                   7114: 
1.933     droeschl 7115: ul.LC_funclist > li:first-child {
                   7116:     font-weight:bold; 
                   7117:     margin-left:0.8em;
                   7118: }
                   7119: 
1.915     droeschl 7120: ul.LC_funclist + ul.LC_funclist {
                   7121:     /* 
                   7122:        left border as a seperator if we have more than
                   7123:        one list 
                   7124:     */
                   7125:     border-left: 1px solid $sidebg;
                   7126:     /* 
                   7127:        this hides the left border behind the border of the 
                   7128:        outer box if element is wrapped to the next 'line' 
                   7129:     */
                   7130:     margin-left: -1px;
                   7131: }
                   7132: 
1.843     bisitz   7133: ul.LC_funclist li {
1.915     droeschl 7134:   display: inline;
1.782     bisitz   7135:   white-space: nowrap;
1.915     droeschl 7136:   margin: 0 0 0 25px;
                   7137:   line-height: 150%;
1.782     bisitz   7138: }
                   7139: 
1.974     wenzelju 7140: .LC_hidden {
                   7141:   display: none;
                   7142: }
                   7143: 
1.1030    www      7144: .LCmodal-overlay {
                   7145: 		position:fixed;
                   7146: 		top:0;
                   7147: 		right:0;
                   7148: 		bottom:0;
                   7149: 		left:0;
                   7150: 		height:100%;
                   7151: 		width:100%;
                   7152: 		margin:0;
                   7153: 		padding:0;
                   7154: 		background:#999;
                   7155: 		opacity:.75;
                   7156: 		filter: alpha(opacity=75);
                   7157: 		-moz-opacity: 0.75;
                   7158: 		z-index:101;
                   7159: }
                   7160: 
                   7161: * html .LCmodal-overlay {   
                   7162: 		position: absolute;
                   7163: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7164: }
                   7165: 
                   7166: .LCmodal-window {
                   7167: 		position:fixed;
                   7168: 		top:50%;
                   7169: 		left:50%;
                   7170: 		margin:0;
                   7171: 		padding:0;
                   7172: 		z-index:102;
                   7173: 	}
                   7174: 
                   7175: * html .LCmodal-window {
                   7176: 		position:absolute;
                   7177: }
                   7178: 
                   7179: .LCclose-window {
                   7180: 		position:absolute;
                   7181: 		width:32px;
                   7182: 		height:32px;
                   7183: 		right:8px;
                   7184: 		top:8px;
                   7185: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7186: 		text-indent:-99999px;
                   7187: 		overflow:hidden;
                   7188: 		cursor:pointer;
                   7189: }
                   7190: 
1.1100    raeburn  7191: /*
                   7192:   styles used by TTH when "Default set of options to pass to tth/m
                   7193:   when converting TeX" in course settings has been set
                   7194: 
                   7195:   option passed: -t
                   7196: 
                   7197: */
                   7198: 
                   7199: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7200: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7201: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7202: td div.norm {line-height:normal;}
                   7203: 
                   7204: /*
                   7205:   option passed -y3
                   7206: */
                   7207: 
                   7208: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7209: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7210: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7211: 
1.343     albertel 7212: END
                   7213: }
                   7214: 
1.306     albertel 7215: =pod
                   7216: 
                   7217: =item * &headtag()
                   7218: 
                   7219: Returns a uniform footer for LON-CAPA web pages.
                   7220: 
1.307     albertel 7221: Inputs: $title - optional title for the head
                   7222:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7223:         $args - optional arguments
1.319     albertel 7224:             force_register - if is true call registerurl so the remote is 
                   7225:                              informed
1.415     albertel 7226:             redirect       -> array ref of
                   7227:                                    1- seconds before redirect occurs
                   7228:                                    2- url to redirect to
                   7229:                                    3- whether the side effect should occur
1.315     albertel 7230:                            (side effect of setting 
                   7231:                                $env{'internal.head.redirect'} to the url 
                   7232:                                redirected too)
1.352     albertel 7233:             domain         -> force to color decorate a page for a specific
                   7234:                                domain
                   7235:             function       -> force usage of a specific rolish color scheme
                   7236:             bgcolor        -> override the default page bgcolor
1.460     albertel 7237:             no_auto_mt_title
                   7238:                            -> prevent &mt()ing the title arg
1.464     albertel 7239: 
1.306     albertel 7240: =cut
                   7241: 
                   7242: sub headtag {
1.313     albertel 7243:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7244:     
1.363     albertel 7245:     my $function = $args->{'function'} || &get_users_function();
                   7246:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7247:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 7248:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7249: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7250: 		   #time(),
1.418     albertel 7251: 		   $env{'environment.color.timestamp'},
1.363     albertel 7252: 		   $function,$domain,$bgcolor);
                   7253: 
1.369     www      7254:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7255: 
1.308     albertel 7256:     my $result =
                   7257: 	'<head>'.
1.461     albertel 7258: 	&font_settings();
1.319     albertel 7259: 
1.1064    raeburn  7260:     my $inhibitprint = &print_suppression();
                   7261: 
1.461     albertel 7262:     if (!$args->{'frameset'}) {
                   7263: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7264:     }
1.962     droeschl 7265:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7266:         $result .= Apache::lonxml::display_title();
1.319     albertel 7267:     }
1.436     albertel 7268:     if (!$args->{'no_nav_bar'} 
                   7269: 	&& !$args->{'only_body'}
                   7270: 	&& !$args->{'frameset'}) {
                   7271: 	$result .= &help_menu_js();
1.1032    www      7272:         $result.=&modal_window();
1.1038    www      7273:         $result.=&togglebox_script();
1.1034    www      7274:         $result.=&wishlist_window();
1.1041    www      7275:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7276:     } else {
                   7277:         if ($args->{'add_modal'}) {
                   7278:            $result.=&modal_window();
                   7279:         }
                   7280:         if ($args->{'add_wishlist'}) {
                   7281:            $result.=&wishlist_window();
                   7282:         }
1.1038    www      7283:         if ($args->{'add_togglebox'}) {
                   7284:            $result.=&togglebox_script();
                   7285:         }
1.1041    www      7286:         if ($args->{'add_progressbar'}) {
                   7287:            $result.=&LCprogressbarUpdate_script();
                   7288:         }
1.436     albertel 7289:     }
1.314     albertel 7290:     if (ref($args->{'redirect'})) {
1.414     albertel 7291: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7292: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7293: 	if (!$inhibit_continue) {
                   7294: 	    $env{'internal.head.redirect'} = $url;
                   7295: 	}
1.313     albertel 7296: 	$result.=<<ADDMETA
                   7297: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7298: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7299: ADDMETA
                   7300:     }
1.306     albertel 7301:     if (!defined($title)) {
                   7302: 	$title = 'The LearningOnline Network with CAPA';
                   7303:     }
1.460     albertel 7304:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7305:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7306: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7307:         .$inhibitprint
1.414     albertel 7308: 	.$head_extra;
1.962     droeschl 7309:     return $result.'</head>';
1.306     albertel 7310: }
                   7311: 
                   7312: =pod
                   7313: 
1.340     albertel 7314: =item * &font_settings()
                   7315: 
                   7316: Returns neccessary <meta> to set the proper encoding
                   7317: 
                   7318: Inputs: none
                   7319: 
                   7320: =cut
                   7321: 
                   7322: sub font_settings {
                   7323:     my $headerstring='';
1.647     www      7324:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 7325: 	$headerstring.=
                   7326: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   7327:     }
                   7328:     return $headerstring;
                   7329: }
                   7330: 
1.341     albertel 7331: =pod
                   7332: 
1.1064    raeburn  7333: =item * &print_suppression()
                   7334: 
                   7335: In course context returns css which causes the body to be blank when media="print",
                   7336: if printout generation is unavailable for the current resource.
                   7337: 
                   7338: This could be because:
                   7339: 
                   7340: (a) printstartdate is in the future
                   7341: 
                   7342: (b) printenddate is in the past
                   7343: 
                   7344: (c) there is an active exam block with "printout"
                   7345: functionality blocked
                   7346: 
                   7347: Users with pav, pfo or evb privileges are exempt.
                   7348: 
                   7349: Inputs: none
                   7350: 
                   7351: =cut
                   7352: 
                   7353: 
                   7354: sub print_suppression {
                   7355:     my $noprint;
                   7356:     if ($env{'request.course.id'}) {
                   7357:         my $scope = $env{'request.course.id'};
                   7358:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7359:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7360:             return;
                   7361:         }
                   7362:         if ($env{'request.course.sec'} ne '') {
                   7363:             $scope .= "/$env{'request.course.sec'}";
                   7364:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7365:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7366:                 return;
1.1064    raeburn  7367:             }
                   7368:         }
                   7369:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7370:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7371:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7372:         if ($blocked) {
                   7373:             my $checkrole = "cm./$cdom/$cnum";
                   7374:             if ($env{'request.course.sec'} ne '') {
                   7375:                 $checkrole .= "/$env{'request.course.sec'}";
                   7376:             }
                   7377:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7378:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7379:                 $noprint = 1;
                   7380:             }
                   7381:         }
                   7382:         unless ($noprint) {
                   7383:             my $symb = &Apache::lonnet::symbread();
                   7384:             if ($symb ne '') {
                   7385:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7386:                 if (ref($navmap)) {
                   7387:                     my $res = $navmap->getBySymb($symb);
                   7388:                     if (ref($res)) {
                   7389:                         if (!$res->resprintable()) {
                   7390:                             $noprint = 1;
                   7391:                         }
                   7392:                     }
                   7393:                 }
                   7394:             }
                   7395:         }
                   7396:         if ($noprint) {
                   7397:             return <<"ENDSTYLE";
                   7398: <style type="text/css" media="print">
                   7399:     body { display:none }
                   7400: </style>
                   7401: ENDSTYLE
                   7402:         }
                   7403:     }
                   7404:     return;
                   7405: }
                   7406: 
                   7407: =pod
                   7408: 
1.341     albertel 7409: =item * &xml_begin()
                   7410: 
                   7411: Returns the needed doctype and <html>
                   7412: 
                   7413: Inputs: none
                   7414: 
                   7415: =cut
                   7416: 
                   7417: sub xml_begin {
                   7418:     my $output='';
                   7419: 
                   7420:     if ($env{'browser.mathml'}) {
                   7421: 	$output='<?xml version="1.0"?>'
                   7422:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7423: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7424:             
                   7425: #	    .'<!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">] >'
                   7426: 	    .'<!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">'
                   7427:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7428: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7429:     } else {
1.849     bisitz   7430: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                   7431:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 7432:     }
                   7433:     return $output;
                   7434: }
1.340     albertel 7435: 
                   7436: =pod
                   7437: 
1.306     albertel 7438: =item * &start_page()
                   7439: 
                   7440: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7441: 
1.648     raeburn  7442: Inputs:
                   7443: 
                   7444: =over 4
                   7445: 
                   7446: $title - optional title for the page
                   7447: 
                   7448: $head_extra - optional extra HTML to incude inside the <head>
                   7449: 
                   7450: $args - additional optional args supported are:
                   7451: 
                   7452: =over 8
                   7453: 
                   7454:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7455:                                     arg on
1.814     bisitz   7456:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7457:              add_entries    -> additional attributes to add to the  <body>
                   7458:              domain         -> force to color decorate a page for a 
1.317     albertel 7459:                                     specific domain
1.648     raeburn  7460:              function       -> force usage of a specific rolish color
1.317     albertel 7461:                                     scheme
1.648     raeburn  7462:              redirect       -> see &headtag()
                   7463:              bgcolor        -> override the default page bg color
                   7464:              js_ready       -> return a string ready for being used in 
1.317     albertel 7465:                                     a javascript writeln
1.648     raeburn  7466:              html_encode    -> return a string ready for being used in 
1.320     albertel 7467:                                     a html attribute
1.648     raeburn  7468:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7469:                                     $forcereg arg
1.648     raeburn  7470:              frameset       -> if true will start with a <frameset>
1.330     albertel 7471:                                     rather than <body>
1.648     raeburn  7472:              skip_phases    -> hash ref of 
1.338     albertel 7473:                                     head -> skip the <html><head> generation
                   7474:                                     body -> skip all <body> generation
1.648     raeburn  7475:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7476:              inherit_jsmath -> when creating popup window in a page,
                   7477:                                     should it have jsmath forced on by the
                   7478:                                     current page
1.867     kalberla 7479:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7480:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7481:              group          -> includes the current group, if page is for a 
                   7482:                                specific group  
1.361     albertel 7483: 
1.648     raeburn  7484: =back
1.460     albertel 7485: 
1.648     raeburn  7486: =back
1.562     albertel 7487: 
1.306     albertel 7488: =cut
                   7489: 
                   7490: sub start_page {
1.309     albertel 7491:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7492:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7493: 
1.315     albertel 7494:     $env{'internal.start_page'}++;
1.1096    raeburn  7495:     my ($result,@advtools);
1.964     droeschl 7496: 
1.338     albertel 7497:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7498:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7499:     }
                   7500:     
                   7501:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7502: 	if ($args->{'frameset'}) {
                   7503: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7504: 						$args->{'add_entries'});
                   7505: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7506:         } else {
                   7507:             $result .=
                   7508:                 &bodytag($title, 
                   7509:                          $args->{'function'},       $args->{'add_entries'},
                   7510:                          $args->{'only_body'},      $args->{'domain'},
                   7511:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  7512:                          $args->{'bgcolor'},        $args,
                   7513:                          \@advtools);
1.831     bisitz   7514:         }
1.330     albertel 7515:     }
1.338     albertel 7516: 
1.315     albertel 7517:     if ($args->{'js_ready'}) {
1.713     kaisler  7518: 		$result = &js_ready($result);
1.315     albertel 7519:     }
1.320     albertel 7520:     if ($args->{'html_encode'}) {
1.713     kaisler  7521: 		$result = &html_encode($result);
                   7522:     }
                   7523: 
1.813     bisitz   7524:     # Preparation for new and consistent functionlist at top of screen
                   7525:     # if ($args->{'functionlist'}) {
                   7526:     #            $result .= &build_functionlist();
                   7527:     #}
                   7528: 
1.964     droeschl 7529:     # Don't add anything more if only_body wanted or in const space
                   7530:     return $result if    $args->{'only_body'} 
                   7531:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7532: 
                   7533:     #Breadcrumbs
1.758     kaisler  7534:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7535: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7536: 		#if any br links exists, add them to the breadcrumbs
                   7537: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7538: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7539: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7540: 			}
                   7541: 		}
1.1096    raeburn  7542:                 # if @advtools array contains items add then to the breadcrumbs
                   7543:                 if (@advtools > 0) {
                   7544:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7545:                 }
1.758     kaisler  7546: 
                   7547: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7548: 		if(exists($args->{'bread_crumbs_component'})){
                   7549: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7550: 		}else{
                   7551: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7552: 		}
1.320     albertel 7553:     }
1.315     albertel 7554:     return $result;
1.306     albertel 7555: }
                   7556: 
                   7557: sub end_page {
1.315     albertel 7558:     my ($args) = @_;
                   7559:     $env{'internal.end_page'}++;
1.330     albertel 7560:     my $result;
1.335     albertel 7561:     if ($args->{'discussion'}) {
                   7562: 	my ($target,$parser);
                   7563: 	if (ref($args->{'discussion'})) {
                   7564: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7565: 				$args->{'discussion'}{'parser'});
                   7566: 	}
                   7567: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7568:     }
1.330     albertel 7569:     if ($args->{'frameset'}) {
                   7570: 	$result .= '</frameset>';
                   7571:     } else {
1.635     raeburn  7572: 	$result .= &endbodytag($args);
1.330     albertel 7573:     }
1.1080    raeburn  7574:     unless ($args->{'notbody'}) {
                   7575:         $result .= "\n</html>";
                   7576:     }
1.330     albertel 7577: 
1.315     albertel 7578:     if ($args->{'js_ready'}) {
1.317     albertel 7579: 	$result = &js_ready($result);
1.315     albertel 7580:     }
1.335     albertel 7581: 
1.320     albertel 7582:     if ($args->{'html_encode'}) {
                   7583: 	$result = &html_encode($result);
                   7584:     }
1.335     albertel 7585: 
1.315     albertel 7586:     return $result;
                   7587: }
                   7588: 
1.1034    www      7589: sub wishlist_window {
                   7590:     return(<<'ENDWISHLIST');
1.1046    raeburn  7591: <script type="text/javascript">
1.1034    www      7592: // <![CDATA[
                   7593: // <!-- BEGIN LON-CAPA Internal
                   7594: function set_wishlistlink(title, path) {
                   7595:     if (!title) {
                   7596:         title = document.title;
                   7597:         title = title.replace(/^LON-CAPA /,'');
                   7598:     }
                   7599:     if (!path) {
                   7600:         path = location.pathname;
                   7601:     }
                   7602:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7603:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7604: }
                   7605: // END LON-CAPA Internal -->
                   7606: // ]]>
                   7607: </script>
                   7608: ENDWISHLIST
                   7609: }
                   7610: 
1.1030    www      7611: sub modal_window {
                   7612:     return(<<'ENDMODAL');
1.1046    raeburn  7613: <script type="text/javascript">
1.1030    www      7614: // <![CDATA[
                   7615: // <!-- BEGIN LON-CAPA Internal
                   7616: var modalWindow = {
                   7617: 	parent:"body",
                   7618: 	windowId:null,
                   7619: 	content:null,
                   7620: 	width:null,
                   7621: 	height:null,
                   7622: 	close:function()
                   7623: 	{
                   7624: 	        $(".LCmodal-window").remove();
                   7625: 	        $(".LCmodal-overlay").remove();
                   7626: 	},
                   7627: 	open:function()
                   7628: 	{
                   7629: 		var modal = "";
                   7630: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7631: 		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;\">";
                   7632: 		modal += this.content;
                   7633: 		modal += "</div>";	
                   7634: 
                   7635: 		$(this.parent).append(modal);
                   7636: 
                   7637: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7638: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7639: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7640: 	}
                   7641: };
1.1031    www      7642: 	var openMyModal = function(source,width,height,scrolling)
1.1030    www      7643: 	{
                   7644: 		modalWindow.windowId = "myModal";
                   7645: 		modalWindow.width = width;
                   7646: 		modalWindow.height = height;
1.1031    www      7647: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
1.1030    www      7648: 		modalWindow.open();
                   7649: 	};	
                   7650: // END LON-CAPA Internal -->
                   7651: // ]]>
                   7652: </script>
                   7653: ENDMODAL
                   7654: }
                   7655: 
                   7656: sub modal_link {
1.1052    www      7657:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
1.1030    www      7658:     unless ($width) { $width=480; }
                   7659:     unless ($height) { $height=400; }
1.1031    www      7660:     unless ($scrolling) { $scrolling='yes'; }
1.1074    raeburn  7661:     my $target_attr;
                   7662:     if (defined($target)) {
                   7663:         $target_attr = 'target="'.$target.'"';
                   7664:     }
                   7665:     return <<"ENDLINK";
                   7666: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
                   7667:            $linktext</a>
                   7668: ENDLINK
1.1030    www      7669: }
                   7670: 
1.1032    www      7671: sub modal_adhoc_script {
                   7672:     my ($funcname,$width,$height,$content)=@_;
                   7673:     return (<<ENDADHOC);
1.1046    raeburn  7674: <script type="text/javascript">
1.1032    www      7675: // <![CDATA[
                   7676:         var $funcname = function()
                   7677:         {
                   7678:                 modalWindow.windowId = "myModal";
                   7679:                 modalWindow.width = $width;
                   7680:                 modalWindow.height = $height;
                   7681:                 modalWindow.content = '$content';
                   7682:                 modalWindow.open();
                   7683:         };  
                   7684: // ]]>
                   7685: </script>
                   7686: ENDADHOC
                   7687: }
                   7688: 
1.1041    www      7689: sub modal_adhoc_inner {
                   7690:     my ($funcname,$width,$height,$content)=@_;
                   7691:     my $innerwidth=$width-20;
                   7692:     $content=&js_ready(
1.1042    www      7693:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1041    www      7694:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
                   7695:                     $content.
                   7696:                  &end_scrollbox().
                   7697:                &end_page()
                   7698:              );
                   7699:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7700: }
                   7701: 
                   7702: sub modal_adhoc_window {
                   7703:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7704:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7705:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7706: }
                   7707: 
                   7708: sub modal_adhoc_launch {
                   7709:     my ($funcname,$width,$height,$content)=@_;
                   7710:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7711: <script type="text/javascript">
                   7712: // <![CDATA[
                   7713: $funcname();
                   7714: // ]]>
                   7715: </script>
                   7716: ENDLAUNCH
                   7717: }
                   7718: 
                   7719: sub modal_adhoc_close {
                   7720:     return (<<ENDCLOSE);
                   7721: <script type="text/javascript">
                   7722: // <![CDATA[
                   7723: modalWindow.close();
                   7724: // ]]>
                   7725: </script>
                   7726: ENDCLOSE
                   7727: }
                   7728: 
1.1038    www      7729: sub togglebox_script {
                   7730:    return(<<ENDTOGGLE);
                   7731: <script type="text/javascript"> 
                   7732: // <![CDATA[
                   7733: function LCtoggleDisplay(id,hidetext,showtext) {
                   7734:    link = document.getElementById(id + "link").childNodes[0];
                   7735:    with (document.getElementById(id).style) {
                   7736:       if (display == "none" ) {
                   7737:           display = "inline";
                   7738:           link.nodeValue = hidetext;
                   7739:         } else {
                   7740:           display = "none";
                   7741:           link.nodeValue = showtext;
                   7742:        }
                   7743:    }
                   7744: }
                   7745: // ]]>
                   7746: </script>
                   7747: ENDTOGGLE
                   7748: }
                   7749: 
1.1039    www      7750: sub start_togglebox {
                   7751:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7752:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7753:     unless ($showtext) { $showtext=&mt('show'); }
                   7754:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7755:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7756:     return &start_data_table().
                   7757:            &start_data_table_header_row().
                   7758:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7759:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7760:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7761:            &end_data_table_header_row().
                   7762:            '<tr id="'.$id.'" style="display:none""><td>';
                   7763: }
                   7764: 
                   7765: sub end_togglebox {
                   7766:     return '</td></tr>'.&end_data_table();
                   7767: }
                   7768: 
1.1041    www      7769: sub LCprogressbar_script {
1.1045    www      7770:    my ($id)=@_;
1.1041    www      7771:    return(<<ENDPROGRESS);
                   7772: <script type="text/javascript">
                   7773: // <![CDATA[
1.1045    www      7774: \$('#progressbar$id').progressbar({
1.1041    www      7775:   value: 0,
                   7776:   change: function(event, ui) {
                   7777:     var newVal = \$(this).progressbar('option', 'value');
                   7778:     \$('.pblabel', this).text(LCprogressTxt);
                   7779:   }
                   7780: });
                   7781: // ]]>
                   7782: </script>
                   7783: ENDPROGRESS
                   7784: }
                   7785: 
                   7786: sub LCprogressbarUpdate_script {
                   7787:    return(<<ENDPROGRESSUPDATE);
                   7788: <style type="text/css">
                   7789: .ui-progressbar { position:relative; }
                   7790: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7791: </style>
                   7792: <script type="text/javascript">
                   7793: // <![CDATA[
1.1045    www      7794: var LCprogressTxt='---';
                   7795: 
                   7796: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7797:    LCprogressTxt=progresstext;
1.1045    www      7798:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7799: }
                   7800: // ]]>
                   7801: </script>
                   7802: ENDPROGRESSUPDATE
                   7803: }
                   7804: 
1.1042    www      7805: my $LClastpercent;
1.1045    www      7806: my $LCidcnt;
                   7807: my $LCcurrentid;
1.1042    www      7808: 
1.1041    www      7809: sub LCprogressbar {
1.1042    www      7810:     my ($r)=(@_);
                   7811:     $LClastpercent=0;
1.1045    www      7812:     $LCidcnt++;
                   7813:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7814:     my $starting=&mt('Starting');
                   7815:     my $content=(<<ENDPROGBAR);
1.1045    www      7816:   <div id="progressbar$LCcurrentid">
1.1041    www      7817:     <span class="pblabel">$starting</span>
                   7818:   </div>
                   7819: ENDPROGBAR
1.1045    www      7820:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7821: }
                   7822: 
                   7823: sub LCprogressbarUpdate {
1.1042    www      7824:     my ($r,$val,$text)=@_;
                   7825:     unless ($val) { 
                   7826:        if ($LClastpercent) {
                   7827:            $val=$LClastpercent;
                   7828:        } else {
                   7829:            $val=0;
                   7830:        }
                   7831:     }
1.1041    www      7832:     if ($val<0) { $val=0; }
                   7833:     if ($val>100) { $val=0; }
1.1042    www      7834:     $LClastpercent=$val;
1.1041    www      7835:     unless ($text) { $text=$val.'%'; }
                   7836:     $text=&js_ready($text);
1.1044    www      7837:     &r_print($r,<<ENDUPDATE);
1.1041    www      7838: <script type="text/javascript">
                   7839: // <![CDATA[
1.1045    www      7840: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7841: // ]]>
                   7842: </script>
                   7843: ENDUPDATE
1.1035    www      7844: }
                   7845: 
1.1042    www      7846: sub LCprogressbarClose {
                   7847:     my ($r)=@_;
                   7848:     $LClastpercent=0;
1.1044    www      7849:     &r_print($r,<<ENDCLOSE);
1.1042    www      7850: <script type="text/javascript">
                   7851: // <![CDATA[
1.1045    www      7852: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7853: // ]]>
                   7854: </script>
                   7855: ENDCLOSE
1.1044    www      7856: }
                   7857: 
                   7858: sub r_print {
                   7859:     my ($r,$to_print)=@_;
                   7860:     if ($r) {
                   7861:       $r->print($to_print);
                   7862:       $r->rflush();
                   7863:     } else {
                   7864:       print($to_print);
                   7865:     }
1.1042    www      7866: }
                   7867: 
1.320     albertel 7868: sub html_encode {
                   7869:     my ($result) = @_;
                   7870: 
1.322     albertel 7871:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7872:     
                   7873:     return $result;
                   7874: }
1.1044    www      7875: 
1.317     albertel 7876: sub js_ready {
                   7877:     my ($result) = @_;
                   7878: 
1.323     albertel 7879:     $result =~ s/[\n\r]/ /xmsg;
                   7880:     $result =~ s/\\/\\\\/xmsg;
                   7881:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7882:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7883:     
                   7884:     return $result;
                   7885: }
                   7886: 
1.315     albertel 7887: sub validate_page {
                   7888:     if (  exists($env{'internal.start_page'})
1.316     albertel 7889: 	  &&     $env{'internal.start_page'} > 1) {
                   7890: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7891: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7892: 				 $ENV{'request.filename'});
1.315     albertel 7893:     }
                   7894:     if (  exists($env{'internal.end_page'})
1.316     albertel 7895: 	  &&     $env{'internal.end_page'} > 1) {
                   7896: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7897: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7898: 				 $env{'request.filename'});
1.315     albertel 7899:     }
                   7900:     if (     exists($env{'internal.start_page'})
                   7901: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7902: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7903: 				 $env{'request.filename'});
1.315     albertel 7904:     }
                   7905:     if (   ! exists($env{'internal.start_page'})
                   7906: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7907: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7908: 				 $env{'request.filename'});
1.315     albertel 7909:     }
1.306     albertel 7910: }
1.315     albertel 7911: 
1.996     www      7912: 
                   7913: sub start_scrollbox {
1.1075    raeburn  7914:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
1.998     raeburn  7915:     unless ($outerwidth) { $outerwidth='520px'; }
                   7916:     unless ($width) { $width='500px'; }
                   7917:     unless ($height) { $height='200px'; }
1.1075    raeburn  7918:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7919:     if ($id ne '') {
1.1020    raeburn  7920:         $table_id = " id='table_$id'";
                   7921:         $div_id = " id='div_$id'";
1.1018    raeburn  7922:     }
1.1075    raeburn  7923:     if ($bgcolor ne '') {
                   7924:         $tdcol = "background-color: $bgcolor;";
                   7925:     }
                   7926:     return <<"END";
                   7927: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
                   7928: END
1.996     www      7929: }
                   7930: 
                   7931: sub end_scrollbox {
1.1036    www      7932:     return '</div></td></tr></table>';
1.996     www      7933: }
                   7934: 
1.318     albertel 7935: sub simple_error_page {
                   7936:     my ($r,$title,$msg) = @_;
                   7937:     my $page =
                   7938: 	&Apache::loncommon::start_page($title).
1.1097    bisitz   7939: 	'<p class="LC_error">'.&mt($msg).'</p>'.
1.318     albertel 7940: 	&Apache::loncommon::end_page();
                   7941:     if (ref($r)) {
                   7942: 	$r->print($page);
1.327     albertel 7943: 	return;
1.318     albertel 7944:     }
                   7945:     return $page;
                   7946: }
1.347     albertel 7947: 
                   7948: {
1.610     albertel 7949:     my @row_count;
1.961     onken    7950: 
                   7951:     sub start_data_table_count {
                   7952:         unshift(@row_count, 0);
                   7953:         return;
                   7954:     }
                   7955: 
                   7956:     sub end_data_table_count {
                   7957:         shift(@row_count);
                   7958:         return;
                   7959:     }
                   7960: 
1.347     albertel 7961:     sub start_data_table {
1.1018    raeburn  7962: 	my ($add_class,$id) = @_;
1.422     albertel 7963: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  7964:         my $table_id;
                   7965:         if (defined($id)) {
                   7966:             $table_id = ' id="'.$id.'"';
                   7967:         }
1.961     onken    7968: 	&start_data_table_count();
1.1018    raeburn  7969: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 7970:     }
                   7971: 
                   7972:     sub end_data_table {
1.961     onken    7973: 	&end_data_table_count();
1.389     albertel 7974: 	return '</table>'."\n";;
1.347     albertel 7975:     }
                   7976: 
                   7977:     sub start_data_table_row {
1.974     wenzelju 7978: 	my ($add_class, $id) = @_;
1.610     albertel 7979: 	$row_count[0]++;
                   7980: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   7981: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 7982:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7983:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 7984:     }
1.471     banghart 7985:     
                   7986:     sub continue_data_table_row {
1.974     wenzelju 7987: 	my ($add_class, $id) = @_;
1.610     albertel 7988: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 7989: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   7990:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7991:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 7992:     }
1.347     albertel 7993: 
                   7994:     sub end_data_table_row {
1.389     albertel 7995: 	return '</tr>'."\n";;
1.347     albertel 7996:     }
1.367     www      7997: 
1.421     albertel 7998:     sub start_data_table_empty_row {
1.707     bisitz   7999: #	$row_count[0]++;
1.421     albertel 8000: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8001:     }
                   8002: 
                   8003:     sub end_data_table_empty_row {
                   8004: 	return '</tr>'."\n";;
                   8005:     }
                   8006: 
1.367     www      8007:     sub start_data_table_header_row {
1.389     albertel 8008: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8009:     }
                   8010: 
                   8011:     sub end_data_table_header_row {
1.389     albertel 8012: 	return '</tr>'."\n";;
1.367     www      8013:     }
1.890     droeschl 8014: 
                   8015:     sub data_table_caption {
                   8016:         my $caption = shift;
                   8017:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8018:     }
1.347     albertel 8019: }
                   8020: 
1.548     albertel 8021: =pod
                   8022: 
                   8023: =item * &inhibit_menu_check($arg)
                   8024: 
                   8025: Checks for a inhibitmenu state and generates output to preserve it
                   8026: 
                   8027: Inputs:         $arg - can be any of
                   8028:                      - undef - in which case the return value is a string 
                   8029:                                to add  into arguments list of a uri
                   8030:                      - 'input' - in which case the return value is a HTML
                   8031:                                  <form> <input> field of type hidden to
                   8032:                                  preserve the value
                   8033:                      - a url - in which case the return value is the url with
                   8034:                                the neccesary cgi args added to preserve the
                   8035:                                inhibitmenu state
                   8036:                      - a ref to a url - no return value, but the string is
                   8037:                                         updated to include the neccessary cgi
                   8038:                                         args to preserve the inhibitmenu state
                   8039: 
                   8040: =cut
                   8041: 
                   8042: sub inhibit_menu_check {
                   8043:     my ($arg) = @_;
                   8044:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8045:     if ($arg eq 'input') {
                   8046: 	if ($env{'form.inhibitmenu'}) {
                   8047: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8048: 	} else {
                   8049: 	    return
                   8050: 	}
                   8051:     }
                   8052:     if ($env{'form.inhibitmenu'}) {
                   8053: 	if (ref($arg)) {
                   8054: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8055: 	} elsif ($arg eq '') {
                   8056: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8057: 	} else {
                   8058: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8059: 	}
                   8060:     }
                   8061:     if (!ref($arg)) {
                   8062: 	return $arg;
                   8063:     }
                   8064: }
                   8065: 
1.251     albertel 8066: ###############################################
1.182     matthew  8067: 
                   8068: =pod
                   8069: 
1.549     albertel 8070: =back
                   8071: 
                   8072: =head1 User Information Routines
                   8073: 
                   8074: =over 4
                   8075: 
1.405     albertel 8076: =item * &get_users_function()
1.182     matthew  8077: 
                   8078: Used by &bodytag to determine the current users primary role.
                   8079: Returns either 'student','coordinator','admin', or 'author'.
                   8080: 
                   8081: =cut
                   8082: 
                   8083: ###############################################
                   8084: sub get_users_function {
1.815     tempelho 8085:     my $function = 'norole';
1.818     tempelho 8086:     if ($env{'request.role'}=~/^(st)/) {
                   8087:         $function='student';
                   8088:     }
1.907     raeburn  8089:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8090:         $function='coordinator';
                   8091:     }
1.258     albertel 8092:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8093:         $function='admin';
                   8094:     }
1.826     bisitz   8095:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8096:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8097:         $function='author';
                   8098:     }
                   8099:     return $function;
1.54      www      8100: }
1.99      www      8101: 
                   8102: ###############################################
                   8103: 
1.233     raeburn  8104: =pod
                   8105: 
1.821     raeburn  8106: =item * &show_course()
                   8107: 
                   8108: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8109: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8110: 
                   8111: Inputs:
                   8112: None
                   8113: 
                   8114: Outputs:
                   8115: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8116: 
                   8117: =cut
                   8118: 
                   8119: ###############################################
                   8120: sub show_course {
                   8121:     my $course = !$env{'user.adv'};
                   8122:     if (!$env{'user.adv'}) {
                   8123:         foreach my $env (keys(%env)) {
                   8124:             next if ($env !~ m/^user\.priv\./);
                   8125:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8126:                 $course = 0;
                   8127:                 last;
                   8128:             }
                   8129:         }
                   8130:     }
                   8131:     return $course;
                   8132: }
                   8133: 
                   8134: ###############################################
                   8135: 
                   8136: =pod
                   8137: 
1.542     raeburn  8138: =item * &check_user_status()
1.274     raeburn  8139: 
                   8140: Determines current status of supplied role for a
                   8141: specific user. Roles can be active, previous or future.
                   8142: 
                   8143: Inputs: 
                   8144: user's domain, user's username, course's domain,
1.375     raeburn  8145: course's number, optional section ID.
1.274     raeburn  8146: 
                   8147: Outputs:
                   8148: role status: active, previous or future. 
                   8149: 
                   8150: =cut
                   8151: 
                   8152: sub check_user_status {
1.412     raeburn  8153:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8154:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8155:     my @uroles = keys %userinfo;
                   8156:     my $srchstr;
                   8157:     my $active_chk = 'none';
1.412     raeburn  8158:     my $now = time;
1.274     raeburn  8159:     if (@uroles > 0) {
1.908     raeburn  8160:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8161:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8162:         } else {
1.412     raeburn  8163:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8164:         }
                   8165:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8166:             my $role_end = 0;
                   8167:             my $role_start = 0;
                   8168:             $active_chk = 'active';
1.412     raeburn  8169:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8170:                 $role_end = $1;
                   8171:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8172:                     $role_start = $1;
1.274     raeburn  8173:                 }
                   8174:             }
                   8175:             if ($role_start > 0) {
1.412     raeburn  8176:                 if ($now < $role_start) {
1.274     raeburn  8177:                     $active_chk = 'future';
                   8178:                 }
                   8179:             }
                   8180:             if ($role_end > 0) {
1.412     raeburn  8181:                 if ($now > $role_end) {
1.274     raeburn  8182:                     $active_chk = 'previous';
                   8183:                 }
                   8184:             }
                   8185:         }
                   8186:     }
                   8187:     return $active_chk;
                   8188: }
                   8189: 
                   8190: ###############################################
                   8191: 
                   8192: =pod
                   8193: 
1.405     albertel 8194: =item * &get_sections()
1.233     raeburn  8195: 
                   8196: Determines all the sections for a course including
                   8197: sections with students and sections containing other roles.
1.419     raeburn  8198: Incoming parameters: 
                   8199: 
                   8200: 1. domain
                   8201: 2. course number 
                   8202: 3. reference to array containing roles for which sections should 
                   8203: be gathered (optional).
                   8204: 4. reference to array containing status types for which sections 
                   8205: should be gathered (optional).
                   8206: 
                   8207: If the third argument is undefined, sections are gathered for any role. 
                   8208: If the fourth argument is undefined, sections are gathered for any status.
                   8209: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8210:  
1.374     raeburn  8211: Returns section hash (keys are section IDs, values are
                   8212: number of users in each section), subject to the
1.419     raeburn  8213: optional roles filter, optional status filter 
1.233     raeburn  8214: 
                   8215: =cut
                   8216: 
                   8217: ###############################################
                   8218: sub get_sections {
1.419     raeburn  8219:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8220:     if (!defined($cdom) || !defined($cnum)) {
                   8221:         my $cid =  $env{'request.course.id'};
                   8222: 
                   8223: 	return if (!defined($cid));
                   8224: 
                   8225:         $cdom = $env{'course.'.$cid.'.domain'};
                   8226:         $cnum = $env{'course.'.$cid.'.num'};
                   8227:     }
                   8228: 
                   8229:     my %sectioncount;
1.419     raeburn  8230:     my $now = time;
1.240     albertel 8231: 
1.1118    raeburn  8232:     my $check_students = 1;
                   8233:     my $only_students = 0;
                   8234:     if (ref($possible_roles) eq 'ARRAY') {
                   8235:         if (grep(/^st$/,@{$possible_roles})) {
                   8236:             if (@{$possible_roles} == 1) {
                   8237:                 $only_students = 1;
                   8238:             }
                   8239:         } else {
                   8240:             $check_students = 0;
                   8241:         }
                   8242:     }
                   8243: 
                   8244:     if ($check_students) { 
1.276     albertel 8245: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8246: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8247: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8248:         my $start_index = &Apache::loncoursedata::CL_START();
                   8249:         my $end_index = &Apache::loncoursedata::CL_END();
                   8250:         my $status;
1.366     albertel 8251: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8252: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8253: 				                     $data->[$status_index],
                   8254:                                                      $data->[$start_index],
                   8255:                                                      $data->[$end_index]);
                   8256:             if ($stu_status eq 'Active') {
                   8257:                 $status = 'active';
                   8258:             } elsif ($end < $now) {
                   8259:                 $status = 'previous';
                   8260:             } elsif ($start > $now) {
                   8261:                 $status = 'future';
                   8262:             } 
                   8263: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8264:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8265:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8266: 		    $sectioncount{$section}++;
                   8267:                 }
1.240     albertel 8268: 	    }
                   8269: 	}
                   8270:     }
1.1118    raeburn  8271:     if ($only_students) {
                   8272:         return %sectioncount;
                   8273:     }
1.240     albertel 8274:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8275:     foreach my $user (sort(keys(%courseroles))) {
                   8276: 	if ($user !~ /^(\w{2})/) { next; }
                   8277: 	my ($role) = ($user =~ /^(\w{2})/);
                   8278: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8279: 	my ($section,$status);
1.240     albertel 8280: 	if ($role eq 'cr' &&
                   8281: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8282: 	    $section=$1;
                   8283: 	}
                   8284: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8285: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8286:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8287:         if ($end == -1 && $start == -1) {
                   8288:             next; #deleted role
                   8289:         }
                   8290:         if (!defined($possible_status)) { 
                   8291:             $sectioncount{$section}++;
                   8292:         } else {
                   8293:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8294:                 $status = 'active';
                   8295:             } elsif ($end < $now) {
                   8296:                 $status = 'future';
                   8297:             } elsif ($start > $now) {
                   8298:                 $status = 'previous';
                   8299:             }
                   8300:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8301:                 $sectioncount{$section}++;
                   8302:             }
                   8303:         }
1.233     raeburn  8304:     }
1.366     albertel 8305:     return %sectioncount;
1.233     raeburn  8306: }
                   8307: 
1.274     raeburn  8308: ###############################################
1.294     raeburn  8309: 
                   8310: =pod
1.405     albertel 8311: 
                   8312: =item * &get_course_users()
                   8313: 
1.275     raeburn  8314: Retrieves usernames:domains for users in the specified course
                   8315: with specific role(s), and access status. 
                   8316: 
                   8317: Incoming parameters:
1.277     albertel 8318: 1. course domain
                   8319: 2. course number
                   8320: 3. access status: users must have - either active, 
1.275     raeburn  8321: previous, future, or all.
1.277     albertel 8322: 4. reference to array of permissible roles
1.288     raeburn  8323: 5. reference to array of section restrictions (optional)
                   8324: 6. reference to results object (hash of hashes).
                   8325: 7. reference to optional userdata hash
1.609     raeburn  8326: 8. reference to optional statushash
1.630     raeburn  8327: 9. flag if privileged users (except those set to unhide in
                   8328:    course settings) should be excluded    
1.609     raeburn  8329: Keys of top level results hash are roles.
1.275     raeburn  8330: Keys of inner hashes are username:domain, with 
                   8331: values set to access type.
1.288     raeburn  8332: Optional userdata hash returns an array with arguments in the 
                   8333: same order as loncoursedata::get_classlist() for student data.
                   8334: 
1.609     raeburn  8335: Optional statushash returns
                   8336: 
1.288     raeburn  8337: Entries for end, start, section and status are blank because
                   8338: of the possibility of multiple values for non-student roles.
                   8339: 
1.275     raeburn  8340: =cut
1.405     albertel 8341: 
1.275     raeburn  8342: ###############################################
1.405     albertel 8343: 
1.275     raeburn  8344: sub get_course_users {
1.630     raeburn  8345:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8346:     my %idx = ();
1.419     raeburn  8347:     my %seclists;
1.288     raeburn  8348: 
                   8349:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8350:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8351:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8352:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8353:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8354:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8355:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8356:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8357: 
1.290     albertel 8358:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8359:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8360:         my $now = time;
1.277     albertel 8361:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8362:             my $match = 0;
1.412     raeburn  8363:             my $secmatch = 0;
1.419     raeburn  8364:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8365:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8366:             if ($section eq '') {
                   8367:                 $section = 'none';
                   8368:             }
1.291     albertel 8369:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8370:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8371:                     $secmatch = 1;
                   8372:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8373:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8374:                         $secmatch = 1;
                   8375:                     }
                   8376:                 } else {  
1.419     raeburn  8377: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8378: 		        $secmatch = 1;
                   8379:                     }
1.290     albertel 8380: 		}
1.412     raeburn  8381:                 if (!$secmatch) {
                   8382:                     next;
                   8383:                 }
1.419     raeburn  8384:             }
1.275     raeburn  8385:             if (defined($$types{'active'})) {
1.288     raeburn  8386:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8387:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8388:                     $match = 1;
1.275     raeburn  8389:                 }
                   8390:             }
                   8391:             if (defined($$types{'previous'})) {
1.609     raeburn  8392:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8393:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8394:                     $match = 1;
1.275     raeburn  8395:                 }
                   8396:             }
                   8397:             if (defined($$types{'future'})) {
1.609     raeburn  8398:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8399:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8400:                     $match = 1;
1.275     raeburn  8401:                 }
                   8402:             }
1.609     raeburn  8403:             if ($match) {
                   8404:                 push(@{$seclists{$student}},$section);
                   8405:                 if (ref($userdata) eq 'HASH') {
                   8406:                     $$userdata{$student} = $$classlist{$student};
                   8407:                 }
                   8408:                 if (ref($statushash) eq 'HASH') {
                   8409:                     $statushash->{$student}{'st'}{$section} = $status;
                   8410:                 }
1.288     raeburn  8411:             }
1.275     raeburn  8412:         }
                   8413:     }
1.412     raeburn  8414:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8415:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8416:         my $now = time;
1.609     raeburn  8417:         my %displaystatus = ( previous => 'Expired',
                   8418:                               active   => 'Active',
                   8419:                               future   => 'Future',
                   8420:                             );
1.1121    raeburn  8421:         my (%nothide,@possdoms);
1.630     raeburn  8422:         if ($hidepriv) {
                   8423:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8424:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8425:                 if ($user !~ /:/) {
                   8426:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8427:                 } else {
                   8428:                     $nothide{$user} = 1;
                   8429:                 }
                   8430:             }
1.1121    raeburn  8431:             my @possdoms = ($cdom);
                   8432:             if ($coursehash{'checkforpriv'}) {
                   8433:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8434:             }
1.630     raeburn  8435:         }
1.439     raeburn  8436:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8437:             my $match = 0;
1.412     raeburn  8438:             my $secmatch = 0;
1.439     raeburn  8439:             my $status;
1.412     raeburn  8440:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8441:             $user =~ s/:$//;
1.439     raeburn  8442:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8443:             if ($end == -1 || $start == -1) {
                   8444:                 next;
                   8445:             }
                   8446:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8447:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8448:                 my ($uname,$udom) = split(/:/,$user);
                   8449:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8450:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8451:                         $secmatch = 1;
                   8452:                     } elsif ($usec eq '') {
1.420     albertel 8453:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8454:                             $secmatch = 1;
                   8455:                         }
                   8456:                     } else {
                   8457:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8458:                             $secmatch = 1;
                   8459:                         }
                   8460:                     }
                   8461:                     if (!$secmatch) {
                   8462:                         next;
                   8463:                     }
1.288     raeburn  8464:                 }
1.419     raeburn  8465:                 if ($usec eq '') {
                   8466:                     $usec = 'none';
                   8467:                 }
1.275     raeburn  8468:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8469:                     if ($hidepriv) {
1.1121    raeburn  8470:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8471:                             (!$nothide{$uname.':'.$udom})) {
                   8472:                             next;
                   8473:                         }
                   8474:                     }
1.503     raeburn  8475:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8476:                         $status = 'previous';
                   8477:                     } elsif ($start > $now) {
                   8478:                         $status = 'future';
                   8479:                     } else {
                   8480:                         $status = 'active';
                   8481:                     }
1.277     albertel 8482:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8483:                         if ($status eq $type) {
1.420     albertel 8484:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8485:                                 push(@{$$users{$role}{$user}},$type);
                   8486:                             }
1.288     raeburn  8487:                             $match = 1;
                   8488:                         }
                   8489:                     }
1.419     raeburn  8490:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8491:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8492: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8493:                         }
1.420     albertel 8494:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8495:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8496:                         }
1.609     raeburn  8497:                         if (ref($statushash) eq 'HASH') {
                   8498:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8499:                         }
1.275     raeburn  8500:                     }
                   8501:                 }
                   8502:             }
                   8503:         }
1.290     albertel 8504:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8505:             if ((defined($cdom)) && (defined($cnum))) {
                   8506:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8507:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8508:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8509:                     next if ($owner eq '');
                   8510:                     my ($ownername,$ownerdom);
                   8511:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8512:                         $ownername = $1;
                   8513:                         $ownerdom = $2;
                   8514:                     } else {
                   8515:                         $ownername = $owner;
                   8516:                         $ownerdom = $cdom;
                   8517:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8518:                     }
                   8519:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8520:                     if (defined($userdata) && 
1.609     raeburn  8521: 			!exists($$userdata{$owner})) {
                   8522: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8523:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8524:                             push(@{$seclists{$owner}},'none');
                   8525:                         }
                   8526:                         if (ref($statushash) eq 'HASH') {
                   8527:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8528:                         }
1.290     albertel 8529: 		    }
1.279     raeburn  8530:                 }
                   8531:             }
                   8532:         }
1.419     raeburn  8533:         foreach my $user (keys(%seclists)) {
                   8534:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8535:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8536:         }
1.275     raeburn  8537:     }
                   8538:     return;
                   8539: }
                   8540: 
1.288     raeburn  8541: sub get_user_info {
                   8542:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8543:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8544: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8545:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8546:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8547:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8548:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8549:     return;
                   8550: }
1.275     raeburn  8551: 
1.472     raeburn  8552: ###############################################
                   8553: 
                   8554: =pod
                   8555: 
                   8556: =item * &get_user_quota()
                   8557: 
                   8558: Retrieves quota assigned for storage of portfolio files for a user  
                   8559: 
                   8560: Incoming parameters:
                   8561: 1. user's username
                   8562: 2. user's domain
                   8563: 
                   8564: Returns:
1.536     raeburn  8565: 1. Disk quota (in Mb) assigned to student.
                   8566: 2. (Optional) Type of setting: custom or default
                   8567:    (individually assigned or default for user's 
                   8568:    institutional status).
                   8569: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8570:    or student - types as defined in localenroll::inst_usertypes 
                   8571:    for user's domain, which determines default quota for user.
                   8572: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8573: 
                   8574: If a value has been stored in the user's environment, 
1.536     raeburn  8575: it will return that, otherwise it returns the maximal default
                   8576: defined for the user's instituional status(es) in the domain.
1.472     raeburn  8577: 
                   8578: =cut
                   8579: 
                   8580: ###############################################
                   8581: 
                   8582: 
                   8583: sub get_user_quota {
                   8584:     my ($uname,$udom) = @_;
1.536     raeburn  8585:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8586:     if (!defined($udom)) {
                   8587:         $udom = $env{'user.domain'};
                   8588:     }
                   8589:     if (!defined($uname)) {
                   8590:         $uname = $env{'user.name'};
                   8591:     }
                   8592:     if (($udom eq '' || $uname eq '') ||
                   8593:         ($udom eq 'public') && ($uname eq 'public')) {
                   8594:         $quota = 0;
1.536     raeburn  8595:         $quotatype = 'default';
                   8596:         $defquota = 0; 
1.472     raeburn  8597:     } else {
1.536     raeburn  8598:         my $inststatus;
1.472     raeburn  8599:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8600:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  8601:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  8602:         } else {
1.536     raeburn  8603:             my %userenv = 
                   8604:                 &Apache::lonnet::get('environment',['portfolioquota',
                   8605:                                      'inststatus'],$udom,$uname);
1.472     raeburn  8606:             my ($tmp) = keys(%userenv);
                   8607:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8608:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  8609:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  8610:             } else {
                   8611:                 undef(%userenv);
                   8612:             }
                   8613:         }
1.536     raeburn  8614:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  8615:         if ($quota eq '') {
1.536     raeburn  8616:             $quota = $defquota;
                   8617:             $quotatype = 'default';
                   8618:         } else {
                   8619:             $quotatype = 'custom';
1.472     raeburn  8620:         }
                   8621:     }
1.536     raeburn  8622:     if (wantarray) {
                   8623:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8624:     } else {
                   8625:         return $quota;
                   8626:     }
1.472     raeburn  8627: }
                   8628: 
                   8629: ###############################################
                   8630: 
                   8631: =pod
                   8632: 
                   8633: =item * &default_quota()
                   8634: 
1.536     raeburn  8635: Retrieves default quota assigned for storage of user portfolio files,
                   8636: given an (optional) user's institutional status.
1.472     raeburn  8637: 
                   8638: Incoming parameters:
                   8639: 1. domain
1.536     raeburn  8640: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8641:    status types (e.g., faculty, staff, student etc.)
                   8642:    which apply to the user for whom the default is being retrieved.
                   8643:    If the institutional status string in undefined, the domain
                   8644:    default quota will be returned. 
1.472     raeburn  8645: 
                   8646: Returns:
                   8647: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  8648: 2. (Optional) institutional type which determined the value of the
                   8649:    default quota.
1.472     raeburn  8650: 
                   8651: If a value has been stored in the domain's configuration db,
                   8652: it will return that, otherwise it returns 20 (for backwards 
                   8653: compatibility with domains which have not set up a configuration
                   8654: db file; the original statically defined portfolio quota was 20 Mb). 
                   8655: 
1.536     raeburn  8656: If the user's status includes multiple types (e.g., staff and student),
                   8657: the largest default quota which applies to the user determines the
                   8658: default quota returned.
                   8659: 
1.780     raeburn  8660: =back
                   8661: 
1.472     raeburn  8662: =cut
                   8663: 
                   8664: ###############################################
                   8665: 
                   8666: 
                   8667: sub default_quota {
1.536     raeburn  8668:     my ($udom,$inststatus) = @_;
                   8669:     my ($defquota,$settingstatus);
                   8670:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8671:                                             ['quotas'],$udom);
                   8672:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8673:         if ($inststatus ne '') {
1.765     raeburn  8674:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8675:             foreach my $item (@statuses) {
1.711     raeburn  8676:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8677:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
                   8678:                         if ($defquota eq '') {
                   8679:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8680:                             $settingstatus = $item;
                   8681:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
                   8682:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8683:                             $settingstatus = $item;
                   8684:                         }
                   8685:                     }
                   8686:                 } else {
                   8687:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8688:                         if ($defquota eq '') {
                   8689:                             $defquota = $quotahash{'quotas'}{$item};
                   8690:                             $settingstatus = $item;
                   8691:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8692:                             $defquota = $quotahash{'quotas'}{$item};
                   8693:                             $settingstatus = $item;
                   8694:                         }
1.536     raeburn  8695:                     }
                   8696:                 }
                   8697:             }
                   8698:         }
                   8699:         if ($defquota eq '') {
1.711     raeburn  8700:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8701:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
                   8702:             } else {
                   8703:                 $defquota = $quotahash{'quotas'}{'default'};
                   8704:             }
1.536     raeburn  8705:             $settingstatus = 'default';
                   8706:         }
                   8707:     } else {
                   8708:         $settingstatus = 'default';
                   8709:         $defquota = 20;
                   8710:     }
                   8711:     if (wantarray) {
                   8712:         return ($defquota,$settingstatus);
1.472     raeburn  8713:     } else {
1.536     raeburn  8714:         return $defquota;
1.472     raeburn  8715:     }
                   8716: }
                   8717: 
1.384     raeburn  8718: sub get_secgrprole_info {
                   8719:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8720:     my %sections_count = &get_sections($cdom,$cnum);
                   8721:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8722:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8723:     my @groups = sort(keys(%curr_groups));
                   8724:     my $allroles = [];
                   8725:     my $rolehash;
                   8726:     my $accesshash = {
                   8727:                      active => 'Currently has access',
                   8728:                      future => 'Will have future access',
                   8729:                      previous => 'Previously had access',
                   8730:                   };
                   8731:     if ($needroles) {
                   8732:         $rolehash = {'all' => 'all'};
1.385     albertel 8733:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8734: 	if (&Apache::lonnet::error(%user_roles)) {
                   8735: 	    undef(%user_roles);
                   8736: 	}
                   8737:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8738:             my ($role)=split(/\:/,$item,2);
                   8739:             if ($role eq 'cr') { next; }
                   8740:             if ($role =~ /^cr/) {
                   8741:                 $$rolehash{$role} = (split('/',$role))[3];
                   8742:             } else {
                   8743:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8744:             }
                   8745:         }
                   8746:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8747:             push(@{$allroles},$key);
                   8748:         }
                   8749:         push (@{$allroles},'st');
                   8750:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8751:     }
                   8752:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8753: }
                   8754: 
1.555     raeburn  8755: sub user_picker {
1.994     raeburn  8756:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8757:     my $currdom = $dom;
                   8758:     my %curr_selected = (
                   8759:                         srchin => 'dom',
1.580     raeburn  8760:                         srchby => 'lastname',
1.555     raeburn  8761:                       );
                   8762:     my $srchterm;
1.625     raeburn  8763:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  8764:         if ($srch->{'srchby'} ne '') {
                   8765:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   8766:         }
                   8767:         if ($srch->{'srchin'} ne '') {
                   8768:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   8769:         }
                   8770:         if ($srch->{'srchtype'} ne '') {
                   8771:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   8772:         }
                   8773:         if ($srch->{'srchdomain'} ne '') {
                   8774:             $currdom = $srch->{'srchdomain'};
                   8775:         }
                   8776:         $srchterm = $srch->{'srchterm'};
                   8777:     }
                   8778:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  8779:                     'usr'       => 'Search criteria',
1.563     raeburn  8780:                     'doma'      => 'Domain/institution to search',
1.558     albertel 8781:                     'uname'     => 'username',
                   8782:                     'lastname'  => 'last name',
1.555     raeburn  8783:                     'lastfirst' => 'last name, first name',
1.558     albertel 8784:                     'crs'       => 'in this course',
1.576     raeburn  8785:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 8786:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  8787:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 8788:                     'exact'     => 'is',
                   8789:                     'contains'  => 'contains',
1.569     raeburn  8790:                     'begins'    => 'begins with',
1.571     raeburn  8791:                     'youm'      => "You must include some text to search for.",
                   8792:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   8793:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   8794:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   8795:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   8796:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   8797:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   8798:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  8799:                                        );
1.563     raeburn  8800:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   8801:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  8802: 
                   8803:     my @srchins = ('crs','dom','alc','instd');
                   8804: 
                   8805:     foreach my $option (@srchins) {
                   8806:         # FIXME 'alc' option unavailable until 
                   8807:         #       loncreateuser::print_user_query_page()
                   8808:         #       has been completed.
                   8809:         next if ($option eq 'alc');
1.880     raeburn  8810:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  8811:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  8812:         if ($curr_selected{'srchin'} eq $option) {
                   8813:             $srchinsel .= ' 
                   8814:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8815:         } else {
                   8816:             $srchinsel .= '
                   8817:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8818:         }
1.555     raeburn  8819:     }
1.563     raeburn  8820:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  8821: 
                   8822:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  8823:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  8824:         if ($curr_selected{'srchby'} eq $option) {
                   8825:             $srchbysel .= '
                   8826:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8827:         } else {
                   8828:             $srchbysel .= '
                   8829:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8830:          }
                   8831:     }
                   8832:     $srchbysel .= "\n  </select>\n";
                   8833: 
                   8834:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  8835:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  8836:         if ($curr_selected{'srchtype'} eq $option) {
                   8837:             $srchtypesel .= '
                   8838:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8839:         } else {
                   8840:             $srchtypesel .= '
                   8841:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8842:         }
                   8843:     }
                   8844:     $srchtypesel .= "\n  </select>\n";
                   8845: 
1.558     albertel 8846:     my ($newuserscript,$new_user_create);
1.994     raeburn  8847:     my $context_dom = $env{'request.role.domain'};
                   8848:     if ($context eq 'requestcrs') {
                   8849:         if ($env{'form.coursedom'} ne '') { 
                   8850:             $context_dom = $env{'form.coursedom'};
                   8851:         }
                   8852:     }
1.556     raeburn  8853:     if ($forcenewuser) {
1.576     raeburn  8854:         if (ref($srch) eq 'HASH') {
1.994     raeburn  8855:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  8856:                 if ($cancreate) {
                   8857:                     $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>';
                   8858:                 } else {
1.799     bisitz   8859:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  8860:                     my %usertypetext = (
                   8861:                         official   => 'institutional',
                   8862:                         unofficial => 'non-institutional',
                   8863:                     );
1.799     bisitz   8864:                     $new_user_create = '<p class="LC_warning">'
                   8865:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   8866:                                       .' '
                   8867:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   8868:                                           ,'<a href="'.$helplink.'">','</a>')
                   8869:                                       .'</p><br />';
1.627     raeburn  8870:                 }
1.576     raeburn  8871:             }
                   8872:         }
                   8873: 
1.556     raeburn  8874:         $newuserscript = <<"ENDSCRIPT";
                   8875: 
1.570     raeburn  8876: function setSearch(createnew,callingForm) {
1.556     raeburn  8877:     if (createnew == 1) {
1.570     raeburn  8878:         for (var i=0; i<callingForm.srchby.length; i++) {
                   8879:             if (callingForm.srchby.options[i].value == 'uname') {
                   8880:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  8881:             }
                   8882:         }
1.570     raeburn  8883:         for (var i=0; i<callingForm.srchin.length; i++) {
                   8884:             if ( callingForm.srchin.options[i].value == 'dom') {
                   8885: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  8886:             }
                   8887:         }
1.570     raeburn  8888:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   8889:             if (callingForm.srchtype.options[i].value == 'exact') {
                   8890:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  8891:             }
                   8892:         }
1.570     raeburn  8893:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  8894:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  8895:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  8896:             }
                   8897:         }
                   8898:     }
                   8899: }
                   8900: ENDSCRIPT
1.558     albertel 8901: 
1.556     raeburn  8902:     }
                   8903: 
1.555     raeburn  8904:     my $output = <<"END_BLOCK";
1.556     raeburn  8905: <script type="text/javascript">
1.824     bisitz   8906: // <![CDATA[
1.570     raeburn  8907: function validateEntry(callingForm) {
1.558     albertel 8908: 
1.556     raeburn  8909:     var checkok = 1;
1.558     albertel 8910:     var srchin;
1.570     raeburn  8911:     for (var i=0; i<callingForm.srchin.length; i++) {
                   8912: 	if ( callingForm.srchin[i].checked ) {
                   8913: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 8914: 	}
                   8915:     }
                   8916: 
1.570     raeburn  8917:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   8918:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   8919:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   8920:     var srchterm =  callingForm.srchterm.value;
                   8921:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  8922:     var msg = "";
                   8923: 
                   8924:     if (srchterm == "") {
                   8925:         checkok = 0;
1.571     raeburn  8926:         msg += "$lt{'youm'}\\n";
1.556     raeburn  8927:     }
                   8928: 
1.569     raeburn  8929:     if (srchtype== 'begins') {
                   8930:         if (srchterm.length < 2) {
                   8931:             checkok = 0;
1.571     raeburn  8932:             msg += "$lt{'thte'}\\n";
1.569     raeburn  8933:         }
                   8934:     }
                   8935: 
1.556     raeburn  8936:     if (srchtype== 'contains') {
                   8937:         if (srchterm.length < 3) {
                   8938:             checkok = 0;
1.571     raeburn  8939:             msg += "$lt{'thet'}\\n";
1.556     raeburn  8940:         }
                   8941:     }
                   8942:     if (srchin == 'instd') {
                   8943:         if (srchdomain == '') {
                   8944:             checkok = 0;
1.571     raeburn  8945:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  8946:         }
                   8947:     }
                   8948:     if (srchin == 'dom') {
                   8949:         if (srchdomain == '') {
                   8950:             checkok = 0;
1.571     raeburn  8951:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  8952:         }
                   8953:     }
                   8954:     if (srchby == 'lastfirst') {
                   8955:         if (srchterm.indexOf(",") == -1) {
                   8956:             checkok = 0;
1.571     raeburn  8957:             msg += "$lt{'whus'}\\n";
1.556     raeburn  8958:         }
                   8959:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   8960:             checkok = 0;
1.571     raeburn  8961:             msg += "$lt{'whse'}\\n";
1.556     raeburn  8962:         }
                   8963:     }
                   8964:     if (checkok == 0) {
1.571     raeburn  8965:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  8966:         return;
                   8967:     }
                   8968:     if (checkok == 1) {
1.570     raeburn  8969:         callingForm.submit();
1.556     raeburn  8970:     }
                   8971: }
                   8972: 
                   8973: $newuserscript
                   8974: 
1.824     bisitz   8975: // ]]>
1.556     raeburn  8976: </script>
1.558     albertel 8977: 
                   8978: $new_user_create
                   8979: 
1.555     raeburn  8980: END_BLOCK
1.558     albertel 8981: 
1.876     raeburn  8982:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   8983:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   8984:                $domform.
                   8985:                &Apache::lonhtmlcommon::row_closure().
                   8986:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   8987:                $srchbysel.
                   8988:                $srchtypesel. 
                   8989:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   8990:                $srchinsel.
                   8991:                &Apache::lonhtmlcommon::row_closure(1). 
                   8992:                &Apache::lonhtmlcommon::end_pick_box().
                   8993:                '<br />';
1.555     raeburn  8994:     return $output;
                   8995: }
                   8996: 
1.612     raeburn  8997: sub user_rule_check {
1.615     raeburn  8998:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  8999:     my $response;
                   9000:     if (ref($usershash) eq 'HASH') {
                   9001:         foreach my $user (keys(%{$usershash})) {
                   9002:             my ($uname,$udom) = split(/:/,$user);
                   9003:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9004:             my ($id,$newuser);
1.612     raeburn  9005:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9006:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9007:                 $id = $usershash->{$user}->{'id'};
                   9008:             }
                   9009:             my $inst_response;
                   9010:             if (ref($checks) eq 'HASH') {
                   9011:                 if (defined($checks->{'username'})) {
1.615     raeburn  9012:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9013:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9014:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9015:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9016:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9017:                 }
1.615     raeburn  9018:             } else {
                   9019:                 ($inst_response,%{$inst_results->{$user}}) =
                   9020:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9021:                 return;
1.612     raeburn  9022:             }
1.615     raeburn  9023:             if (!$got_rules->{$udom}) {
1.612     raeburn  9024:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9025:                                                   ['usercreation'],$udom);
                   9026:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9027:                     foreach my $item ('username','id') {
1.612     raeburn  9028:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9029:                             $$curr_rules{$udom}{$item} = 
                   9030:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9031:                         }
                   9032:                     }
                   9033:                 }
1.615     raeburn  9034:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9035:             }
1.612     raeburn  9036:             foreach my $item (keys(%{$checks})) {
                   9037:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9038:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9039:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9040:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9041:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9042:                                 if ($rule_check{$rule}) {
                   9043:                                     $$rulematch{$user}{$item} = $rule;
                   9044:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9045:                                         if (ref($inst_results) eq 'HASH') {
                   9046:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9047:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9048:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9049:                                                 }
1.612     raeburn  9050:                                             }
                   9051:                                         }
1.615     raeburn  9052:                                     }
                   9053:                                     last;
1.585     raeburn  9054:                                 }
                   9055:                             }
                   9056:                         }
                   9057:                     }
                   9058:                 }
                   9059:             }
                   9060:         }
                   9061:     }
1.612     raeburn  9062:     return;
                   9063: }
                   9064: 
                   9065: sub user_rule_formats {
                   9066:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9067:     my %text = ( 
                   9068:                  'username' => 'Usernames',
                   9069:                  'id'       => 'IDs',
                   9070:                );
                   9071:     my $output;
                   9072:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9073:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9074:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9075:             $output = '<br />'.
                   9076:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9077:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9078:                       ' <ul>';
1.612     raeburn  9079:             foreach my $rule (@{$ruleorder}) {
                   9080:                 if (ref($curr_rules) eq 'ARRAY') {
                   9081:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9082:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9083:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9084:                                         $rules->{$rule}{'desc'}.'</li>';
                   9085:                         }
                   9086:                     }
                   9087:                 }
                   9088:             }
                   9089:             $output .= '</ul>';
                   9090:         }
                   9091:     }
                   9092:     return $output;
                   9093: }
                   9094: 
                   9095: sub instrule_disallow_msg {
1.615     raeburn  9096:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9097:     my $response;
                   9098:     my %text = (
                   9099:                   item   => 'username',
                   9100:                   items  => 'usernames',
                   9101:                   match  => 'matches',
                   9102:                   do     => 'does',
                   9103:                   action => 'a username',
                   9104:                   one    => 'one',
                   9105:                );
                   9106:     if ($count > 1) {
                   9107:         $text{'item'} = 'usernames';
                   9108:         $text{'match'} ='match';
                   9109:         $text{'do'} = 'do';
                   9110:         $text{'action'} = 'usernames',
                   9111:         $text{'one'} = 'ones';
                   9112:     }
                   9113:     if ($checkitem eq 'id') {
                   9114:         $text{'items'} = 'IDs';
                   9115:         $text{'item'} = 'ID';
                   9116:         $text{'action'} = 'an ID';
1.615     raeburn  9117:         if ($count > 1) {
                   9118:             $text{'item'} = 'IDs';
                   9119:             $text{'action'} = 'IDs';
                   9120:         }
1.612     raeburn  9121:     }
1.674     bisitz   9122:     $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  9123:     if ($mode eq 'upload') {
                   9124:         if ($checkitem eq 'username') {
                   9125:             $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'}.");
                   9126:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9127:             $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  9128:         }
1.669     raeburn  9129:     } elsif ($mode eq 'selfcreate') {
                   9130:         if ($checkitem eq 'id') {
                   9131:             $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.");
                   9132:         }
1.615     raeburn  9133:     } else {
                   9134:         if ($checkitem eq 'username') {
                   9135:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9136:         } elsif ($checkitem eq 'id') {
                   9137:             $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.");
                   9138:         }
1.612     raeburn  9139:     }
                   9140:     return $response;
1.585     raeburn  9141: }
                   9142: 
1.624     raeburn  9143: sub personal_data_fieldtitles {
                   9144:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9145:                         id => 'Student/Employee ID',
                   9146:                         permanentemail => 'E-mail address',
                   9147:                         lastname => 'Last Name',
                   9148:                         firstname => 'First Name',
                   9149:                         middlename => 'Middle Name',
                   9150:                         generation => 'Generation',
                   9151:                         gen => 'Generation',
1.765     raeburn  9152:                         inststatus => 'Affiliation',
1.624     raeburn  9153:                    );
                   9154:     return %fieldtitles;
                   9155: }
                   9156: 
1.642     raeburn  9157: sub sorted_inst_types {
                   9158:     my ($dom) = @_;
                   9159:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9160:     my $othertitle = &mt('All users');
                   9161:     if ($env{'request.course.id'}) {
1.668     raeburn  9162:         $othertitle  = &mt('Any users');
1.642     raeburn  9163:     }
                   9164:     my @types;
                   9165:     if (ref($order) eq 'ARRAY') {
                   9166:         @types = @{$order};
                   9167:     }
                   9168:     if (@types == 0) {
                   9169:         if (ref($usertypes) eq 'HASH') {
                   9170:             @types = sort(keys(%{$usertypes}));
                   9171:         }
                   9172:     }
                   9173:     if (keys(%{$usertypes}) > 0) {
                   9174:         $othertitle = &mt('Other users');
                   9175:     }
                   9176:     return ($othertitle,$usertypes,\@types);
                   9177: }
                   9178: 
1.645     raeburn  9179: sub get_institutional_codes {
                   9180:     my ($settings,$allcourses,$LC_code) = @_;
                   9181: # Get complete list of course sections to update
                   9182:     my @currsections = ();
                   9183:     my @currxlists = ();
                   9184:     my $coursecode = $$settings{'internal.coursecode'};
                   9185: 
                   9186:     if ($$settings{'internal.sectionnums'} ne '') {
                   9187:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9188:     }
                   9189: 
                   9190:     if ($$settings{'internal.crosslistings'} ne '') {
                   9191:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9192:     }
                   9193: 
                   9194:     if (@currxlists > 0) {
                   9195:         foreach (@currxlists) {
                   9196:             if (m/^([^:]+):(\w*)$/) {
                   9197:                 unless (grep/^$1$/,@{$allcourses}) {
                   9198:                     push @{$allcourses},$1;
                   9199:                     $$LC_code{$1} = $2;
                   9200:                 }
                   9201:             }
                   9202:         }
                   9203:     }
                   9204:  
                   9205:     if (@currsections > 0) {
                   9206:         foreach (@currsections) {
                   9207:             if (m/^(\w+):(\w*)$/) {
                   9208:                 my $sec = $coursecode.$1;
                   9209:                 my $lc_sec = $2;
                   9210:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9211:                     push @{$allcourses},$sec;
                   9212:                     $$LC_code{$sec} = $lc_sec;
                   9213:                 }
                   9214:             }
                   9215:         }
                   9216:     }
                   9217:     return;
                   9218: }
                   9219: 
1.971     raeburn  9220: sub get_standard_codeitems {
                   9221:     return ('Year','Semester','Department','Number','Section');
                   9222: }
                   9223: 
1.112     bowersj2 9224: =pod
                   9225: 
1.780     raeburn  9226: =head1 Slot Helpers
                   9227: 
                   9228: =over 4
                   9229: 
                   9230: =item * sorted_slots()
                   9231: 
1.1040    raeburn  9232: Sorts an array of slot names in order of an optional sort key,
                   9233: default sort is by slot start time (earliest first). 
1.780     raeburn  9234: 
                   9235: Inputs:
                   9236: 
                   9237: =over 4
                   9238: 
                   9239: slotsarr  - Reference to array of unsorted slot names.
                   9240: 
                   9241: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9242: 
1.1040    raeburn  9243: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9244: 
1.549     albertel 9245: =back
                   9246: 
1.780     raeburn  9247: Returns:
                   9248: 
                   9249: =over 4
                   9250: 
1.1040    raeburn  9251: sorted   - An array of slot names sorted by a specified sort key 
                   9252:            (default sort key is start time of the slot).
1.780     raeburn  9253: 
                   9254: =back
                   9255: 
                   9256: =cut
                   9257: 
                   9258: 
                   9259: sub sorted_slots {
1.1040    raeburn  9260:     my ($slotsarr,$slots,$sortkey) = @_;
                   9261:     if ($sortkey eq '') {
                   9262:         $sortkey = 'starttime';
                   9263:     }
1.780     raeburn  9264:     my @sorted;
                   9265:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9266:         @sorted =
                   9267:             sort {
                   9268:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9269:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9270:                      }
                   9271:                      if (ref($slots->{$a})) { return -1;}
                   9272:                      if (ref($slots->{$b})) { return 1;}
                   9273:                      return 0;
                   9274:                  } @{$slotsarr};
                   9275:     }
                   9276:     return @sorted;
                   9277: }
                   9278: 
1.1040    raeburn  9279: =pod
                   9280: 
                   9281: =item * get_future_slots()
                   9282: 
                   9283: Inputs:
                   9284: 
                   9285: =over 4
                   9286: 
                   9287: cnum - course number
                   9288: 
                   9289: cdom - course domain
                   9290: 
                   9291: now - current UNIX time
                   9292: 
                   9293: symb - optional symb
                   9294: 
                   9295: =back
                   9296: 
                   9297: Returns:
                   9298: 
                   9299: =over 4
                   9300: 
                   9301: sorted_reservable - ref to array of student_schedulable slots currently 
                   9302:                     reservable, ordered by end date of reservation period.
                   9303: 
                   9304: reservable_now - ref to hash of student_schedulable slots currently
                   9305:                  reservable.
                   9306: 
                   9307:     Keys in inner hash are:
                   9308:     (a) symb: either blank or symb to which slot use is restricted.
                   9309:     (b) endreserve: end date of reservation period. 
                   9310: 
                   9311: sorted_future - ref to array of student_schedulable slots reservable in
                   9312:                 the future, ordered by start date of reservation period.
                   9313: 
                   9314: future_reservable - ref to hash of student_schedulable slots reservable
                   9315:                     in the future.
                   9316: 
                   9317:     Keys in inner hash are:
                   9318:     (a) symb: either blank or symb to which slot use is restricted.
                   9319:     (b) startreserve:  start date of reservation period.
                   9320: 
                   9321: =back
                   9322: 
                   9323: =cut
                   9324: 
                   9325: sub get_future_slots {
                   9326:     my ($cnum,$cdom,$now,$symb) = @_;
                   9327:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9328:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9329:     foreach my $slot (keys(%slots)) {
                   9330:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9331:         if ($symb) {
                   9332:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9333:                      ($slots{$slot}->{'symb'} ne $symb));
                   9334:         }
                   9335:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9336:             ($slots{$slot}->{'endtime'} > $now)) {
                   9337:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9338:                 my $userallowed = 0;
                   9339:                 if ($slots{$slot}->{'allowedsections'}) {
                   9340:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9341:                     if (!defined($env{'request.role.sec'})
                   9342:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9343:                         $userallowed=1;
                   9344:                     } else {
                   9345:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9346:                             $userallowed=1;
                   9347:                         }
                   9348:                     }
                   9349:                     unless ($userallowed) {
                   9350:                         if (defined($env{'request.course.groups'})) {
                   9351:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9352:                             foreach my $group (@groups) {
                   9353:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9354:                                     $userallowed=1;
                   9355:                                     last;
                   9356:                                 }
                   9357:                             }
                   9358:                         }
                   9359:                     }
                   9360:                 }
                   9361:                 if ($slots{$slot}->{'allowedusers'}) {
                   9362:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9363:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9364:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9365:                         $userallowed = 1;
                   9366:                     }
                   9367:                 }
                   9368:                 next unless($userallowed);
                   9369:             }
                   9370:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9371:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9372:             my $symb = $slots{$slot}->{'symb'};
                   9373:             if (($startreserve < $now) &&
                   9374:                 (!$endreserve || $endreserve > $now)) {
                   9375:                 my $lastres = $endreserve;
                   9376:                 if (!$lastres) {
                   9377:                     $lastres = $slots{$slot}->{'starttime'};
                   9378:                 }
                   9379:                 $reservable_now{$slot} = {
                   9380:                                            symb       => $symb,
                   9381:                                            endreserve => $lastres
                   9382:                                          };
                   9383:             } elsif (($startreserve > $now) &&
                   9384:                      (!$endreserve || $endreserve > $startreserve)) {
                   9385:                 $future_reservable{$slot} = {
                   9386:                                               symb         => $symb,
                   9387:                                               startreserve => $startreserve
                   9388:                                             };
                   9389:             }
                   9390:         }
                   9391:     }
                   9392:     my @unsorted_reservable = keys(%reservable_now);
                   9393:     if (@unsorted_reservable > 0) {
                   9394:         @sorted_reservable = 
                   9395:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9396:     }
                   9397:     my @unsorted_future = keys(%future_reservable);
                   9398:     if (@unsorted_future > 0) {
                   9399:         @sorted_future =
                   9400:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9401:     }
                   9402:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9403: }
1.780     raeburn  9404: 
                   9405: =pod
                   9406: 
1.1057    foxr     9407: =back
                   9408: 
1.549     albertel 9409: =head1 HTTP Helpers
                   9410: 
                   9411: =over 4
                   9412: 
1.648     raeburn  9413: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9414: 
1.258     albertel 9415: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9416: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9417: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9418: 
                   9419: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9420: $possible_names is an ref to an array of form element names.  As an example:
                   9421: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9422: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9423: 
                   9424: =cut
1.1       albertel 9425: 
1.6       albertel 9426: sub get_unprocessed_cgi {
1.25      albertel 9427:   my ($query,$possible_names)= @_;
1.26      matthew  9428:   # $Apache::lonxml::debug=1;
1.356     albertel 9429:   foreach my $pair (split(/&/,$query)) {
                   9430:     my ($name, $value) = split(/=/,$pair);
1.369     www      9431:     $name = &unescape($name);
1.25      albertel 9432:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9433:       $value =~ tr/+/ /;
                   9434:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9435:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9436:     }
1.16      harris41 9437:   }
1.6       albertel 9438: }
                   9439: 
1.112     bowersj2 9440: =pod
                   9441: 
1.648     raeburn  9442: =item * &cacheheader() 
1.112     bowersj2 9443: 
                   9444: returns cache-controlling header code
                   9445: 
                   9446: =cut
                   9447: 
1.7       albertel 9448: sub cacheheader {
1.258     albertel 9449:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9450:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9451:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9452:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9453:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9454:     return $output;
1.7       albertel 9455: }
                   9456: 
1.112     bowersj2 9457: =pod
                   9458: 
1.648     raeburn  9459: =item * &no_cache($r) 
1.112     bowersj2 9460: 
                   9461: specifies header code to not have cache
                   9462: 
                   9463: =cut
                   9464: 
1.9       albertel 9465: sub no_cache {
1.216     albertel 9466:     my ($r) = @_;
                   9467:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9468: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9469:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9470:     $r->no_cache(1);
                   9471:     $r->header_out("Expires" => $date);
                   9472:     $r->header_out("Pragma" => "no-cache");
1.123     www      9473: }
                   9474: 
                   9475: sub content_type {
1.181     albertel 9476:     my ($r,$type,$charset) = @_;
1.299     foxr     9477:     if ($r) {
                   9478: 	#  Note that printout.pl calls this with undef for $r.
                   9479: 	&no_cache($r);
                   9480:     }
1.258     albertel 9481:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9482:     unless ($charset) {
                   9483: 	$charset=&Apache::lonlocal::current_encoding;
                   9484:     }
                   9485:     if ($charset) { $type.='; charset='.$charset; }
                   9486:     if ($r) {
                   9487: 	$r->content_type($type);
                   9488:     } else {
                   9489: 	print("Content-type: $type\n\n");
                   9490:     }
1.9       albertel 9491: }
1.25      albertel 9492: 
1.112     bowersj2 9493: =pod
                   9494: 
1.648     raeburn  9495: =item * &add_to_env($name,$value) 
1.112     bowersj2 9496: 
1.258     albertel 9497: adds $name to the %env hash with value
1.112     bowersj2 9498: $value, if $name already exists, the entry is converted to an array
                   9499: reference and $value is added to the array.
                   9500: 
                   9501: =cut
                   9502: 
1.25      albertel 9503: sub add_to_env {
                   9504:   my ($name,$value)=@_;
1.258     albertel 9505:   if (defined($env{$name})) {
                   9506:     if (ref($env{$name})) {
1.25      albertel 9507:       #already have multiple values
1.258     albertel 9508:       push(@{ $env{$name} },$value);
1.25      albertel 9509:     } else {
                   9510:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9511:       my $first=$env{$name};
                   9512:       undef($env{$name});
                   9513:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9514:     }
                   9515:   } else {
1.258     albertel 9516:     $env{$name}=$value;
1.25      albertel 9517:   }
1.31      albertel 9518: }
1.149     albertel 9519: 
                   9520: =pod
                   9521: 
1.648     raeburn  9522: =item * &get_env_multiple($name) 
1.149     albertel 9523: 
1.258     albertel 9524: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9525: values may be defined and end up as an array ref.
                   9526: 
                   9527: returns an array of values
                   9528: 
                   9529: =cut
                   9530: 
                   9531: sub get_env_multiple {
                   9532:     my ($name) = @_;
                   9533:     my @values;
1.258     albertel 9534:     if (defined($env{$name})) {
1.149     albertel 9535:         # exists is it an array
1.258     albertel 9536:         if (ref($env{$name})) {
                   9537:             @values=@{ $env{$name} };
1.149     albertel 9538:         } else {
1.258     albertel 9539:             $values[0]=$env{$name};
1.149     albertel 9540:         }
                   9541:     }
                   9542:     return(@values);
                   9543: }
                   9544: 
1.660     raeburn  9545: sub ask_for_embedded_content {
                   9546:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9547:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  9548:         %currsubfile,%unused,$rem);
1.1071    raeburn  9549:     my $counter = 0;
                   9550:     my $numnew = 0;
1.987     raeburn  9551:     my $numremref = 0;
                   9552:     my $numinvalid = 0;
                   9553:     my $numpathchg = 0;
                   9554:     my $numexisting = 0;
1.1071    raeburn  9555:     my $numunused = 0;
                   9556:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
                   9557:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
                   9558:     my $heading = &mt('Upload embedded files');
                   9559:     my $buttontext = &mt('Upload');
                   9560: 
1.1085    raeburn  9561:     my $navmap;
                   9562:     if ($env{'request.course.id'}) {
                   9563:         $navmap = Apache::lonnavmaps::navmap->new();
                   9564:     }
1.984     raeburn  9565:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9566:         my $current_path='/';
                   9567:         if ($env{'form.currentpath'}) {
                   9568:             $current_path = $env{'form.currentpath'};
                   9569:         }
                   9570:         if ($actionurl eq '/adm/coursegrp_portfolio') {
                   9571:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9572:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9573:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9574:         } else {
                   9575:             $udom = $env{'user.domain'};
                   9576:             $uname = $env{'user.name'};
                   9577:             $url = '/userfiles/portfolio';
                   9578:         }
1.987     raeburn  9579:         $toplevel = $url.'/';
1.984     raeburn  9580:         $url .= $current_path;
                   9581:         $getpropath = 1;
1.987     raeburn  9582:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9583:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9584:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9585:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9586:         $toplevel = $url;
1.984     raeburn  9587:         if ($rest ne '') {
1.987     raeburn  9588:             $url .= $rest;
                   9589:         }
                   9590:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9591:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9592:             $url = $args->{'docs_url'};
                   9593:             $toplevel = $url;
1.1084    raeburn  9594:             if ($args->{'context'} eq 'paste') {
                   9595:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9596:                 ($path) = 
                   9597:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9598:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9599:                 $fileloc =~ s{^/}{};
                   9600:             }
1.1071    raeburn  9601:         }
1.1084    raeburn  9602:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  9603:         if ($env{'request.course.id'} ne '') {
                   9604:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9605:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
                   9606:             if (ref($args) eq 'HASH') {
                   9607:                 $url = $args->{'docs_url'};
                   9608:                 $title = $args->{'docs_title'};
                   9609:                 $toplevel = "/$url";
1.1085    raeburn  9610:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1071    raeburn  9611:                 ($path) =  
                   9612:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9613:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9614:                 $fileloc =~ s{^/}{};
                   9615:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9616:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9617:             }
1.987     raeburn  9618:         }
                   9619:     }
                   9620:     my $now = time();
                   9621:     foreach my $embed_file (keys(%{$allfiles})) {
                   9622:         my $absolutepath;
                   9623:         if ($embed_file =~ m{^\w+://}) {
                   9624:             $newfiles{$embed_file} = 1;
                   9625:             $mapping{$embed_file} = $embed_file;
                   9626:         } else {
                   9627:             if ($embed_file =~ m{^/}) {
                   9628:                 $absolutepath = $embed_file;
                   9629:                 $embed_file =~ s{^(/+)}{};
                   9630:             }
                   9631:             if ($embed_file =~ m{/}) {
                   9632:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
                   9633:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9634:                 my $item = $fname;
                   9635:                 if ($path ne '') {
                   9636:                     $item = $path.'/'.$fname;
                   9637:                     $subdependencies{$path}{$fname} = 1;
                   9638:                 } else {
                   9639:                     $dependencies{$item} = 1;
                   9640:                 }
                   9641:                 if ($absolutepath) {
                   9642:                     $mapping{$item} = $absolutepath;
                   9643:                 } else {
                   9644:                     $mapping{$item} = $embed_file;
                   9645:                 }
                   9646:             } else {
                   9647:                 $dependencies{$embed_file} = 1;
                   9648:                 if ($absolutepath) {
                   9649:                     $mapping{$embed_file} = $absolutepath;
                   9650:                 } else {
                   9651:                     $mapping{$embed_file} = $embed_file;
                   9652:                 }
                   9653:             }
1.984     raeburn  9654:         }
                   9655:     }
1.1071    raeburn  9656:     my $dirptr = 16384;
1.984     raeburn  9657:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9658:         $currsubfile{$path} = {};
1.984     raeburn  9659:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9660:             my ($sublistref,$listerror) =
                   9661:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9662:             if (ref($sublistref) eq 'ARRAY') {
                   9663:                 foreach my $line (@{$sublistref}) {
                   9664:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9665:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9666:                 }
1.984     raeburn  9667:             }
1.987     raeburn  9668:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9669:             if (opendir(my $dir,$url.'/'.$path)) {
                   9670:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9671:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9672:             }
1.1084    raeburn  9673:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9674:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9675:                   ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9676:             if ($env{'request.course.id'} ne '') {
                   9677:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9678:                 if ($dir ne '') {
                   9679:                     my ($sublistref,$listerror) =
                   9680:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9681:                     if (ref($sublistref) eq 'ARRAY') {
                   9682:                         foreach my $line (@{$sublistref}) {
                   9683:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9684:                                 undef,$mtime)=split(/\&/,$line,12);
                   9685:                             unless (($testdir&$dirptr) ||
                   9686:                                     ($file_name =~ /^\.\.?$/)) {
                   9687:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9688:                             }
                   9689:                         }
                   9690:                     }
                   9691:                 }
1.984     raeburn  9692:             }
                   9693:         }
                   9694:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9695:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9696:                 my $item = $path.'/'.$file;
                   9697:                 unless ($mapping{$item} eq $item) {
                   9698:                     $pathchanges{$item} = 1;
                   9699:                 }
                   9700:                 $existing{$item} = 1;
                   9701:                 $numexisting ++;
                   9702:             } else {
                   9703:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9704:             }
                   9705:         }
1.1071    raeburn  9706:         if ($actionurl eq '/adm/dependencies') {
                   9707:             foreach my $path (keys(%currsubfile)) {
                   9708:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9709:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9710:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  9711:                              next if (($rem ne '') &&
                   9712:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9713:                                        (ref($navmap) &&
                   9714:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9715:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9716:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9717:                              $unused{$path.'/'.$file} = 1; 
                   9718:                          }
                   9719:                     }
                   9720:                 }
                   9721:             }
                   9722:         }
1.984     raeburn  9723:     }
1.987     raeburn  9724:     my %currfile;
1.984     raeburn  9725:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9726:         my ($dirlistref,$listerror) =
                   9727:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9728:         if (ref($dirlistref) eq 'ARRAY') {
                   9729:             foreach my $line (@{$dirlistref}) {
                   9730:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   9731:                 $currfile{$file_name} = 1;
                   9732:             }
1.984     raeburn  9733:         }
1.987     raeburn  9734:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9735:         if (opendir(my $dir,$url)) {
1.987     raeburn  9736:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  9737:             map {$currfile{$_} = 1;} @dir_list;
                   9738:         }
1.1084    raeburn  9739:     } elsif (($actionurl eq '/adm/dependencies') ||
                   9740:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9741:               ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9742:         if ($env{'request.course.id'} ne '') {
                   9743:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9744:             if ($dir ne '') {
                   9745:                 my ($dirlistref,$listerror) =
                   9746:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   9747:                 if (ref($dirlistref) eq 'ARRAY') {
                   9748:                     foreach my $line (@{$dirlistref}) {
                   9749:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   9750:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   9751:                         unless (($testdir&$dirptr) ||
                   9752:                                 ($file_name =~ /^\.\.?$/)) {
                   9753:                             $currfile{$file_name} = [$size,$mtime];
                   9754:                         }
                   9755:                     }
                   9756:                 }
                   9757:             }
                   9758:         }
1.984     raeburn  9759:     }
                   9760:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  9761:         if (exists($currfile{$file})) {
1.987     raeburn  9762:             unless ($mapping{$file} eq $file) {
                   9763:                 $pathchanges{$file} = 1;
                   9764:             }
                   9765:             $existing{$file} = 1;
                   9766:             $numexisting ++;
                   9767:         } else {
1.984     raeburn  9768:             $newfiles{$file} = 1;
                   9769:         }
                   9770:     }
1.1071    raeburn  9771:     foreach my $file (keys(%currfile)) {
                   9772:         unless (($file eq $filename) ||
                   9773:                 ($file eq $filename.'.bak') ||
                   9774:                 ($dependencies{$file})) {
1.1085    raeburn  9775:             if ($actionurl eq '/adm/dependencies') {
                   9776:                 next if (($rem ne '') &&
                   9777:                          (($env{"httpref.$rem".$file} ne '') ||
                   9778:                           (ref($navmap) &&
                   9779:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   9780:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9781:                             ($navmap->getResourceByUrl($rem.$1)))))));
                   9782:             }
1.1071    raeburn  9783:             $unused{$file} = 1;
                   9784:         }
                   9785:     }
1.1084    raeburn  9786:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9787:         ($args->{'context'} eq 'paste')) {
                   9788:         $counter = scalar(keys(%existing));
                   9789:         $numpathchg = scalar(keys(%pathchanges));
                   9790:         return ($output,$counter,$numpathchg,\%existing); 
                   9791:     }
1.984     raeburn  9792:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  9793:         if ($actionurl eq '/adm/dependencies') {
                   9794:             next if ($embed_file =~ m{^\w+://});
                   9795:         }
1.660     raeburn  9796:         $upload_output .= &start_data_table_row().
1.1071    raeburn  9797:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
                   9798:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  9799:         unless ($mapping{$embed_file} eq $embed_file) {
                   9800:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
                   9801:         }
                   9802:         $upload_output .= '</td><td>';
1.1071    raeburn  9803:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.660     raeburn  9804:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
1.987     raeburn  9805:             $numremref++;
1.660     raeburn  9806:         } elsif ($args->{'error_on_invalid_names'}
                   9807:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.987     raeburn  9808:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
                   9809:             $numinvalid++;
1.660     raeburn  9810:         } else {
1.1071    raeburn  9811:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  9812:                                                      $embed_file,\%mapping,
1.1071    raeburn  9813:                                                      $allfiles,$codebase,'upload');
                   9814:             $counter ++;
                   9815:             $numnew ++;
1.987     raeburn  9816:         }
                   9817:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   9818:     }
                   9819:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  9820:         if ($actionurl eq '/adm/dependencies') {
                   9821:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   9822:             $modify_output .= &start_data_table_row().
                   9823:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   9824:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   9825:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   9826:                               '<td>'.$size.'</td>'.
                   9827:                               '<td>'.$mtime.'</td>'.
                   9828:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   9829:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   9830:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   9831:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   9832:                               &embedded_file_element('upload_embedded',$counter,
                   9833:                                                      $embed_file,\%mapping,
                   9834:                                                      $allfiles,$codebase,'modify').
                   9835:                               '</div></td>'.
                   9836:                               &end_data_table_row()."\n";
                   9837:             $counter ++;
                   9838:         } else {
                   9839:             $upload_output .= &start_data_table_row().
                   9840:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
                   9841:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
                   9842:                               &Apache::loncommon::end_data_table_row()."\n";
                   9843:         }
                   9844:     }
                   9845:     my $delidx = $counter;
                   9846:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   9847:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   9848:         $delete_output .= &start_data_table_row().
                   9849:                           '<td><img src="'.&icon($oldfile).'" />'.
                   9850:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   9851:                           '<td>'.$size.'</td>'.
                   9852:                           '<td>'.$mtime.'</td>'.
                   9853:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   9854:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   9855:                           &embedded_file_element('upload_embedded',$delidx,
                   9856:                                                  $oldfile,\%mapping,$allfiles,
                   9857:                                                  $codebase,'delete').'</td>'.
                   9858:                           &end_data_table_row()."\n"; 
                   9859:         $numunused ++;
                   9860:         $delidx ++;
1.987     raeburn  9861:     }
                   9862:     if ($upload_output) {
                   9863:         $upload_output = &start_data_table().
                   9864:                          $upload_output.
                   9865:                          &end_data_table()."\n";
                   9866:     }
1.1071    raeburn  9867:     if ($modify_output) {
                   9868:         $modify_output = &start_data_table().
                   9869:                          &start_data_table_header_row().
                   9870:                          '<th>'.&mt('File').'</th>'.
                   9871:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9872:                          '<th>'.&mt('Modified').'</th>'.
                   9873:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   9874:                          &end_data_table_header_row().
                   9875:                          $modify_output.
                   9876:                          &end_data_table()."\n";
                   9877:     }
                   9878:     if ($delete_output) {
                   9879:         $delete_output = &start_data_table().
                   9880:                          &start_data_table_header_row().
                   9881:                          '<th>'.&mt('File').'</th>'.
                   9882:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9883:                          '<th>'.&mt('Modified').'</th>'.
                   9884:                          '<th>'.&mt('Delete?').'</th>'.
                   9885:                          &end_data_table_header_row().
                   9886:                          $delete_output.
                   9887:                          &end_data_table()."\n";
                   9888:     }
1.987     raeburn  9889:     my $applies = 0;
                   9890:     if ($numremref) {
                   9891:         $applies ++;
                   9892:     }
                   9893:     if ($numinvalid) {
                   9894:         $applies ++;
                   9895:     }
                   9896:     if ($numexisting) {
                   9897:         $applies ++;
                   9898:     }
1.1071    raeburn  9899:     if ($counter || $numunused) {
1.987     raeburn  9900:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   9901:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  9902:                   $state.'<h3>'.$heading.'</h3>'; 
                   9903:         if ($actionurl eq '/adm/dependencies') {
                   9904:             if ($numnew) {
                   9905:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   9906:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   9907:                            $upload_output.'<br />'."\n";
                   9908:             }
                   9909:             if ($numexisting) {
                   9910:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   9911:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   9912:                            $modify_output.'<br />'."\n";
                   9913:                            $buttontext = &mt('Save changes');
                   9914:             }
                   9915:             if ($numunused) {
                   9916:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   9917:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   9918:                            $delete_output.'<br />'."\n";
                   9919:                            $buttontext = &mt('Save changes');
                   9920:             }
                   9921:         } else {
                   9922:             $output .= $upload_output.'<br />'."\n";
                   9923:         }
                   9924:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   9925:                    $counter.'" />'."\n";
                   9926:         if ($actionurl eq '/adm/dependencies') { 
                   9927:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   9928:                        $numnew.'" />'."\n";
                   9929:         } elsif ($actionurl eq '') {
1.987     raeburn  9930:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   9931:         }
                   9932:     } elsif ($applies) {
                   9933:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   9934:         if ($applies > 1) {
                   9935:             $output .=  
                   9936:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
                   9937:             if ($numremref) {
                   9938:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   9939:             }
                   9940:             if ($numinvalid) {
                   9941:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   9942:             }
                   9943:             if ($numexisting) {
                   9944:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   9945:             }
                   9946:             $output .= '</ul><br />';
                   9947:         } elsif ($numremref) {
                   9948:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   9949:         } elsif ($numinvalid) {
                   9950:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   9951:         } elsif ($numexisting) {
                   9952:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   9953:         }
                   9954:         $output .= $upload_output.'<br />';
                   9955:     }
                   9956:     my ($pathchange_output,$chgcount);
1.1071    raeburn  9957:     $chgcount = $counter;
1.987     raeburn  9958:     if (keys(%pathchanges) > 0) {
                   9959:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  9960:             if ($counter) {
1.987     raeburn  9961:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   9962:                                                   $embed_file,\%mapping,
1.1071    raeburn  9963:                                                   $allfiles,$codebase,'change');
1.987     raeburn  9964:             } else {
                   9965:                 $pathchange_output .= 
                   9966:                     &start_data_table_row().
                   9967:                     '<td><input type ="checkbox" name="namechange" value="'.
                   9968:                     $chgcount.'" checked="checked" /></td>'.
                   9969:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   9970:                     '<td>'.$embed_file.
                   9971:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  9972:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  9973:                     '</td>'.&end_data_table_row();
1.660     raeburn  9974:             }
1.987     raeburn  9975:             $numpathchg ++;
                   9976:             $chgcount ++;
1.660     raeburn  9977:         }
                   9978:     }
1.1071    raeburn  9979:     if ($counter) {
1.987     raeburn  9980:         if ($numpathchg) {
                   9981:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   9982:                        $numpathchg.'" />'."\n";
                   9983:         }
                   9984:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   9985:             ($actionurl eq '/adm/imsimport')) {
                   9986:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   9987:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   9988:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  9989:         } elsif ($actionurl eq '/adm/dependencies') {
                   9990:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  9991:         }
1.1071    raeburn  9992:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  9993:     } elsif ($numpathchg) {
                   9994:         my %pathchange = ();
                   9995:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   9996:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9997:             $output .= '<p>'.&mt('or').'</p>'; 
                   9998:         } 
                   9999:     }
1.1071    raeburn  10000:     return ($output,$counter,$numpathchg);
1.987     raeburn  10001: }
                   10002: 
                   10003: sub embedded_file_element {
1.1071    raeburn  10004:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10005:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10006:                    (ref($codebase) eq 'HASH'));
                   10007:     my $output;
1.1071    raeburn  10008:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10009:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10010:     }
                   10011:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10012:                &escape($embed_file).'" />';
                   10013:     unless (($context eq 'upload_embedded') && 
                   10014:             ($mapping->{$embed_file} eq $embed_file)) {
                   10015:         $output .='
                   10016:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10017:     }
                   10018:     my $attrib;
                   10019:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10020:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10021:     }
                   10022:     $output .=
                   10023:         "\n\t\t".
                   10024:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10025:         $attrib.'" />';
                   10026:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10027:         $output .=
                   10028:             "\n\t\t".
                   10029:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10030:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10031:     }
1.987     raeburn  10032:     return $output;
1.660     raeburn  10033: }
                   10034: 
1.1071    raeburn  10035: sub get_dependency_details {
                   10036:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10037:     my ($size,$mtime,$showsize,$showmtime);
                   10038:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10039:         if ($embed_file =~ m{/}) {
                   10040:             my ($path,$fname) = split(/\//,$embed_file);
                   10041:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10042:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10043:             }
                   10044:         } else {
                   10045:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10046:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10047:             }
                   10048:         }
                   10049:         $showsize = $size/1024.0;
                   10050:         $showsize = sprintf("%.1f",$showsize);
                   10051:         if ($mtime > 0) {
                   10052:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10053:         }
                   10054:     }
                   10055:     return ($showsize,$showmtime);
                   10056: }
                   10057: 
                   10058: sub ask_embedded_js {
                   10059:     return <<"END";
                   10060: <script type="text/javascript"">
                   10061: // <![CDATA[
                   10062: function toggleBrowse(counter) {
                   10063:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10064:     var fileid = document.getElementById('embedded_item_'+counter);
                   10065:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10066:     if (chkboxid.checked == true) {
                   10067:         uploaddivid.style.display='block';
                   10068:     } else {
                   10069:         uploaddivid.style.display='none';
                   10070:         fileid.value = '';
                   10071:     }
                   10072: }
                   10073: // ]]>
                   10074: </script>
                   10075: 
                   10076: END
                   10077: }
                   10078: 
1.661     raeburn  10079: sub upload_embedded {
                   10080:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10081:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10082:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10083:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10084:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10085:         my $orig_uploaded_filename =
                   10086:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10087:         foreach my $type ('orig','ref','attrib','codebase') {
                   10088:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10089:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10090:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10091:             }
                   10092:         }
1.661     raeburn  10093:         my ($path,$fname) =
                   10094:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10095:         # no path, whole string is fname
                   10096:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10097:         $fname = &Apache::lonnet::clean_filename($fname);
                   10098:         # See if there is anything left
                   10099:         next if ($fname eq '');
                   10100: 
                   10101:         # Check if file already exists as a file or directory.
                   10102:         my ($state,$msg);
                   10103:         if ($context eq 'portfolio') {
                   10104:             my $port_path = $dirpath;
                   10105:             if ($group ne '') {
                   10106:                 $port_path = "groups/$group/$port_path";
                   10107:             }
1.987     raeburn  10108:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10109:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10110:                                               $dir_root,$port_path,$disk_quota,
                   10111:                                               $current_disk_usage,$uname,$udom);
                   10112:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10113:                 || $state eq 'file_locked') {
1.661     raeburn  10114:                 $output .= $msg;
                   10115:                 next;
                   10116:             }
                   10117:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10118:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10119:             if ($state eq 'exists') {
                   10120:                 $output .= $msg;
                   10121:                 next;
                   10122:             }
                   10123:         }
                   10124:         # Check if extension is valid
                   10125:         if (($fname =~ /\.(\w+)$/) &&
                   10126:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.987     raeburn  10127:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
1.661     raeburn  10128:             next;
                   10129:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10130:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10131:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10132:             next;
                   10133:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10134:             $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  10135:             next;
                   10136:         }
                   10137:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   10138:         if ($context eq 'portfolio') {
1.984     raeburn  10139:             my $result;
                   10140:             if ($state eq 'existingfile') {
                   10141:                 $result=
                   10142:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.987     raeburn  10143:                                                     $dirpath.$env{'form.currentpath'}.$path);
1.661     raeburn  10144:             } else {
1.984     raeburn  10145:                 $result=
                   10146:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10147:                                                     $dirpath.
                   10148:                                                     $env{'form.currentpath'}.$path);
1.984     raeburn  10149:                 if ($result !~ m|^/uploaded/|) {
                   10150:                     $output .= '<span class="LC_error">'
                   10151:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10152:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10153:                                .'</span><br />';
                   10154:                     next;
                   10155:                 } else {
1.987     raeburn  10156:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10157:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10158:                 }
1.661     raeburn  10159:             }
1.987     raeburn  10160:         } elsif ($context eq 'coursedoc') {
                   10161:             my $result =
                   10162:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
                   10163:                                                 $dirpath.'/'.$path);
                   10164:             if ($result !~ m|^/uploaded/|) {
                   10165:                 $output .= '<span class="LC_error">'
                   10166:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10167:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10168:                            .'</span><br />';
                   10169:                     next;
                   10170:             } else {
                   10171:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10172:                            $path.$fname.'</span>').'<br />';
                   10173:             }
1.661     raeburn  10174:         } else {
                   10175: # Save the file
                   10176:             my $target = $env{'form.embedded_item_'.$i};
                   10177:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10178:             my $dest = $fullpath.$fname;
                   10179:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10180:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10181:             my $count;
                   10182:             my $filepath = $dir_root;
1.1027    raeburn  10183:             foreach my $subdir (@parts) {
                   10184:                 $filepath .= "/$subdir";
                   10185:                 if (!-e $filepath) {
1.661     raeburn  10186:                     mkdir($filepath,0770);
                   10187:                 }
                   10188:             }
                   10189:             my $fh;
                   10190:             if (!open($fh,'>'.$dest)) {
                   10191:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10192:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10193:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10194:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10195:                            '</span><br />';
                   10196:             } else {
                   10197:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10198:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10199:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10200:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10201:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10202:                               '</span><br />';
                   10203:                 } else {
1.987     raeburn  10204:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10205:                                $url.'</span>').'<br />';
                   10206:                     unless ($context eq 'testbank') {
                   10207:                         $footer .= &mt('View embedded file: [_1]',
                   10208:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10209:                     }
                   10210:                 }
                   10211:                 close($fh);
                   10212:             }
                   10213:         }
                   10214:         if ($env{'form.embedded_ref_'.$i}) {
                   10215:             $pathchange{$i} = 1;
                   10216:         }
                   10217:     }
                   10218:     if ($output) {
                   10219:         $output = '<p>'.$output.'</p>';
                   10220:     }
                   10221:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10222:     $returnflag = 'ok';
1.1071    raeburn  10223:     my $numpathchgs = scalar(keys(%pathchange));
                   10224:     if ($numpathchgs > 0) {
1.987     raeburn  10225:         if ($context eq 'portfolio') {
                   10226:             $output .= '<p>'.&mt('or').'</p>';
                   10227:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10228:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10229:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10230:             $returnflag = 'modify_orightml';
                   10231:         }
                   10232:     }
1.1071    raeburn  10233:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10234: }
                   10235: 
                   10236: sub modify_html_form {
                   10237:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10238:     my $end = 0;
                   10239:     my $modifyform;
                   10240:     if ($context eq 'upload_embedded') {
                   10241:         return unless (ref($pathchange) eq 'HASH');
                   10242:         if ($env{'form.number_embedded_items'}) {
                   10243:             $end += $env{'form.number_embedded_items'};
                   10244:         }
                   10245:         if ($env{'form.number_pathchange_items'}) {
                   10246:             $end += $env{'form.number_pathchange_items'};
                   10247:         }
                   10248:         if ($end) {
                   10249:             for (my $i=0; $i<$end; $i++) {
                   10250:                 if ($i < $env{'form.number_embedded_items'}) {
                   10251:                     next unless($pathchange->{$i});
                   10252:                 }
                   10253:                 $modifyform .=
                   10254:                     &start_data_table_row().
                   10255:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10256:                     'checked="checked" /></td>'.
                   10257:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10258:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10259:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10260:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10261:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10262:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10263:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10264:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10265:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10266:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10267:                     &end_data_table_row();
1.1071    raeburn  10268:             }
1.987     raeburn  10269:         }
                   10270:     } else {
                   10271:         $modifyform = $pathchgtable;
                   10272:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10273:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10274:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10275:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10276:         }
                   10277:     }
                   10278:     if ($modifyform) {
1.1071    raeburn  10279:         if ($actionurl eq '/adm/dependencies') {
                   10280:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10281:         }
1.987     raeburn  10282:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10283:                '<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".
                   10284:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10285:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10286:                '</ol></p>'."\n".'<p>'.
                   10287:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10288:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10289:                &start_data_table()."\n".
                   10290:                &start_data_table_header_row().
                   10291:                '<th>'.&mt('Change?').'</th>'.
                   10292:                '<th>'.&mt('Current reference').'</th>'.
                   10293:                '<th>'.&mt('Required reference').'</th>'.
                   10294:                &end_data_table_header_row()."\n".
                   10295:                $modifyform.
                   10296:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10297:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10298:                '</form>'."\n";
                   10299:     }
                   10300:     return;
                   10301: }
                   10302: 
                   10303: sub modify_html_refs {
                   10304:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
                   10305:     my $container;
                   10306:     if ($context eq 'portfolio') {
                   10307:         $container = $env{'form.container'};
                   10308:     } elsif ($context eq 'coursedoc') {
                   10309:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10310:     } elsif ($context eq 'manage_dependencies') {
                   10311:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10312:         $container = "/$container";
1.987     raeburn  10313:     } else {
1.1027    raeburn  10314:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10315:     }
                   10316:     my (%allfiles,%codebase,$output,$content);
                   10317:     my @changes = &get_env_multiple('form.namechange');
1.1071    raeburn  10318:     unless (@changes > 0) {
                   10319:         if (wantarray) {
                   10320:             return ('',0,0); 
                   10321:         } else {
                   10322:             return;
                   10323:         }
                   10324:     }
                   10325:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10326:         ($context eq 'manage_dependencies')) {
                   10327:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10328:             if (wantarray) {
                   10329:                 return ('',0,0);
                   10330:             } else {
                   10331:                 return;
                   10332:             }
                   10333:         } 
1.987     raeburn  10334:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10335:         if ($content eq '-1') {
                   10336:             if (wantarray) {
                   10337:                 return ('',0,0);
                   10338:             } else {
                   10339:                 return;
                   10340:             }
                   10341:         }
1.987     raeburn  10342:     } else {
1.1071    raeburn  10343:         unless ($container =~ /^\Q$dir_root\E/) {
                   10344:             if (wantarray) {
                   10345:                 return ('',0,0);
                   10346:             } else {
                   10347:                 return;
                   10348:             }
                   10349:         } 
1.987     raeburn  10350:         if (open(my $fh,"<$container")) {
                   10351:             $content = join('', <$fh>);
                   10352:             close($fh);
                   10353:         } else {
1.1071    raeburn  10354:             if (wantarray) {
                   10355:                 return ('',0,0);
                   10356:             } else {
                   10357:                 return;
                   10358:             }
1.987     raeburn  10359:         }
                   10360:     }
                   10361:     my ($count,$codebasecount) = (0,0);
                   10362:     my $mm = new File::MMagic;
                   10363:     my $mime_type = $mm->checktype_contents($content);
                   10364:     if ($mime_type eq 'text/html') {
                   10365:         my $parse_result = 
                   10366:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10367:                                                     \%codebase,\$content);
                   10368:         if ($parse_result eq 'ok') {
                   10369:             foreach my $i (@changes) {
                   10370:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10371:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10372:                 if ($allfiles{$ref}) {
                   10373:                     my $newname =  $orig;
                   10374:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10375:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10376:                     if ($attrib_regexp =~ /:/) {
                   10377:                         $attrib_regexp =~ s/\:/|/g;
                   10378:                     }
                   10379:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10380:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10381:                         $count += $numchg;
                   10382:                     }
                   10383:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10384:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10385:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10386:                         $codebasecount ++;
                   10387:                     }
                   10388:                 }
                   10389:             }
                   10390:             if ($count || $codebasecount) {
                   10391:                 my $saveresult;
1.1071    raeburn  10392:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10393:                     ($context eq 'manage_dependencies')) {
1.987     raeburn  10394:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10395:                     if ($url eq $container) {
                   10396:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10397:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10398:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10399:                                             $fname.'</span>').'</p>';
1.987     raeburn  10400:                     } else {
                   10401:                          $output = '<p class="LC_error">'.
                   10402:                                    &mt('Error: update failed for: [_1].',
                   10403:                                    '<span class="LC_filename">'.
                   10404:                                    $container.'</span>').'</p>';
                   10405:                     }
                   10406:                 } else {
                   10407:                     if (open(my $fh,">$container")) {
                   10408:                         print $fh $content;
                   10409:                         close($fh);
                   10410:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10411:                                   $count,'<span class="LC_filename">'.
                   10412:                                   $container.'</span>').'</p>';
1.661     raeburn  10413:                     } else {
1.987     raeburn  10414:                          $output = '<p class="LC_error">'.
                   10415:                                    &mt('Error: could not update [_1].',
                   10416:                                    '<span class="LC_filename">'.
                   10417:                                    $container.'</span>').'</p>';
1.661     raeburn  10418:                     }
                   10419:                 }
                   10420:             }
1.987     raeburn  10421:         } else {
                   10422:             &logthis('Failed to parse '.$container.
                   10423:                      ' to modify references: '.$parse_result);
1.661     raeburn  10424:         }
                   10425:     }
1.1071    raeburn  10426:     if (wantarray) {
                   10427:         return ($output,$count,$codebasecount);
                   10428:     } else {
                   10429:         return $output;
                   10430:     }
1.661     raeburn  10431: }
                   10432: 
                   10433: sub check_for_existing {
                   10434:     my ($path,$fname,$element) = @_;
                   10435:     my ($state,$msg);
                   10436:     if (-d $path.'/'.$fname) {
                   10437:         $state = 'exists';
                   10438:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10439:     } elsif (-e $path.'/'.$fname) {
                   10440:         $state = 'exists';
                   10441:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10442:     }
                   10443:     if ($state eq 'exists') {
                   10444:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10445:     }
                   10446:     return ($state,$msg);
                   10447: }
                   10448: 
                   10449: sub check_for_upload {
                   10450:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10451:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10452:     my $filesize = length($env{'form.'.$element});
                   10453:     if (!$filesize) {
                   10454:         my $msg = '<span class="LC_error">'.
                   10455:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10456:                       '<span class="LC_filename">'.$fname.'</span>',
                   10457:                       $filesize).'<br />'.
1.1007    raeburn  10458:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10459:                   '</span>';
                   10460:         return ('zero_bytes',$msg);
                   10461:     }
                   10462:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10463:     my $getpropath = 1;
1.1021    raeburn  10464:     my ($dirlistref,$listerror) =
                   10465:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10466:     my $found_file = 0;
                   10467:     my $locked_file = 0;
1.991     raeburn  10468:     my @lockers;
                   10469:     my $navmap;
                   10470:     if ($env{'request.course.id'}) {
                   10471:         $navmap = Apache::lonnavmaps::navmap->new();
                   10472:     }
1.1021    raeburn  10473:     if (ref($dirlistref) eq 'ARRAY') {
                   10474:         foreach my $line (@{$dirlistref}) {
                   10475:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10476:             if ($file_name eq $fname){
                   10477:                 $file_name = $path.$file_name;
                   10478:                 if ($group ne '') {
                   10479:                     $file_name = $group.$file_name;
                   10480:                 }
                   10481:                 $found_file = 1;
                   10482:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10483:                     foreach my $lock (@lockers) {
                   10484:                         if (ref($lock) eq 'ARRAY') {
                   10485:                             my ($symb,$crsid) = @{$lock};
                   10486:                             if ($crsid eq $env{'request.course.id'}) {
                   10487:                                 if (ref($navmap)) {
                   10488:                                     my $res = $navmap->getBySymb($symb);
                   10489:                                     foreach my $part (@{$res->parts()}) { 
                   10490:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10491:                                         unless (($slot_status == $res->RESERVED) ||
                   10492:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10493:                                             $locked_file = 1;
                   10494:                                         }
1.991     raeburn  10495:                                     }
1.1021    raeburn  10496:                                 } else {
                   10497:                                     $locked_file = 1;
1.991     raeburn  10498:                                 }
                   10499:                             } else {
                   10500:                                 $locked_file = 1;
                   10501:                             }
                   10502:                         }
1.1021    raeburn  10503:                    }
                   10504:                 } else {
                   10505:                     my @info = split(/\&/,$rest);
                   10506:                     my $currsize = $info[6]/1000;
                   10507:                     if ($currsize < $filesize) {
                   10508:                         my $extra = $filesize - $currsize;
                   10509:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10510:                             my $msg = '<span class="LC_error">'.
                   10511:                                       &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.',
                   10512:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10513:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10514:                                                    $disk_quota,$current_disk_usage);
                   10515:                             return ('will_exceed_quota',$msg);
                   10516:                         }
1.984     raeburn  10517:                     }
                   10518:                 }
1.661     raeburn  10519:             }
                   10520:         }
                   10521:     }
                   10522:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10523:         my $msg = '<span class="LC_error">'.
                   10524:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10525:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10526:         return ('will_exceed_quota',$msg);
                   10527:     } elsif ($found_file) {
                   10528:         if ($locked_file) {
                   10529:             my $msg = '<span class="LC_error">';
                   10530:             $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>');
                   10531:             $msg .= '</span><br />';
                   10532:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10533:             return ('file_locked',$msg);
                   10534:         } else {
                   10535:             my $msg = '<span class="LC_error">';
1.984     raeburn  10536:             $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  10537:             $msg .= '</span>';
1.984     raeburn  10538:             return ('existingfile',$msg);
1.661     raeburn  10539:         }
                   10540:     }
                   10541: }
                   10542: 
1.987     raeburn  10543: sub check_for_traversal {
                   10544:     my ($path,$url,$toplevel) = @_;
                   10545:     my @parts=split(/\//,$path);
                   10546:     my $cleanpath;
                   10547:     my $fullpath = $url;
                   10548:     for (my $i=0;$i<@parts;$i++) {
                   10549:         next if ($parts[$i] eq '.');
                   10550:         if ($parts[$i] eq '..') {
                   10551:             $fullpath =~ s{([^/]+/)$}{};
                   10552:         } else {
                   10553:             $fullpath .= $parts[$i].'/';
                   10554:         }
                   10555:     }
                   10556:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10557:         $cleanpath = $1;
                   10558:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10559:         my $curr_toprel = $1;
                   10560:         my @parts = split(/\//,$curr_toprel);
                   10561:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10562:         my @urlparts = split(/\//,$url_toprel);
                   10563:         my $doubledots;
                   10564:         my $startdiff = -1;
                   10565:         for (my $i=0; $i<@urlparts; $i++) {
                   10566:             if ($startdiff == -1) {
                   10567:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10568:                     $startdiff = $i;
                   10569:                     $doubledots .= '../';
                   10570:                 }
                   10571:             } else {
                   10572:                 $doubledots .= '../';
                   10573:             }
                   10574:         }
                   10575:         if ($startdiff > -1) {
                   10576:             $cleanpath = $doubledots;
                   10577:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10578:                 $cleanpath .= $parts[$i].'/';
                   10579:             }
                   10580:         }
                   10581:     }
                   10582:     $cleanpath =~ s{(/)$}{};
                   10583:     return $cleanpath;
                   10584: }
1.31      albertel 10585: 
1.1053    raeburn  10586: sub is_archive_file {
                   10587:     my ($mimetype) = @_;
                   10588:     if (($mimetype eq 'application/octet-stream') ||
                   10589:         ($mimetype eq 'application/x-stuffit') ||
                   10590:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10591:         return 1;
                   10592:     }
                   10593:     return;
                   10594: }
                   10595: 
                   10596: sub decompress_form {
1.1065    raeburn  10597:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10598:     my %lt = &Apache::lonlocal::texthash (
                   10599:         this => 'This file is an archive file.',
1.1067    raeburn  10600:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10601:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10602:         youm => 'You may wish to extract its contents.',
                   10603:         extr => 'Extract contents',
1.1067    raeburn  10604:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10605:         proa => 'Process automatically?',
1.1053    raeburn  10606:         yes  => 'Yes',
                   10607:         no   => 'No',
1.1067    raeburn  10608:         fold => 'Title for folder containing movie',
                   10609:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10610:     );
1.1065    raeburn  10611:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10612:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10613:     my $info = &list_archive_contents($fileloc,\@paths);
                   10614:     if (@paths) {
                   10615:         foreach my $path (@paths) {
                   10616:             $path =~ s{^/}{};
1.1067    raeburn  10617:             if ($path =~ m{^([^/]+)/$}) {
                   10618:                 $topdir = $1;
                   10619:             }
1.1065    raeburn  10620:             if ($path =~ m{^([^/]+)/}) {
                   10621:                 $toplevel{$1} = $path;
                   10622:             } else {
                   10623:                 $toplevel{$path} = $path;
                   10624:             }
                   10625:         }
                   10626:     }
1.1067    raeburn  10627:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
                   10628:         my @camtasia = ("$topdir/","$topdir/index.html",
                   10629:                         "$topdir/media/",
                   10630:                         "$topdir/media/$topdir.mp4",
                   10631:                         "$topdir/media/FirstFrame.png",
                   10632:                         "$topdir/media/player.swf",
                   10633:                         "$topdir/media/swfobject.js",
                   10634:                         "$topdir/media/expressInstall.swf");
                   10635:         my @diffs = &compare_arrays(\@paths,\@camtasia);
                   10636:         if (@diffs == 0) {
                   10637:             $is_camtasia = 1;
                   10638:         }
                   10639:     }
                   10640:     my $output;
                   10641:     if ($is_camtasia) {
                   10642:         $output = <<"ENDCAM";
                   10643: <script type="text/javascript" language="Javascript">
                   10644: // <![CDATA[
                   10645: 
                   10646: function camtasiaToggle() {
                   10647:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   10648:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
                   10649:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
                   10650: 
                   10651:                 document.getElementById('camtasia_titles').style.display='block';
                   10652:             } else {
                   10653:                 document.getElementById('camtasia_titles').style.display='none';
                   10654:             }
                   10655:         }
                   10656:     }
                   10657:     return;
                   10658: }
                   10659: 
                   10660: // ]]>
                   10661: </script>
                   10662: <p>$lt{'camt'}</p>
                   10663: ENDCAM
1.1065    raeburn  10664:     } else {
1.1067    raeburn  10665:         $output = '<p>'.$lt{'this'};
                   10666:         if ($info eq '') {
                   10667:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   10668:         } else {
                   10669:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   10670:                        '<div><pre>'.$info.'</pre></div>';
                   10671:         }
1.1065    raeburn  10672:     }
1.1067    raeburn  10673:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  10674:     my $duplicates;
                   10675:     my $num = 0;
                   10676:     if (ref($dirlist) eq 'ARRAY') {
                   10677:         foreach my $item (@{$dirlist}) {
                   10678:             if (ref($item) eq 'ARRAY') {
                   10679:                 if (exists($toplevel{$item->[0]})) {
                   10680:                     $duplicates .= 
                   10681:                         &start_data_table_row().
                   10682:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10683:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   10684:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10685:                         'value="1" />'.&mt('Yes').'</label>'.
                   10686:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   10687:                         '<td>'.$item->[0].'</td>';
                   10688:                     if ($item->[2]) {
                   10689:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   10690:                     } else {
                   10691:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   10692:                     }
                   10693:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   10694:                                    '<td>'.
                   10695:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   10696:                                    '</td>'.
                   10697:                                    &end_data_table_row();
                   10698:                     $num ++;
                   10699:                 }
                   10700:             }
                   10701:         }
                   10702:     }
                   10703:     my $itemcount;
                   10704:     if (@paths > 0) {
                   10705:         $itemcount = scalar(@paths);
                   10706:     } else {
                   10707:         $itemcount = 1;
                   10708:     }
1.1067    raeburn  10709:     if ($is_camtasia) {
                   10710:         $output .= $lt{'auto'}.'<br />'.
                   10711:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
                   10712:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
                   10713:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   10714:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   10715:                    $lt{'no'}.'</label></span><br />'.
                   10716:                    '<div id="camtasia_titles" style="display:block">'.
                   10717:                    &Apache::lonhtmlcommon::start_pick_box().
                   10718:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   10719:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   10720:                    &Apache::lonhtmlcommon::row_closure().
                   10721:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   10722:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   10723:                    &Apache::lonhtmlcommon::row_closure(1).
                   10724:                    &Apache::lonhtmlcommon::end_pick_box().
                   10725:                    '</div>';
                   10726:     }
1.1065    raeburn  10727:     $output .= 
                   10728:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  10729:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   10730:         "\n";
1.1065    raeburn  10731:     if ($duplicates ne '') {
                   10732:         $output .= '<p><span class="LC_warning">'.
                   10733:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   10734:                    &start_data_table().
                   10735:                    &start_data_table_header_row().
                   10736:                    '<th>'.&mt('Overwrite?').'</th>'.
                   10737:                    '<th>'.&mt('Name').'</th>'.
                   10738:                    '<th>'.&mt('Type').'</th>'.
                   10739:                    '<th>'.&mt('Size').'</th>'.
                   10740:                    '<th>'.&mt('Last modified').'</th>'.
                   10741:                    &end_data_table_header_row().
                   10742:                    $duplicates.
                   10743:                    &end_data_table().
                   10744:                    '</p>';
                   10745:     }
1.1067    raeburn  10746:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  10747:     if (ref($hiddenelements) eq 'HASH') {
                   10748:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   10749:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   10750:         }
                   10751:     }
                   10752:     $output .= <<"END";
1.1067    raeburn  10753: <br />
1.1053    raeburn  10754: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   10755: </form>
                   10756: $noextract
                   10757: END
                   10758:     return $output;
                   10759: }
                   10760: 
1.1065    raeburn  10761: sub decompression_utility {
                   10762:     my ($program) = @_;
                   10763:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   10764:     my $location;
                   10765:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   10766:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   10767:                          '/usr/sbin/') {
                   10768:             if (-x $dir.$program) {
                   10769:                 $location = $dir.$program;
                   10770:                 last;
                   10771:             }
                   10772:         }
                   10773:     }
                   10774:     return $location;
                   10775: }
                   10776: 
                   10777: sub list_archive_contents {
                   10778:     my ($file,$pathsref) = @_;
                   10779:     my (@cmd,$output);
                   10780:     my $needsregexp;
                   10781:     if ($file =~ /\.zip$/) {
                   10782:         @cmd = (&decompression_utility('unzip'),"-l");
                   10783:         $needsregexp = 1;
                   10784:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   10785:              ($file =~ /\.tgz$/)) {
                   10786:         @cmd = (&decompression_utility('tar'),"-ztf");
                   10787:     } elsif ($file =~ /\.tar\.bz2$/) {
                   10788:         @cmd = (&decompression_utility('tar'),"-jtf");
                   10789:     } elsif ($file =~ m|\.tar$|) {
                   10790:         @cmd = (&decompression_utility('tar'),"-tf");
                   10791:     }
                   10792:     if (@cmd) {
                   10793:         undef($!);
                   10794:         undef($@);
                   10795:         if (open(my $fh,"-|", @cmd, $file)) {
                   10796:             while (my $line = <$fh>) {
                   10797:                 $output .= $line;
                   10798:                 chomp($line);
                   10799:                 my $item;
                   10800:                 if ($needsregexp) {
                   10801:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   10802:                 } else {
                   10803:                     $item = $line;
                   10804:                 }
                   10805:                 if ($item ne '') {
                   10806:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   10807:                         push(@{$pathsref},$item);
                   10808:                     } 
                   10809:                 }
                   10810:             }
                   10811:             close($fh);
                   10812:         }
                   10813:     }
                   10814:     return $output;
                   10815: }
                   10816: 
1.1053    raeburn  10817: sub decompress_uploaded_file {
                   10818:     my ($file,$dir) = @_;
                   10819:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   10820:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   10821:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   10822:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   10823:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   10824:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   10825:     my $decompressed = $env{'cgi.decompressed'};
                   10826:     &Apache::lonnet::delenv('cgi.file');
                   10827:     &Apache::lonnet::delenv('cgi.dir');
                   10828:     &Apache::lonnet::delenv('cgi.decompressed');
                   10829:     return ($decompressed,$result);
                   10830: }
                   10831: 
1.1055    raeburn  10832: sub process_decompression {
                   10833:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   10834:     my ($dir,$error,$warning,$output);
                   10835:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
1.1120    bisitz   10836:         $error = &mt('Filename not a supported archive file type.').
                   10837:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  10838:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   10839:     } else {
                   10840:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   10841:         if ($docuhome eq 'no_host') {
                   10842:             $error = &mt('Could not determine home server for course.');
                   10843:         } else {
                   10844:             my @ids=&Apache::lonnet::current_machine_ids();
                   10845:             my $currdir = "$dir_root/$destination";
                   10846:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   10847:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   10848:                        "$dir_root/$destination";
                   10849:             } else {
                   10850:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   10851:                        "$dir_root/$docudom/$docuname/$destination";
                   10852:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   10853:                     $error = &mt('Archive file not found.');
                   10854:                 }
                   10855:             }
1.1065    raeburn  10856:             my (@to_overwrite,@to_skip);
                   10857:             if ($env{'form.archive_overwrite_total'} > 0) {
                   10858:                 my $total = $env{'form.archive_overwrite_total'};
                   10859:                 for (my $i=0; $i<$total; $i++) {
                   10860:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   10861:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   10862:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   10863:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   10864:                     }
                   10865:                 }
                   10866:             }
                   10867:             my $numskip = scalar(@to_skip);
                   10868:             if (($numskip > 0) && 
                   10869:                 ($numskip == $env{'form.archive_itemcount'})) {
                   10870:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   10871:             } elsif ($dir eq '') {
1.1055    raeburn  10872:                 $error = &mt('Directory containing archive file unavailable.');
                   10873:             } elsif (!$error) {
1.1065    raeburn  10874:                 my ($decompressed,$display);
                   10875:                 if ($numskip > 0) {
                   10876:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   10877:                     mkdir("$dir/$tempdir",0755);
                   10878:                     system("mv $dir/$file $dir/$tempdir/$file");
                   10879:                     ($decompressed,$display) = 
                   10880:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   10881:                     foreach my $item (@to_skip) {
                   10882:                         if (($item ne '') && ($item !~ /\.\./)) {
                   10883:                             if (-f "$dir/$tempdir/$item") { 
                   10884:                                 unlink("$dir/$tempdir/$item");
                   10885:                             } elsif (-d "$dir/$tempdir/$item") {
                   10886:                                 system("rm -rf $dir/$tempdir/$item");
                   10887:                             }
                   10888:                         }
                   10889:                     }
                   10890:                     system("mv $dir/$tempdir/* $dir");
                   10891:                     rmdir("$dir/$tempdir");   
                   10892:                 } else {
                   10893:                     ($decompressed,$display) = 
                   10894:                         &decompress_uploaded_file($file,$dir);
                   10895:                 }
1.1055    raeburn  10896:                 if ($decompressed eq 'ok') {
1.1065    raeburn  10897:                     $output = '<p class="LC_info">'.
                   10898:                               &mt('Files extracted successfully from archive.').
                   10899:                               '</p>'."\n";
1.1055    raeburn  10900:                     my ($warning,$result,@contents);
                   10901:                     my ($newdirlistref,$newlisterror) =
                   10902:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   10903:                                                  $docuname,1);
                   10904:                     my (%is_dir,%changes,@newitems);
                   10905:                     my $dirptr = 16384;
1.1065    raeburn  10906:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  10907:                         foreach my $dir_line (@{$newdirlistref}) {
                   10908:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  10909:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   10910:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  10911:                                 push(@newitems,$item);
                   10912:                                 if ($dirptr&$testdir) {
                   10913:                                     $is_dir{$item} = 1;
                   10914:                                 }
                   10915:                                 $changes{$item} = 1;
                   10916:                             }
                   10917:                         }
                   10918:                     }
                   10919:                     if (keys(%changes) > 0) {
                   10920:                         foreach my $item (sort(@newitems)) {
                   10921:                             if ($changes{$item}) {
                   10922:                                 push(@contents,$item);
                   10923:                             }
                   10924:                         }
                   10925:                     }
                   10926:                     if (@contents > 0) {
1.1067    raeburn  10927:                         my $wantform;
                   10928:                         unless ($env{'form.autoextract_camtasia'}) {
                   10929:                             $wantform = 1;
                   10930:                         }
1.1056    raeburn  10931:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  10932:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   10933:                                                                 $currdir,\%is_dir,
                   10934:                                                                 \%children,\%parent,
1.1056    raeburn  10935:                                                                 \@contents,\%dirorder,
                   10936:                                                                 \%titles,$wantform);
1.1055    raeburn  10937:                         if ($datatable ne '') {
                   10938:                             $output .= &archive_options_form('decompressed',$datatable,
                   10939:                                                              $count,$hiddenelem);
1.1065    raeburn  10940:                             my $startcount = 6;
1.1055    raeburn  10941:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  10942:                                                            \%titles,\%children);
1.1055    raeburn  10943:                         }
1.1067    raeburn  10944:                         if ($env{'form.autoextract_camtasia'}) {
                   10945:                             my %displayed;
                   10946:                             my $total = 1;
                   10947:                             $env{'form.archive_directory'} = [];
                   10948:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   10949:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   10950:                                 $path =~ s{/$}{};
                   10951:                                 my $item;
                   10952:                                 if ($path ne '') {
                   10953:                                     $item = "$path/$titles{$i}";
                   10954:                                 } else {
                   10955:                                     $item = $titles{$i};
                   10956:                                 }
                   10957:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   10958:                                 if ($item eq $contents[0]) {
                   10959:                                     push(@{$env{'form.archive_directory'}},$i);
                   10960:                                     $env{'form.archive_'.$i} = 'display';
                   10961:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   10962:                                     $displayed{'folder'} = $i;
                   10963:                                 } elsif ($item eq "$contents[0]/index.html") {
                   10964:                                     $env{'form.archive_'.$i} = 'display';
                   10965:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   10966:                                     $displayed{'web'} = $i;
                   10967:                                 } else {
                   10968:                                     if ($item eq "$contents[0]/media") {
                   10969:                                         push(@{$env{'form.archive_directory'}},$i);
                   10970:                                     }
                   10971:                                     $env{'form.archive_'.$i} = 'dependency';
                   10972:                                 }
                   10973:                                 $total ++;
                   10974:                             }
                   10975:                             for (my $i=1; $i<$total; $i++) {
                   10976:                                 next if ($i == $displayed{'web'});
                   10977:                                 next if ($i == $displayed{'folder'});
                   10978:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   10979:                             }
                   10980:                             $env{'form.phase'} = 'decompress_cleanup';
                   10981:                             $env{'form.archivedelete'} = 1;
                   10982:                             $env{'form.archive_count'} = $total-1;
                   10983:                             $output .=
                   10984:                                 &process_extracted_files('coursedocs',$docudom,
                   10985:                                                          $docuname,$destination,
                   10986:                                                          $dir_root,$hiddenelem);
                   10987:                         }
1.1055    raeburn  10988:                     } else {
                   10989:                         $warning = &mt('No new items extracted from archive file.');
                   10990:                     }
                   10991:                 } else {
                   10992:                     $output = $display;
                   10993:                     $error = &mt('An error occurred during extraction from the archive file.');
                   10994:                 }
                   10995:             }
                   10996:         }
                   10997:     }
                   10998:     if ($error) {
                   10999:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11000:                    $error.'</p>'."\n";
                   11001:     }
                   11002:     if ($warning) {
                   11003:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11004:     }
                   11005:     return $output;
                   11006: }
                   11007: 
                   11008: sub get_extracted {
1.1056    raeburn  11009:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11010:         $titles,$wantform) = @_;
1.1055    raeburn  11011:     my $count = 0;
                   11012:     my $depth = 0;
                   11013:     my $datatable;
1.1056    raeburn  11014:     my @hierarchy;
1.1055    raeburn  11015:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11016:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11017:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11018:     foreach my $item (@{$contents}) {
                   11019:         $count ++;
1.1056    raeburn  11020:         @{$dirorder->{$count}} = @hierarchy;
                   11021:         $titles->{$count} = $item;
1.1055    raeburn  11022:         &archive_hierarchy($depth,$count,$parent,$children);
                   11023:         if ($wantform) {
                   11024:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11025:                                        $currdir,$depth,$count);
                   11026:         }
                   11027:         if ($is_dir->{$item}) {
                   11028:             $depth ++;
1.1056    raeburn  11029:             push(@hierarchy,$count);
                   11030:             $parent->{$depth} = $count;
1.1055    raeburn  11031:             $datatable .=
                   11032:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11033:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11034:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11035:             $depth --;
1.1056    raeburn  11036:             pop(@hierarchy);
1.1055    raeburn  11037:         }
                   11038:     }
                   11039:     return ($count,$datatable);
                   11040: }
                   11041: 
                   11042: sub recurse_extracted_archive {
1.1056    raeburn  11043:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11044:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11045:     my $result='';
1.1056    raeburn  11046:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11047:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11048:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11049:         return $result;
                   11050:     }
                   11051:     my $dirptr = 16384;
                   11052:     my ($newdirlistref,$newlisterror) =
                   11053:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11054:     if (ref($newdirlistref) eq 'ARRAY') {
                   11055:         foreach my $dir_line (@{$newdirlistref}) {
                   11056:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11057:             unless ($item =~ /^\.+$/) {
                   11058:                 $$count ++;
1.1056    raeburn  11059:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11060:                 $titles->{$$count} = $item;
1.1055    raeburn  11061:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11062: 
1.1055    raeburn  11063:                 my $is_dir;
                   11064:                 if ($dirptr&$testdir) {
                   11065:                     $is_dir = 1;
                   11066:                 }
                   11067:                 if ($wantform) {
                   11068:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11069:                 }
                   11070:                 if ($is_dir) {
                   11071:                     $$depth ++;
1.1056    raeburn  11072:                     push(@{$hierarchy},$$count);
                   11073:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11074:                     $result .=
                   11075:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11076:                                                    $docuname,$depth,$count,
1.1056    raeburn  11077:                                                    $hierarchy,$dirorder,$children,
                   11078:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11079:                     $$depth --;
1.1056    raeburn  11080:                     pop(@{$hierarchy});
1.1055    raeburn  11081:                 }
                   11082:             }
                   11083:         }
                   11084:     }
                   11085:     return $result;
                   11086: }
                   11087: 
                   11088: sub archive_hierarchy {
                   11089:     my ($depth,$count,$parent,$children) =@_;
                   11090:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11091:         if (exists($parent->{$depth})) {
                   11092:              $children->{$parent->{$depth}} .= $count.':';
                   11093:         }
                   11094:     }
                   11095:     return;
                   11096: }
                   11097: 
                   11098: sub archive_row {
                   11099:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11100:     my ($name) = ($item =~ m{([^/]+)$});
                   11101:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11102:                                        'display'    => 'Add as file',
1.1055    raeburn  11103:                                        'dependency' => 'Include as dependency',
                   11104:                                        'discard'    => 'Discard',
                   11105:                                       );
                   11106:     if ($is_dir) {
1.1059    raeburn  11107:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11108:     }
1.1056    raeburn  11109:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11110:     my $offset = 0;
1.1055    raeburn  11111:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11112:         $offset ++;
1.1065    raeburn  11113:         if ($action ne 'display') {
                   11114:             $offset ++;
                   11115:         }  
1.1055    raeburn  11116:         $output .= '<td><span class="LC_nobreak">'.
                   11117:                    '<label><input type="radio" name="archive_'.$count.
                   11118:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11119:         my $text = $choices{$action};
                   11120:         if ($is_dir) {
                   11121:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11122:             if ($action eq 'display') {
1.1059    raeburn  11123:                 $text = &mt('Add as folder');
1.1055    raeburn  11124:             }
1.1056    raeburn  11125:         } else {
                   11126:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11127: 
                   11128:         }
                   11129:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11130:         if ($action eq 'dependency') {
                   11131:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11132:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11133:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11134:                        '<option value=""></option>'."\n".
                   11135:                        '</select>'."\n".
                   11136:                        '</div>';
1.1059    raeburn  11137:         } elsif ($action eq 'display') {
                   11138:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11139:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11140:                        '</div>';
1.1055    raeburn  11141:         }
1.1056    raeburn  11142:         $output .= '</td>';
1.1055    raeburn  11143:     }
                   11144:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11145:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11146:     for (my $i=0; $i<$depth; $i++) {
                   11147:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11148:     }
                   11149:     if ($is_dir) {
                   11150:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11151:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11152:     } else {
                   11153:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11154:     }
                   11155:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11156:                &end_data_table_row();
                   11157:     return $output;
                   11158: }
                   11159: 
                   11160: sub archive_options_form {
1.1065    raeburn  11161:     my ($form,$display,$count,$hiddenelem) = @_;
                   11162:     my %lt = &Apache::lonlocal::texthash(
                   11163:                perm => 'Permanently remove archive file?',
                   11164:                hows => 'How should each extracted item be incorporated in the course?',
                   11165:                cont => 'Content actions for all',
                   11166:                addf => 'Add as folder/file',
                   11167:                incd => 'Include as dependency for a displayed file',
                   11168:                disc => 'Discard',
                   11169:                no   => 'No',
                   11170:                yes  => 'Yes',
                   11171:                save => 'Save',
                   11172:     );
                   11173:     my $output = <<"END";
                   11174: <form name="$form" method="post" action="">
                   11175: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11176: <label>
                   11177:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11178: </label>
                   11179: &nbsp;
                   11180: <label>
                   11181:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11182: </span>
                   11183: </p>
                   11184: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11185: <br />$lt{'hows'}
                   11186: <div class="LC_columnSection">
                   11187:   <fieldset>
                   11188:     <legend>$lt{'cont'}</legend>
                   11189:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11190:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11191:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11192:   </fieldset>
                   11193: </div>
                   11194: END
                   11195:     return $output.
1.1055    raeburn  11196:            &start_data_table()."\n".
1.1065    raeburn  11197:            $display."\n".
1.1055    raeburn  11198:            &end_data_table()."\n".
                   11199:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11200:            $hiddenelem.
1.1065    raeburn  11201:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11202:            '</form>';
                   11203: }
                   11204: 
                   11205: sub archive_javascript {
1.1056    raeburn  11206:     my ($startcount,$numitems,$titles,$children) = @_;
                   11207:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11208:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11209:     my $scripttag = <<START;
                   11210: <script type="text/javascript">
                   11211: // <![CDATA[
                   11212: 
                   11213: function checkAll(form,prefix) {
                   11214:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11215:     for (var i=0; i < form.elements.length; i++) {
                   11216:         var id = form.elements[i].id;
                   11217:         if ((id != '') && (id != undefined)) {
                   11218:             if (idstr.test(id)) {
                   11219:                 if (form.elements[i].type == 'radio') {
                   11220:                     form.elements[i].checked = true;
1.1056    raeburn  11221:                     var nostart = i-$startcount;
1.1059    raeburn  11222:                     var offset = nostart%7;
                   11223:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11224:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11225:                 }
                   11226:             }
                   11227:         }
                   11228:     }
                   11229: }
                   11230: 
                   11231: function propagateCheck(form,count) {
                   11232:     if (count > 0) {
1.1059    raeburn  11233:         var startelement = $startcount + ((count-1) * 7);
                   11234:         for (var j=1; j<6; j++) {
                   11235:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11236:                 var item = startelement + j; 
                   11237:                 if (form.elements[item].type == 'radio') {
                   11238:                     if (form.elements[item].checked) {
                   11239:                         containerCheck(form,count,j);
                   11240:                         break;
                   11241:                     }
1.1055    raeburn  11242:                 }
                   11243:             }
                   11244:         }
                   11245:     }
                   11246: }
                   11247: 
                   11248: numitems = $numitems
1.1056    raeburn  11249: var titles = new Array(numitems);
                   11250: var parents = new Array(numitems);
1.1055    raeburn  11251: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11252:     parents[i] = new Array;
1.1055    raeburn  11253: }
1.1059    raeburn  11254: var maintitle = '$maintitle';
1.1055    raeburn  11255: 
                   11256: START
                   11257: 
1.1056    raeburn  11258:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11259:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11260:         for (my $i=0; $i<@contents; $i ++) {
                   11261:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11262:         }
                   11263:     }
                   11264: 
1.1056    raeburn  11265:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11266:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11267:     }
                   11268: 
1.1055    raeburn  11269:     $scripttag .= <<END;
                   11270: 
                   11271: function containerCheck(form,count,offset) {
                   11272:     if (count > 0) {
1.1056    raeburn  11273:         dependencyCheck(form,count,offset);
1.1059    raeburn  11274:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11275:         form.elements[item].checked = true;
                   11276:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11277:             if (parents[count].length > 0) {
                   11278:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11279:                     containerCheck(form,parents[count][j],offset);
                   11280:                 }
                   11281:             }
                   11282:         }
                   11283:     }
                   11284: }
                   11285: 
                   11286: function dependencyCheck(form,count,offset) {
                   11287:     if (count > 0) {
1.1059    raeburn  11288:         var chosen = (offset+$startcount)+7*(count-1);
                   11289:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11290:         var currtype = form.elements[depitem].type;
                   11291:         if (form.elements[chosen].value == 'dependency') {
                   11292:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11293:             form.elements[depitem].options.length = 0;
                   11294:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  11295:             for (var i=1; i<=numitems; i++) {
                   11296:                 if (i == count) {
                   11297:                     continue;
                   11298:                 }
1.1059    raeburn  11299:                 var startelement = $startcount + (i-1) * 7;
                   11300:                 for (var j=1; j<6; j++) {
                   11301:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11302:                         var item = startelement + j;
                   11303:                         if (form.elements[item].type == 'radio') {
                   11304:                             if (form.elements[item].checked) {
                   11305:                                 if (form.elements[item].value == 'display') {
                   11306:                                     var n = form.elements[depitem].options.length;
                   11307:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11308:                                 }
                   11309:                             }
                   11310:                         }
                   11311:                     }
                   11312:                 }
                   11313:             }
                   11314:         } else {
                   11315:             document.getElementById('arc_depon_'+count).style.display='none';
                   11316:             form.elements[depitem].options.length = 0;
                   11317:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11318:         }
1.1059    raeburn  11319:         titleCheck(form,count,offset);
1.1056    raeburn  11320:     }
                   11321: }
                   11322: 
                   11323: function propagateSelect(form,count,offset) {
                   11324:     if (count > 0) {
1.1065    raeburn  11325:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11326:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11327:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11328:             if (parents[count].length > 0) {
                   11329:                 for (var j=0; j<parents[count].length; j++) {
                   11330:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11331:                 }
                   11332:             }
                   11333:         }
                   11334:     }
                   11335: }
1.1056    raeburn  11336: 
                   11337: function containerSelect(form,count,offset,picked) {
                   11338:     if (count > 0) {
1.1065    raeburn  11339:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11340:         if (form.elements[item].type == 'radio') {
                   11341:             if (form.elements[item].value == 'dependency') {
                   11342:                 if (form.elements[item+1].type == 'select-one') {
                   11343:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11344:                         if (form.elements[item+1].options[i].value == picked) {
                   11345:                             form.elements[item+1].selectedIndex = i;
                   11346:                             break;
                   11347:                         }
                   11348:                     }
                   11349:                 }
                   11350:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11351:                     if (parents[count].length > 0) {
                   11352:                         for (var j=0; j<parents[count].length; j++) {
                   11353:                             containerSelect(form,parents[count][j],offset,picked);
                   11354:                         }
                   11355:                     }
                   11356:                 }
                   11357:             }
                   11358:         }
                   11359:     }
                   11360: }
                   11361: 
1.1059    raeburn  11362: function titleCheck(form,count,offset) {
                   11363:     if (count > 0) {
                   11364:         var chosen = (offset+$startcount)+7*(count-1);
                   11365:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11366:         var currtype = form.elements[depitem].type;
                   11367:         if (form.elements[chosen].value == 'display') {
                   11368:             document.getElementById('arc_title_'+count).style.display='block';
                   11369:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11370:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11371:             }
                   11372:         } else {
                   11373:             document.getElementById('arc_title_'+count).style.display='none';
                   11374:             if (currtype == 'text') { 
                   11375:                 document.getElementById('archive_title_'+count).value='';
                   11376:             }
                   11377:         }
                   11378:     }
                   11379:     return;
                   11380: }
                   11381: 
1.1055    raeburn  11382: // ]]>
                   11383: </script>
                   11384: END
                   11385:     return $scripttag;
                   11386: }
                   11387: 
                   11388: sub process_extracted_files {
1.1067    raeburn  11389:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11390:     my $numitems = $env{'form.archive_count'};
                   11391:     return unless ($numitems);
                   11392:     my @ids=&Apache::lonnet::current_machine_ids();
                   11393:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11394:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11395:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11396:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11397:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11398:         $pathtocheck = "$dir_root/$destination";
                   11399:         $dir = $dir_root;
                   11400:         $ishome = 1;
                   11401:     } else {
                   11402:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11403:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11404:         $dir = "$dir_root/$docudom/$docuname";    
                   11405:     }
                   11406:     my $currdir = "$dir_root/$destination";
                   11407:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11408:     if ($env{'form.folderpath'}) {
                   11409:         my @items = split('&',$env{'form.folderpath'});
                   11410:         $folders{'0'} = $items[-2];
1.1099    raeburn  11411:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11412:             $containers{'0'}='page';
                   11413:         } else {  
                   11414:             $containers{'0'}='sequence';
                   11415:         }
1.1055    raeburn  11416:     }
                   11417:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11418:     if ($numitems) {
                   11419:         for (my $i=1; $i<=$numitems; $i++) {
                   11420:             my $path = $env{'form.archive_content_'.$i};
                   11421:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11422:                 my $item = $1;
                   11423:                 $toplevelitems{$item} = $i;
                   11424:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11425:                     $is_dir{$item} = 1;
                   11426:                 }
                   11427:             }
                   11428:         }
                   11429:     }
1.1067    raeburn  11430:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11431:     if (keys(%toplevelitems) > 0) {
                   11432:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11433:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11434:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11435:     }
1.1066    raeburn  11436:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11437:     if ($numitems) {
                   11438:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  11439:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11440:             my $path = $env{'form.archive_content_'.$i};
                   11441:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11442:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11443:                     if ($prefix ne '' && $path ne '') {
                   11444:                         if (-e $prefix.$path) {
1.1066    raeburn  11445:                             if ((@archdirs > 0) && 
                   11446:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11447:                                 $todeletedir{$prefix.$path} = 1;
                   11448:                             } else {
                   11449:                                 $todelete{$prefix.$path} = 1;
                   11450:                             }
1.1055    raeburn  11451:                         }
                   11452:                     }
                   11453:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11454:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11455:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11456:                     $docstitle = $env{'form.archive_title_'.$i};
                   11457:                     if ($docstitle eq '') {
                   11458:                         $docstitle = $title;
                   11459:                     }
1.1055    raeburn  11460:                     $outer = 0;
1.1056    raeburn  11461:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11462:                         if (@{$dirorder{$i}} > 0) {
                   11463:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11464:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11465:                                     $outer = $item;
                   11466:                                     last;
                   11467:                                 }
                   11468:                             }
                   11469:                         }
                   11470:                     }
                   11471:                     my ($errtext,$fatal) = 
                   11472:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11473:                                                '/'.$folders{$outer}.'.'.
                   11474:                                                $containers{$outer});
                   11475:                     next if ($fatal);
                   11476:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11477:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11478:                             $mapinner{$i} = time;
1.1055    raeburn  11479:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11480:                             $containers{$i} = 'sequence';
                   11481:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11482:                                       $folders{$i}.'.'.$containers{$i};
                   11483:                             my $newidx = &LONCAPA::map::getresidx();
                   11484:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11485:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11486:                             push(@LONCAPA::map::order,$newidx);
                   11487:                             my ($outtext,$errtext) =
                   11488:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11489:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11490:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11491:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11492:                             unless ($errtext) {
                   11493:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11494:                             }
1.1055    raeburn  11495:                         }
                   11496:                     } else {
                   11497:                         if ($context eq 'coursedocs') {
                   11498:                             my $newidx=&LONCAPA::map::getresidx();
                   11499:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11500:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11501:                                       $title;
                   11502:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11503:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11504:                             }
                   11505:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11506:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11507:                             }
                   11508:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11509:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11510:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11511:                                 unless ($ishome) {
                   11512:                                     my $fetch = "$newdest{$i}/$title";
                   11513:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11514:                                     $prompttofetch{$fetch} = 1;
                   11515:                                 }
1.1055    raeburn  11516:                             }
                   11517:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11518:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11519:                             push(@LONCAPA::map::order, $newidx);
                   11520:                             my ($outtext,$errtext)=
                   11521:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11522:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11523:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11524:                             unless ($errtext) {
                   11525:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11526:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11527:                                 }
                   11528:                             }
1.1055    raeburn  11529:                         }
                   11530:                     }
1.1086    raeburn  11531:                 }
                   11532:             } else {
                   11533:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11534:             }
                   11535:         }
                   11536:         for (my $i=1; $i<=$numitems; $i++) {
                   11537:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11538:             my $path = $env{'form.archive_content_'.$i};
                   11539:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11540:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11541:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11542:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11543:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11544:                         my ($itemidx,$fullpath,$relpath);
                   11545:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11546:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11547:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  11548:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11549:                                     $itemidx = $j;
1.1056    raeburn  11550:                                 }
                   11551:                             }
1.1086    raeburn  11552:                         }
                   11553:                         if ($itemidx eq '') {
                   11554:                             $itemidx =  0;
                   11555:                         } 
                   11556:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11557:                             if ($mapinner{$referrer{$i}}) {
                   11558:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11559:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11560:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11561:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11562:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11563:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11564:                                             if (!-e $fullpath) {
                   11565:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11566:                                             }
                   11567:                                         }
1.1086    raeburn  11568:                                     } else {
                   11569:                                         last;
1.1056    raeburn  11570:                                     }
1.1086    raeburn  11571:                                 }
                   11572:                             }
                   11573:                         } elsif ($newdest{$referrer{$i}}) {
                   11574:                             $fullpath = $newdest{$referrer{$i}};
                   11575:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11576:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11577:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11578:                                     last;
                   11579:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11580:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11581:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11582:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11583:                                         if (!-e $fullpath) {
                   11584:                                             mkdir($fullpath,0755);
1.1056    raeburn  11585:                                         }
                   11586:                                     }
1.1086    raeburn  11587:                                 } else {
                   11588:                                     last;
1.1056    raeburn  11589:                                 }
1.1055    raeburn  11590:                             }
                   11591:                         }
1.1086    raeburn  11592:                         if ($fullpath ne '') {
                   11593:                             if (-e "$prefix$path") {
                   11594:                                 system("mv $prefix$path $fullpath/$title");
                   11595:                             }
                   11596:                             if (-e "$fullpath/$title") {
                   11597:                                 my $showpath;
                   11598:                                 if ($relpath ne '') {
                   11599:                                     $showpath = "$relpath/$title";
                   11600:                                 } else {
                   11601:                                     $showpath = "/$title";
                   11602:                                 } 
                   11603:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   11604:                             } 
                   11605:                             unless ($ishome) {
                   11606:                                 my $fetch = "$fullpath/$title";
                   11607:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   11608:                                 $prompttofetch{$fetch} = 1;
                   11609:                             }
                   11610:                         }
1.1055    raeburn  11611:                     }
1.1086    raeburn  11612:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   11613:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   11614:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  11615:                 }
                   11616:             } else {
                   11617:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11618:             }
                   11619:         }
                   11620:         if (keys(%todelete)) {
                   11621:             foreach my $key (keys(%todelete)) {
                   11622:                 unlink($key);
1.1066    raeburn  11623:             }
                   11624:         }
                   11625:         if (keys(%todeletedir)) {
                   11626:             foreach my $key (keys(%todeletedir)) {
                   11627:                 rmdir($key);
                   11628:             }
                   11629:         }
                   11630:         foreach my $dir (sort(keys(%is_dir))) {
                   11631:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   11632:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  11633:             }
                   11634:         }
1.1067    raeburn  11635:         if ($result ne '') {
                   11636:             $output .= '<ul>'."\n".
                   11637:                        $result."\n".
                   11638:                        '</ul>';
                   11639:         }
                   11640:         unless ($ishome) {
                   11641:             my $replicationfail;
                   11642:             foreach my $item (keys(%prompttofetch)) {
                   11643:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   11644:                 unless ($fetchresult eq 'ok') {
                   11645:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   11646:                 }
                   11647:             }
                   11648:             if ($replicationfail) {
                   11649:                 $output .= '<p class="LC_error">'.
                   11650:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   11651:                            $replicationfail.
                   11652:                            '</ul></p>';
                   11653:             }
                   11654:         }
1.1055    raeburn  11655:     } else {
                   11656:         $warning = &mt('No items found in archive.');
                   11657:     }
                   11658:     if ($error) {
                   11659:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11660:                    $error.'</p>'."\n";
                   11661:     }
                   11662:     if ($warning) {
                   11663:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11664:     }
                   11665:     return $output;
                   11666: }
                   11667: 
1.1066    raeburn  11668: sub cleanup_empty_dirs {
                   11669:     my ($path) = @_;
                   11670:     if (($path ne '') && (-d $path)) {
                   11671:         if (opendir(my $dirh,$path)) {
                   11672:             my @dircontents = grep(!/^\./,readdir($dirh));
                   11673:             my $numitems = 0;
                   11674:             foreach my $item (@dircontents) {
                   11675:                 if (-d "$path/$item") {
1.1111    raeburn  11676:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  11677:                     if (-e "$path/$item") {
                   11678:                         $numitems ++;
                   11679:                     }
                   11680:                 } else {
                   11681:                     $numitems ++;
                   11682:                 }
                   11683:             }
                   11684:             if ($numitems == 0) {
                   11685:                 rmdir($path);
                   11686:             }
                   11687:             closedir($dirh);
                   11688:         }
                   11689:     }
                   11690:     return;
                   11691: }
                   11692: 
1.41      ng       11693: =pod
1.45      matthew  11694: 
1.1068    raeburn  11695: =item &get_folder_hierarchy()
                   11696: 
                   11697: Provides hierarchy of names of folders/sub-folders containing the current
                   11698: item,
                   11699: 
                   11700: Inputs: 3
                   11701:      - $navmap - navmaps object
                   11702: 
                   11703:      - $map - url for map (either the trigger itself, or map containing
                   11704:                            the resource, which is the trigger).
                   11705: 
                   11706:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   11707: 
                   11708: Outputs: 1 @pathitems - array of folder/subfolder names.
                   11709: 
                   11710: =cut
                   11711: 
                   11712: sub get_folder_hierarchy {
                   11713:     my ($navmap,$map,$showitem) = @_;
                   11714:     my @pathitems;
                   11715:     if (ref($navmap)) {
                   11716:         my $mapres = $navmap->getResourceByUrl($map);
                   11717:         if (ref($mapres)) {
                   11718:             my $pcslist = $mapres->map_hierarchy();
                   11719:             if ($pcslist ne '') {
                   11720:                 my @pcs = split(/,/,$pcslist);
                   11721:                 foreach my $pc (@pcs) {
                   11722:                     if ($pc == 1) {
                   11723:                         push(@pathitems,&mt('Main Course Documents'));
                   11724:                     } else {
                   11725:                         my $res = $navmap->getByMapPc($pc);
                   11726:                         if (ref($res)) {
                   11727:                             my $title = $res->compTitle();
                   11728:                             $title =~ s/\W+/_/g;
                   11729:                             if ($title ne '') {
                   11730:                                 push(@pathitems,$title);
                   11731:                             }
                   11732:                         }
                   11733:                     }
                   11734:                 }
                   11735:             }
1.1071    raeburn  11736:             if ($showitem) {
                   11737:                 if ($mapres->{ID} eq '0.0') {
                   11738:                     push(@pathitems,&mt('Main Course Documents'));
                   11739:                 } else {
                   11740:                     my $maptitle = $mapres->compTitle();
                   11741:                     $maptitle =~ s/\W+/_/g;
                   11742:                     if ($maptitle ne '') {
                   11743:                         push(@pathitems,$maptitle);
                   11744:                     }
1.1068    raeburn  11745:                 }
                   11746:             }
                   11747:         }
                   11748:     }
                   11749:     return @pathitems;
                   11750: }
                   11751: 
                   11752: =pod
                   11753: 
1.1015    raeburn  11754: =item * &get_turnedin_filepath()
                   11755: 
                   11756: Determines path in a user's portfolio file for storage of files uploaded
                   11757: to a specific essayresponse or dropbox item.
                   11758: 
                   11759: Inputs: 3 required + 1 optional.
                   11760: $symb is symb for resource, $uname and $udom are for current user (required).
                   11761: $caller is optional (can be "submission", if routine is called when storing
                   11762: an upoaded file when "Submit Answer" button was pressed).
                   11763: 
                   11764: Returns array containing $path and $multiresp. 
                   11765: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   11766: than one file upload item.  Callers of routine should append partid as a 
                   11767: subdirectory to $path in cases where $multiresp is 1.
                   11768: 
                   11769: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   11770: 
                   11771: =cut
                   11772: 
                   11773: sub get_turnedin_filepath {
                   11774:     my ($symb,$uname,$udom,$caller) = @_;
                   11775:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   11776:     my $turnindir;
                   11777:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   11778:     $turnindir = $userhash{'turnindir'};
                   11779:     my ($path,$multiresp);
                   11780:     if ($turnindir eq '') {
                   11781:         if ($caller eq 'submission') {
                   11782:             $turnindir = &mt('turned in');
                   11783:             $turnindir =~ s/\W+/_/g;
                   11784:             my %newhash = (
                   11785:                             'turnindir' => $turnindir,
                   11786:                           );
                   11787:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   11788:         }
                   11789:     }
                   11790:     if ($turnindir ne '') {
                   11791:         $path = '/'.$turnindir.'/';
                   11792:         my ($multipart,$turnin,@pathitems);
                   11793:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11794:         if (defined($navmap)) {
                   11795:             my $mapres = $navmap->getResourceByUrl($map);
                   11796:             if (ref($mapres)) {
                   11797:                 my $pcslist = $mapres->map_hierarchy();
                   11798:                 if ($pcslist ne '') {
                   11799:                     foreach my $pc (split(/,/,$pcslist)) {
                   11800:                         my $res = $navmap->getByMapPc($pc);
                   11801:                         if (ref($res)) {
                   11802:                             my $title = $res->compTitle();
                   11803:                             $title =~ s/\W+/_/g;
                   11804:                             if ($title ne '') {
                   11805:                                 push(@pathitems,$title);
                   11806:                             }
                   11807:                         }
                   11808:                     }
                   11809:                 }
                   11810:                 my $maptitle = $mapres->compTitle();
                   11811:                 $maptitle =~ s/\W+/_/g;
                   11812:                 if ($maptitle ne '') {
                   11813:                     push(@pathitems,$maptitle);
                   11814:                 }
                   11815:                 unless ($env{'request.state'} eq 'construct') {
                   11816:                     my $res = $navmap->getBySymb($symb);
                   11817:                     if (ref($res)) {
                   11818:                         my $partlist = $res->parts();
                   11819:                         my $totaluploads = 0;
                   11820:                         if (ref($partlist) eq 'ARRAY') {
                   11821:                             foreach my $part (@{$partlist}) {
                   11822:                                 my @types = $res->responseType($part);
                   11823:                                 my @ids = $res->responseIds($part);
                   11824:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   11825:                                     if ($types[$i] eq 'essay') {
                   11826:                                         my $partid = $part.'_'.$ids[$i];
                   11827:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   11828:                                             $totaluploads ++;
                   11829:                                         }
                   11830:                                     }
                   11831:                                 }
                   11832:                             }
                   11833:                             if ($totaluploads > 1) {
                   11834:                                 $multiresp = 1;
                   11835:                             }
                   11836:                         }
                   11837:                     }
                   11838:                 }
                   11839:             } else {
                   11840:                 return;
                   11841:             }
                   11842:         } else {
                   11843:             return;
                   11844:         }
                   11845:         my $restitle=&Apache::lonnet::gettitle($symb);
                   11846:         $restitle =~ s/\W+/_/g;
                   11847:         if ($restitle eq '') {
                   11848:             $restitle = ($resurl =~ m{/[^/]+$});
                   11849:             if ($restitle eq '') {
                   11850:                 $restitle = time;
                   11851:             }
                   11852:         }
                   11853:         push(@pathitems,$restitle);
                   11854:         $path .= join('/',@pathitems);
                   11855:     }
                   11856:     return ($path,$multiresp);
                   11857: }
                   11858: 
                   11859: =pod
                   11860: 
1.464     albertel 11861: =back
1.41      ng       11862: 
1.112     bowersj2 11863: =head1 CSV Upload/Handling functions
1.38      albertel 11864: 
1.41      ng       11865: =over 4
                   11866: 
1.648     raeburn  11867: =item * &upfile_store($r)
1.41      ng       11868: 
                   11869: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 11870: needs $env{'form.upfile'}
1.41      ng       11871: returns $datatoken to be put into hidden field
                   11872: 
                   11873: =cut
1.31      albertel 11874: 
                   11875: sub upfile_store {
                   11876:     my $r=shift;
1.258     albertel 11877:     $env{'form.upfile'}=~s/\r/\n/gs;
                   11878:     $env{'form.upfile'}=~s/\f/\n/gs;
                   11879:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   11880:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 11881: 
1.258     albertel 11882:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   11883: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 11884:     {
1.158     raeburn  11885:         my $datafile = $r->dir_config('lonDaemons').
                   11886:                            '/tmp/'.$datatoken.'.tmp';
                   11887:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 11888:             print $fh $env{'form.upfile'};
1.158     raeburn  11889:             close($fh);
                   11890:         }
1.31      albertel 11891:     }
                   11892:     return $datatoken;
                   11893: }
                   11894: 
1.56      matthew  11895: =pod
                   11896: 
1.648     raeburn  11897: =item * &load_tmp_file($r)
1.41      ng       11898: 
                   11899: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 11900: needs $env{'form.datatoken'},
                   11901: sets $env{'form.upfile'} to the contents of the file
1.41      ng       11902: 
                   11903: =cut
1.31      albertel 11904: 
                   11905: sub load_tmp_file {
                   11906:     my $r=shift;
                   11907:     my @studentdata=();
                   11908:     {
1.158     raeburn  11909:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 11910:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  11911:         if ( open(my $fh,"<$studentfile") ) {
                   11912:             @studentdata=<$fh>;
                   11913:             close($fh);
                   11914:         }
1.31      albertel 11915:     }
1.258     albertel 11916:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 11917: }
                   11918: 
1.56      matthew  11919: =pod
                   11920: 
1.648     raeburn  11921: =item * &upfile_record_sep()
1.41      ng       11922: 
                   11923: Separate uploaded file into records
                   11924: returns array of records,
1.258     albertel 11925: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       11926: 
                   11927: =cut
1.31      albertel 11928: 
                   11929: sub upfile_record_sep {
1.258     albertel 11930:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 11931:     } else {
1.248     albertel 11932: 	my @records;
1.258     albertel 11933: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 11934: 	    if ($line=~/^\s*$/) { next; }
                   11935: 	    push(@records,$line);
                   11936: 	}
                   11937: 	return @records;
1.31      albertel 11938:     }
                   11939: }
                   11940: 
1.56      matthew  11941: =pod
                   11942: 
1.648     raeburn  11943: =item * &record_sep($record)
1.41      ng       11944: 
1.258     albertel 11945: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       11946: 
                   11947: =cut
                   11948: 
1.263     www      11949: sub takeleft {
                   11950:     my $index=shift;
                   11951:     return substr('0000'.$index,-4,4);
                   11952: }
                   11953: 
1.31      albertel 11954: sub record_sep {
                   11955:     my $record=shift;
                   11956:     my %components=();
1.258     albertel 11957:     if ($env{'form.upfiletype'} eq 'xml') {
                   11958:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 11959:         my $i=0;
1.356     albertel 11960:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 11961:             $field=~s/^(\"|\')//;
                   11962:             $field=~s/(\"|\')$//;
1.263     www      11963:             $components{&takeleft($i)}=$field;
1.31      albertel 11964:             $i++;
                   11965:         }
1.258     albertel 11966:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 11967:         my $i=0;
1.356     albertel 11968:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 11969:             $field=~s/^(\"|\')//;
                   11970:             $field=~s/(\"|\')$//;
1.263     www      11971:             $components{&takeleft($i)}=$field;
1.31      albertel 11972:             $i++;
                   11973:         }
                   11974:     } else {
1.561     www      11975:         my $separator=',';
1.480     banghart 11976:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      11977:             $separator=';';
1.480     banghart 11978:         }
1.31      albertel 11979:         my $i=0;
1.561     www      11980: # the character we are looking for to indicate the end of a quote or a record 
                   11981:         my $looking_for=$separator;
                   11982: # do not add the characters to the fields
                   11983:         my $ignore=0;
                   11984: # we just encountered a separator (or the beginning of the record)
                   11985:         my $just_found_separator=1;
                   11986: # store the field we are working on here
                   11987:         my $field='';
                   11988: # work our way through all characters in record
                   11989:         foreach my $character ($record=~/(.)/g) {
                   11990:             if ($character eq $looking_for) {
                   11991:                if ($character ne $separator) {
                   11992: # Found the end of a quote, again looking for separator
                   11993:                   $looking_for=$separator;
                   11994:                   $ignore=1;
                   11995:                } else {
                   11996: # Found a separator, store away what we got
                   11997:                   $components{&takeleft($i)}=$field;
                   11998: 	          $i++;
                   11999:                   $just_found_separator=1;
                   12000:                   $ignore=0;
                   12001:                   $field='';
                   12002:                }
                   12003:                next;
                   12004:             }
                   12005: # single or double quotation marks after a separator indicate beginning of a quote
                   12006: # we are now looking for the end of the quote and need to ignore separators
                   12007:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12008:                $looking_for=$character;
                   12009:                next;
                   12010:             }
                   12011: # ignore would be true after we reached the end of a quote
                   12012:             if ($ignore) { next; }
                   12013:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12014:             $field.=$character;
                   12015:             $just_found_separator=0; 
1.31      albertel 12016:         }
1.561     www      12017: # catch the very last entry, since we never encountered the separator
                   12018:         $components{&takeleft($i)}=$field;
1.31      albertel 12019:     }
                   12020:     return %components;
                   12021: }
                   12022: 
1.144     matthew  12023: ######################################################
                   12024: ######################################################
                   12025: 
1.56      matthew  12026: =pod
                   12027: 
1.648     raeburn  12028: =item * &upfile_select_html()
1.41      ng       12029: 
1.144     matthew  12030: Return HTML code to select a file from the users machine and specify 
                   12031: the file type.
1.41      ng       12032: 
                   12033: =cut
                   12034: 
1.144     matthew  12035: ######################################################
                   12036: ######################################################
1.31      albertel 12037: sub upfile_select_html {
1.144     matthew  12038:     my %Types = (
                   12039:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12040:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12041:                  space => &mt('Space separated'),
                   12042:                  tab   => &mt('Tabulator separated'),
                   12043: #                 xml   => &mt('HTML/XML'),
                   12044:                  );
                   12045:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12046:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12047:     foreach my $type (sort(keys(%Types))) {
                   12048:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12049:     }
                   12050:     $Str .= "</select>\n";
                   12051:     return $Str;
1.31      albertel 12052: }
                   12053: 
1.301     albertel 12054: sub get_samples {
                   12055:     my ($records,$toget) = @_;
                   12056:     my @samples=({});
                   12057:     my $got=0;
                   12058:     foreach my $rec (@$records) {
                   12059: 	my %temp = &record_sep($rec);
                   12060: 	if (! grep(/\S/, values(%temp))) { next; }
                   12061: 	if (%temp) {
                   12062: 	    $samples[$got]=\%temp;
                   12063: 	    $got++;
                   12064: 	    if ($got == $toget) { last; }
                   12065: 	}
                   12066:     }
                   12067:     return \@samples;
                   12068: }
                   12069: 
1.144     matthew  12070: ######################################################
                   12071: ######################################################
                   12072: 
1.56      matthew  12073: =pod
                   12074: 
1.648     raeburn  12075: =item * &csv_print_samples($r,$records)
1.41      ng       12076: 
                   12077: Prints a table of sample values from each column uploaded $r is an
                   12078: Apache Request ref, $records is an arrayref from
                   12079: &Apache::loncommon::upfile_record_sep
                   12080: 
                   12081: =cut
                   12082: 
1.144     matthew  12083: ######################################################
                   12084: ######################################################
1.31      albertel 12085: sub csv_print_samples {
                   12086:     my ($r,$records) = @_;
1.662     bisitz   12087:     my $samples = &get_samples($records,5);
1.301     albertel 12088: 
1.594     raeburn  12089:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12090:               &start_data_table_header_row());
1.356     albertel 12091:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12092:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12093:     $r->print(&end_data_table_header_row());
1.301     albertel 12094:     foreach my $hash (@$samples) {
1.594     raeburn  12095: 	$r->print(&start_data_table_row());
1.356     albertel 12096: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12097: 	    $r->print('<td>');
1.356     albertel 12098: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12099: 	    $r->print('</td>');
                   12100: 	}
1.594     raeburn  12101: 	$r->print(&end_data_table_row());
1.31      albertel 12102:     }
1.594     raeburn  12103:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12104: }
                   12105: 
1.144     matthew  12106: ######################################################
                   12107: ######################################################
                   12108: 
1.56      matthew  12109: =pod
                   12110: 
1.648     raeburn  12111: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12112: 
                   12113: Prints a table to create associations between values and table columns.
1.144     matthew  12114: 
1.41      ng       12115: $r is an Apache Request ref,
                   12116: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12117: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12118: 
                   12119: =cut
                   12120: 
1.144     matthew  12121: ######################################################
                   12122: ######################################################
1.31      albertel 12123: sub csv_print_select_table {
                   12124:     my ($r,$records,$d) = @_;
1.301     albertel 12125:     my $i=0;
                   12126:     my $samples = &get_samples($records,1);
1.144     matthew  12127:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12128: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12129:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12130:               '<th>'.&mt('Column').'</th>'.
                   12131:               &end_data_table_header_row()."\n");
1.356     albertel 12132:     foreach my $array_ref (@$d) {
                   12133: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12134: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12135: 
1.875     bisitz   12136: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12137: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12138: 	$r->print('<option value="none"></option>');
1.356     albertel 12139: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12140: 	    $r->print('<option value="'.$sample.'"'.
                   12141:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12142:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12143: 	}
1.594     raeburn  12144: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12145: 	$i++;
                   12146:     }
1.594     raeburn  12147:     $r->print(&end_data_table());
1.31      albertel 12148:     $i--;
                   12149:     return $i;
                   12150: }
1.56      matthew  12151: 
1.144     matthew  12152: ######################################################
                   12153: ######################################################
                   12154: 
1.56      matthew  12155: =pod
1.31      albertel 12156: 
1.648     raeburn  12157: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12158: 
                   12159: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12160: 
                   12161: $r is an Apache Request ref,
                   12162: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12163: $d is an array of 2 element arrays (internal name, displayed name)
                   12164: 
                   12165: =cut
                   12166: 
1.144     matthew  12167: ######################################################
                   12168: ######################################################
1.31      albertel 12169: sub csv_samples_select_table {
                   12170:     my ($r,$records,$d) = @_;
                   12171:     my $i=0;
1.144     matthew  12172:     #
1.662     bisitz   12173:     my $max_samples = 5;
                   12174:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12175:     $r->print(&start_data_table().
                   12176:               &start_data_table_header_row().'<th>'.
                   12177:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12178:               &end_data_table_header_row());
1.301     albertel 12179: 
                   12180:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12181: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12182: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12183: 	foreach my $option (@$d) {
                   12184: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12185: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12186:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12187:                       $display.'</option>');
1.31      albertel 12188: 	}
                   12189: 	$r->print('</select></td><td>');
1.662     bisitz   12190: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12191: 	    if (defined($samples->[$line]{$key})) { 
                   12192: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12193: 	    }
                   12194: 	}
1.594     raeburn  12195: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12196: 	$i++;
                   12197:     }
1.594     raeburn  12198:     $r->print(&end_data_table());
1.31      albertel 12199:     $i--;
                   12200:     return($i);
1.115     matthew  12201: }
                   12202: 
1.144     matthew  12203: ######################################################
                   12204: ######################################################
                   12205: 
1.115     matthew  12206: =pod
                   12207: 
1.648     raeburn  12208: =item * &clean_excel_name($name)
1.115     matthew  12209: 
                   12210: Returns a replacement for $name which does not contain any illegal characters.
                   12211: 
                   12212: =cut
                   12213: 
1.144     matthew  12214: ######################################################
                   12215: ######################################################
1.115     matthew  12216: sub clean_excel_name {
                   12217:     my ($name) = @_;
                   12218:     $name =~ s/[:\*\?\/\\]//g;
                   12219:     if (length($name) > 31) {
                   12220:         $name = substr($name,0,31);
                   12221:     }
                   12222:     return $name;
1.25      albertel 12223: }
1.84      albertel 12224: 
1.85      albertel 12225: =pod
                   12226: 
1.648     raeburn  12227: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12228: 
                   12229: Returns either 1 or undef
                   12230: 
                   12231: 1 if the part is to be hidden, undef if it is to be shown
                   12232: 
                   12233: Arguments are:
                   12234: 
                   12235: $id the id of the part to be checked
                   12236: $symb, optional the symb of the resource to check
                   12237: $udom, optional the domain of the user to check for
                   12238: $uname, optional the username of the user to check for
                   12239: 
                   12240: =cut
1.84      albertel 12241: 
                   12242: sub check_if_partid_hidden {
                   12243:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12244:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12245: 					 $symb,$udom,$uname);
1.141     albertel 12246:     my $truth=1;
                   12247:     #if the string starts with !, then the list is the list to show not hide
                   12248:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12249:     my @hiddenlist=split(/,/,$hiddenparts);
                   12250:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12251: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12252:     }
1.141     albertel 12253:     return !$truth;
1.84      albertel 12254: }
1.127     matthew  12255: 
1.138     matthew  12256: 
                   12257: ############################################################
                   12258: ############################################################
                   12259: 
                   12260: =pod
                   12261: 
1.157     matthew  12262: =back 
                   12263: 
1.138     matthew  12264: =head1 cgi-bin script and graphing routines
                   12265: 
1.157     matthew  12266: =over 4
                   12267: 
1.648     raeburn  12268: =item * &get_cgi_id()
1.138     matthew  12269: 
                   12270: Inputs: none
                   12271: 
                   12272: Returns an id which can be used to pass environment variables
                   12273: to various cgi-bin scripts.  These environment variables will
                   12274: be removed from the users environment after a given time by
                   12275: the routine &Apache::lonnet::transfer_profile_to_env.
                   12276: 
                   12277: =cut
                   12278: 
                   12279: ############################################################
                   12280: ############################################################
1.152     albertel 12281: my $uniq=0;
1.136     matthew  12282: sub get_cgi_id {
1.154     albertel 12283:     $uniq=($uniq+1)%100000;
1.280     albertel 12284:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12285: }
                   12286: 
1.127     matthew  12287: ############################################################
                   12288: ############################################################
                   12289: 
                   12290: =pod
                   12291: 
1.648     raeburn  12292: =item * &DrawBarGraph()
1.127     matthew  12293: 
1.138     matthew  12294: Facilitates the plotting of data in a (stacked) bar graph.
                   12295: Puts plot definition data into the users environment in order for 
                   12296: graph.png to plot it.  Returns an <img> tag for the plot.
                   12297: The bars on the plot are labeled '1','2',...,'n'.
                   12298: 
                   12299: Inputs:
                   12300: 
                   12301: =over 4
                   12302: 
                   12303: =item $Title: string, the title of the plot
                   12304: 
                   12305: =item $xlabel: string, text describing the X-axis of the plot
                   12306: 
                   12307: =item $ylabel: string, text describing the Y-axis of the plot
                   12308: 
                   12309: =item $Max: scalar, the maximum Y value to use in the plot
                   12310: If $Max is < any data point, the graph will not be rendered.
                   12311: 
1.140     matthew  12312: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12313: they are plotted.  If undefined, default values will be used.
                   12314: 
1.178     matthew  12315: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12316: 
1.138     matthew  12317: =item @Values: An array of array references.  Each array reference holds data
                   12318: to be plotted in a stacked bar chart.
                   12319: 
1.239     matthew  12320: =item If the final element of @Values is a hash reference the key/value
                   12321: pairs will be added to the graph definition.
                   12322: 
1.138     matthew  12323: =back
                   12324: 
                   12325: Returns:
                   12326: 
                   12327: An <img> tag which references graph.png and the appropriate identifying
                   12328: information for the plot.
                   12329: 
1.127     matthew  12330: =cut
                   12331: 
                   12332: ############################################################
                   12333: ############################################################
1.134     matthew  12334: sub DrawBarGraph {
1.178     matthew  12335:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12336:     #
                   12337:     if (! defined($colors)) {
                   12338:         $colors = ['#33ff00', 
                   12339:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12340:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12341:                   ]; 
                   12342:     }
1.228     matthew  12343:     my $extra_settings = {};
                   12344:     if (ref($Values[-1]) eq 'HASH') {
                   12345:         $extra_settings = pop(@Values);
                   12346:     }
1.127     matthew  12347:     #
1.136     matthew  12348:     my $identifier = &get_cgi_id();
                   12349:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12350:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12351:         return '';
                   12352:     }
1.225     matthew  12353:     #
                   12354:     my @Labels;
                   12355:     if (defined($labels)) {
                   12356:         @Labels = @$labels;
                   12357:     } else {
                   12358:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12359:             push (@Labels,$i+1);
                   12360:         }
                   12361:     }
                   12362:     #
1.129     matthew  12363:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12364:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12365:     my %ValuesHash;
                   12366:     my $NumSets=1;
                   12367:     foreach my $array (@Values) {
                   12368:         next if (! ref($array));
1.136     matthew  12369:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12370:             join(',',@$array);
1.129     matthew  12371:     }
1.127     matthew  12372:     #
1.136     matthew  12373:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12374:     if ($NumBars < 3) {
                   12375:         $width = 120+$NumBars*32;
1.220     matthew  12376:         $xskip = 1;
1.225     matthew  12377:         $bar_width = 30;
                   12378:     } elsif ($NumBars < 5) {
                   12379:         $width = 120+$NumBars*20;
                   12380:         $xskip = 1;
                   12381:         $bar_width = 20;
1.220     matthew  12382:     } elsif ($NumBars < 10) {
1.136     matthew  12383:         $width = 120+$NumBars*15;
                   12384:         $xskip = 1;
                   12385:         $bar_width = 15;
                   12386:     } elsif ($NumBars <= 25) {
                   12387:         $width = 120+$NumBars*11;
                   12388:         $xskip = 5;
                   12389:         $bar_width = 8;
                   12390:     } elsif ($NumBars <= 50) {
                   12391:         $width = 120+$NumBars*8;
                   12392:         $xskip = 5;
                   12393:         $bar_width = 4;
                   12394:     } else {
                   12395:         $width = 120+$NumBars*8;
                   12396:         $xskip = 5;
                   12397:         $bar_width = 4;
                   12398:     }
                   12399:     #
1.137     matthew  12400:     $Max = 1 if ($Max < 1);
                   12401:     if ( int($Max) < $Max ) {
                   12402:         $Max++;
                   12403:         $Max = int($Max);
                   12404:     }
1.127     matthew  12405:     $Title  = '' if (! defined($Title));
                   12406:     $xlabel = '' if (! defined($xlabel));
                   12407:     $ylabel = '' if (! defined($ylabel));
1.369     www      12408:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12409:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12410:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12411:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12412:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12413:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12414:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12415:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12416:     $ValuesHash{$id.'.height'}   = $height;
                   12417:     $ValuesHash{$id.'.width'}    = $width;
                   12418:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12419:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12420:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12421:     #
1.228     matthew  12422:     # Deal with other parameters
                   12423:     while (my ($key,$value) = each(%$extra_settings)) {
                   12424:         $ValuesHash{$id.'.'.$key} = $value;
                   12425:     }
                   12426:     #
1.646     raeburn  12427:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12428:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12429: }
                   12430: 
                   12431: ############################################################
                   12432: ############################################################
                   12433: 
                   12434: =pod
                   12435: 
1.648     raeburn  12436: =item * &DrawXYGraph()
1.137     matthew  12437: 
1.138     matthew  12438: Facilitates the plotting of data in an XY graph.
                   12439: Puts plot definition data into the users environment in order for 
                   12440: graph.png to plot it.  Returns an <img> tag for the plot.
                   12441: 
                   12442: Inputs:
                   12443: 
                   12444: =over 4
                   12445: 
                   12446: =item $Title: string, the title of the plot
                   12447: 
                   12448: =item $xlabel: string, text describing the X-axis of the plot
                   12449: 
                   12450: =item $ylabel: string, text describing the Y-axis of the plot
                   12451: 
                   12452: =item $Max: scalar, the maximum Y value to use in the plot
                   12453: If $Max is < any data point, the graph will not be rendered.
                   12454: 
                   12455: =item $colors: Array ref containing the hex color codes for the data to be 
                   12456: plotted in.  If undefined, default values will be used.
                   12457: 
                   12458: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12459: 
                   12460: =item $Ydata: Array ref containing Array refs.  
1.185     www      12461: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12462: 
                   12463: =item %Values: hash indicating or overriding any default values which are 
                   12464: passed to graph.png.  
                   12465: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12466: 
                   12467: =back
                   12468: 
                   12469: Returns:
                   12470: 
                   12471: An <img> tag which references graph.png and the appropriate identifying
                   12472: information for the plot.
                   12473: 
1.137     matthew  12474: =cut
                   12475: 
                   12476: ############################################################
                   12477: ############################################################
                   12478: sub DrawXYGraph {
                   12479:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12480:     #
                   12481:     # Create the identifier for the graph
                   12482:     my $identifier = &get_cgi_id();
                   12483:     my $id = 'cgi.'.$identifier;
                   12484:     #
                   12485:     $Title  = '' if (! defined($Title));
                   12486:     $xlabel = '' if (! defined($xlabel));
                   12487:     $ylabel = '' if (! defined($ylabel));
                   12488:     my %ValuesHash = 
                   12489:         (
1.369     www      12490:          $id.'.title'  => &escape($Title),
                   12491:          $id.'.xlabel' => &escape($xlabel),
                   12492:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12493:          $id.'.y_max_value'=> $Max,
                   12494:          $id.'.labels'     => join(',',@$Xlabels),
                   12495:          $id.'.PlotType'   => 'XY',
                   12496:          );
                   12497:     #
                   12498:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12499:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12500:     }
                   12501:     #
                   12502:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12503:         return '';
                   12504:     }
                   12505:     my $NumSets=1;
1.138     matthew  12506:     foreach my $array (@{$Ydata}){
1.137     matthew  12507:         next if (! ref($array));
                   12508:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12509:     }
1.138     matthew  12510:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12511:     #
                   12512:     # Deal with other parameters
                   12513:     while (my ($key,$value) = each(%Values)) {
                   12514:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12515:     }
                   12516:     #
1.646     raeburn  12517:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12518:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12519: }
                   12520: 
                   12521: ############################################################
                   12522: ############################################################
                   12523: 
                   12524: =pod
                   12525: 
1.648     raeburn  12526: =item * &DrawXYYGraph()
1.138     matthew  12527: 
                   12528: Facilitates the plotting of data in an XY graph with two Y axes.
                   12529: Puts plot definition data into the users environment in order for 
                   12530: graph.png to plot it.  Returns an <img> tag for the plot.
                   12531: 
                   12532: Inputs:
                   12533: 
                   12534: =over 4
                   12535: 
                   12536: =item $Title: string, the title of the plot
                   12537: 
                   12538: =item $xlabel: string, text describing the X-axis of the plot
                   12539: 
                   12540: =item $ylabel: string, text describing the Y-axis of the plot
                   12541: 
                   12542: =item $colors: Array ref containing the hex color codes for the data to be 
                   12543: plotted in.  If undefined, default values will be used.
                   12544: 
                   12545: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12546: 
                   12547: =item $Ydata1: The first data set
                   12548: 
                   12549: =item $Min1: The minimum value of the left Y-axis
                   12550: 
                   12551: =item $Max1: The maximum value of the left Y-axis
                   12552: 
                   12553: =item $Ydata2: The second data set
                   12554: 
                   12555: =item $Min2: The minimum value of the right Y-axis
                   12556: 
                   12557: =item $Max2: The maximum value of the left Y-axis
                   12558: 
                   12559: =item %Values: hash indicating or overriding any default values which are 
                   12560: passed to graph.png.  
                   12561: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12562: 
                   12563: =back
                   12564: 
                   12565: Returns:
                   12566: 
                   12567: An <img> tag which references graph.png and the appropriate identifying
                   12568: information for the plot.
1.136     matthew  12569: 
                   12570: =cut
                   12571: 
                   12572: ############################################################
                   12573: ############################################################
1.137     matthew  12574: sub DrawXYYGraph {
                   12575:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12576:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12577:     #
                   12578:     # Create the identifier for the graph
                   12579:     my $identifier = &get_cgi_id();
                   12580:     my $id = 'cgi.'.$identifier;
                   12581:     #
                   12582:     $Title  = '' if (! defined($Title));
                   12583:     $xlabel = '' if (! defined($xlabel));
                   12584:     $ylabel = '' if (! defined($ylabel));
                   12585:     my %ValuesHash = 
                   12586:         (
1.369     www      12587:          $id.'.title'  => &escape($Title),
                   12588:          $id.'.xlabel' => &escape($xlabel),
                   12589:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  12590:          $id.'.labels' => join(',',@$Xlabels),
                   12591:          $id.'.PlotType' => 'XY',
                   12592:          $id.'.NumSets' => 2,
1.137     matthew  12593:          $id.'.two_axes' => 1,
                   12594:          $id.'.y1_max_value' => $Max1,
                   12595:          $id.'.y1_min_value' => $Min1,
                   12596:          $id.'.y2_max_value' => $Max2,
                   12597:          $id.'.y2_min_value' => $Min2,
1.136     matthew  12598:          );
                   12599:     #
1.137     matthew  12600:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12601:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12602:     }
                   12603:     #
                   12604:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   12605:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  12606:         return '';
                   12607:     }
                   12608:     my $NumSets=1;
1.137     matthew  12609:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  12610:         next if (! ref($array));
                   12611:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  12612:     }
                   12613:     #
                   12614:     # Deal with other parameters
                   12615:     while (my ($key,$value) = each(%Values)) {
                   12616:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  12617:     }
                   12618:     #
1.646     raeburn  12619:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 12620:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  12621: }
                   12622: 
                   12623: ############################################################
                   12624: ############################################################
                   12625: 
                   12626: =pod
                   12627: 
1.157     matthew  12628: =back 
                   12629: 
1.139     matthew  12630: =head1 Statistics helper routines?  
                   12631: 
                   12632: Bad place for them but what the hell.
                   12633: 
1.157     matthew  12634: =over 4
                   12635: 
1.648     raeburn  12636: =item * &chartlink()
1.139     matthew  12637: 
                   12638: Returns a link to the chart for a specific student.  
                   12639: 
                   12640: Inputs:
                   12641: 
                   12642: =over 4
                   12643: 
                   12644: =item $linktext: The text of the link
                   12645: 
                   12646: =item $sname: The students username
                   12647: 
                   12648: =item $sdomain: The students domain
                   12649: 
                   12650: =back
                   12651: 
1.157     matthew  12652: =back
                   12653: 
1.139     matthew  12654: =cut
                   12655: 
                   12656: ############################################################
                   12657: ############################################################
                   12658: sub chartlink {
                   12659:     my ($linktext, $sname, $sdomain) = @_;
                   12660:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      12661:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 12662:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  12663:        '">'.$linktext.'</a>';
1.153     matthew  12664: }
                   12665: 
                   12666: #######################################################
                   12667: #######################################################
                   12668: 
                   12669: =pod
                   12670: 
                   12671: =head1 Course Environment Routines
1.157     matthew  12672: 
                   12673: =over 4
1.153     matthew  12674: 
1.648     raeburn  12675: =item * &restore_course_settings()
1.153     matthew  12676: 
1.648     raeburn  12677: =item * &store_course_settings()
1.153     matthew  12678: 
                   12679: Restores/Store indicated form parameters from the course environment.
                   12680: Will not overwrite existing values of the form parameters.
                   12681: 
                   12682: Inputs: 
                   12683: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   12684: 
                   12685: a hash ref describing the data to be stored.  For example:
                   12686:    
                   12687: %Save_Parameters = ('Status' => 'scalar',
                   12688:     'chartoutputmode' => 'scalar',
                   12689:     'chartoutputdata' => 'scalar',
                   12690:     'Section' => 'array',
1.373     raeburn  12691:     'Group' => 'array',
1.153     matthew  12692:     'StudentData' => 'array',
                   12693:     'Maps' => 'array');
                   12694: 
                   12695: Returns: both routines return nothing
                   12696: 
1.631     raeburn  12697: =back
                   12698: 
1.153     matthew  12699: =cut
                   12700: 
                   12701: #######################################################
                   12702: #######################################################
                   12703: sub store_course_settings {
1.496     albertel 12704:     return &store_settings($env{'request.course.id'},@_);
                   12705: }
                   12706: 
                   12707: sub store_settings {
1.153     matthew  12708:     # save to the environment
                   12709:     # appenv the same items, just to be safe
1.300     albertel 12710:     my $udom  = $env{'user.domain'};
                   12711:     my $uname = $env{'user.name'};
1.496     albertel 12712:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12713:     my %SaveHash;
                   12714:     my %AppHash;
                   12715:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 12716:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 12717:         my $envname = 'environment.'.$basename;
1.258     albertel 12718:         if (exists($env{'form.'.$setting})) {
1.153     matthew  12719:             # Save this value away
                   12720:             if ($type eq 'scalar' &&
1.258     albertel 12721:                 (! exists($env{$envname}) || 
                   12722:                  $env{$envname} ne $env{'form.'.$setting})) {
                   12723:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   12724:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  12725:             } elsif ($type eq 'array') {
                   12726:                 my $stored_form;
1.258     albertel 12727:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  12728:                     $stored_form = join(',',
                   12729:                                         map {
1.369     www      12730:                                             &escape($_);
1.258     albertel 12731:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  12732:                 } else {
                   12733:                     $stored_form = 
1.369     www      12734:                         &escape($env{'form.'.$setting});
1.153     matthew  12735:                 }
                   12736:                 # Determine if the array contents are the same.
1.258     albertel 12737:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  12738:                     $SaveHash{$basename} = $stored_form;
                   12739:                     $AppHash{$envname}   = $stored_form;
                   12740:                 }
                   12741:             }
                   12742:         }
                   12743:     }
                   12744:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 12745:                                           $udom,$uname);
1.153     matthew  12746:     if ($put_result !~ /^(ok|delayed)/) {
                   12747:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   12748:                                  'got error:'.$put_result);
                   12749:     }
                   12750:     # Make sure these settings stick around in this session, too
1.646     raeburn  12751:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  12752:     return;
                   12753: }
                   12754: 
                   12755: sub restore_course_settings {
1.499     albertel 12756:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 12757: }
                   12758: 
                   12759: sub restore_settings {
                   12760:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12761:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 12762:         next if (exists($env{'form.'.$setting}));
1.496     albertel 12763:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  12764:             '.'.$setting;
1.258     albertel 12765:         if (exists($env{$envname})) {
1.153     matthew  12766:             if ($type eq 'scalar') {
1.258     albertel 12767:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  12768:             } elsif ($type eq 'array') {
1.258     albertel 12769:                 $env{'form.'.$setting} = [ 
1.153     matthew  12770:                                            map { 
1.369     www      12771:                                                &unescape($_); 
1.258     albertel 12772:                                            } split(',',$env{$envname})
1.153     matthew  12773:                                            ];
                   12774:             }
                   12775:         }
                   12776:     }
1.127     matthew  12777: }
                   12778: 
1.618     raeburn  12779: #######################################################
                   12780: #######################################################
                   12781: 
                   12782: =pod
                   12783: 
                   12784: =head1 Domain E-mail Routines  
                   12785: 
                   12786: =over 4
                   12787: 
1.648     raeburn  12788: =item * &build_recipient_list()
1.618     raeburn  12789: 
1.884     raeburn  12790: Build recipient lists for five types of e-mail:
1.766     raeburn  12791: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.884     raeburn  12792: (d) Help requests, (e) Course requests needing approval,  generated by
                   12793: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
                   12794: loncoursequeueadmin.pm respectively.
1.618     raeburn  12795: 
                   12796: Inputs:
1.619     raeburn  12797: defmail (scalar - email address of default recipient), 
1.618     raeburn  12798: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  12799: defdom (domain for which to retrieve configuration settings),
                   12800: origmail (scalar - email address of recipient from loncapa.conf, 
                   12801: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  12802: 
1.655     raeburn  12803: Returns: comma separated list of addresses to which to send e-mail.
                   12804: 
                   12805: =back
1.618     raeburn  12806: 
                   12807: =cut
                   12808: 
                   12809: ############################################################
                   12810: ############################################################
                   12811: sub build_recipient_list {
1.619     raeburn  12812:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  12813:     my @recipients;
                   12814:     my $otheremails;
                   12815:     my %domconfig =
                   12816:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   12817:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  12818:         if (exists($domconfig{'contacts'}{$mailing})) {
                   12819:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   12820:                 my @contacts = ('adminemail','supportemail');
                   12821:                 foreach my $item (@contacts) {
                   12822:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   12823:                         my $addr = $domconfig{'contacts'}{$item}; 
                   12824:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12825:                             push(@recipients,$addr);
                   12826:                         }
1.619     raeburn  12827:                     }
1.766     raeburn  12828:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  12829:                 }
                   12830:             }
1.766     raeburn  12831:         } elsif ($origmail ne '') {
                   12832:             push(@recipients,$origmail);
1.618     raeburn  12833:         }
1.619     raeburn  12834:     } elsif ($origmail ne '') {
                   12835:         push(@recipients,$origmail);
1.618     raeburn  12836:     }
1.688     raeburn  12837:     if (defined($defmail)) {
                   12838:         if ($defmail ne '') {
                   12839:             push(@recipients,$defmail);
                   12840:         }
1.618     raeburn  12841:     }
                   12842:     if ($otheremails) {
1.619     raeburn  12843:         my @others;
                   12844:         if ($otheremails =~ /,/) {
                   12845:             @others = split(/,/,$otheremails);
1.618     raeburn  12846:         } else {
1.619     raeburn  12847:             push(@others,$otheremails);
                   12848:         }
                   12849:         foreach my $addr (@others) {
                   12850:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12851:                 push(@recipients,$addr);
                   12852:             }
1.618     raeburn  12853:         }
                   12854:     }
1.619     raeburn  12855:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  12856:     return $recipientlist;
                   12857: }
                   12858: 
1.127     matthew  12859: ############################################################
                   12860: ############################################################
1.154     albertel 12861: 
1.655     raeburn  12862: =pod
                   12863: 
                   12864: =head1 Course Catalog Routines
                   12865: 
                   12866: =over 4
                   12867: 
                   12868: =item * &gather_categories()
                   12869: 
                   12870: Converts category definitions - keys of categories hash stored in  
                   12871: coursecategories in configuration.db on the primary library server in a 
                   12872: domain - to an array.  Also generates javascript and idx hash used to 
                   12873: generate Domain Coordinator interface for editing Course Categories.
                   12874: 
                   12875: Inputs:
1.663     raeburn  12876: 
1.655     raeburn  12877: categories (reference to hash of category definitions).
1.663     raeburn  12878: 
1.655     raeburn  12879: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12880:       categories and subcategories).
1.663     raeburn  12881: 
1.655     raeburn  12882: idx (reference to hash of counters used in Domain Coordinator interface for 
                   12883:       editing Course Categories).
1.663     raeburn  12884: 
1.655     raeburn  12885: jsarray (reference to array of categories used to create Javascript arrays for
                   12886:          Domain Coordinator interface for editing Course Categories).
                   12887: 
                   12888: Returns: nothing
                   12889: 
                   12890: Side effects: populates cats, idx and jsarray. 
                   12891: 
                   12892: =cut
                   12893: 
                   12894: sub gather_categories {
                   12895:     my ($categories,$cats,$idx,$jsarray) = @_;
                   12896:     my %counters;
                   12897:     my $num = 0;
                   12898:     foreach my $item (keys(%{$categories})) {
                   12899:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   12900:         if ($container eq '' && $depth == 0) {
                   12901:             $cats->[$depth][$categories->{$item}] = $cat;
                   12902:         } else {
                   12903:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   12904:         }
                   12905:         my ($escitem,$tail) = split(/:/,$item,2);
                   12906:         if ($counters{$tail} eq '') {
                   12907:             $counters{$tail} = $num;
                   12908:             $num ++;
                   12909:         }
                   12910:         if (ref($idx) eq 'HASH') {
                   12911:             $idx->{$item} = $counters{$tail};
                   12912:         }
                   12913:         if (ref($jsarray) eq 'ARRAY') {
                   12914:             push(@{$jsarray->[$counters{$tail}]},$item);
                   12915:         }
                   12916:     }
                   12917:     return;
                   12918: }
                   12919: 
                   12920: =pod
                   12921: 
                   12922: =item * &extract_categories()
                   12923: 
                   12924: Used to generate breadcrumb trails for course categories.
                   12925: 
                   12926: Inputs:
1.663     raeburn  12927: 
1.655     raeburn  12928: categories (reference to hash of category definitions).
1.663     raeburn  12929: 
1.655     raeburn  12930: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12931:       categories and subcategories).
1.663     raeburn  12932: 
1.655     raeburn  12933: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  12934: 
1.655     raeburn  12935: allitems (reference to hash - key is category key 
                   12936:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12937: 
1.655     raeburn  12938: idx (reference to hash of counters used in Domain Coordinator interface for
                   12939:       editing Course Categories).
1.663     raeburn  12940: 
1.655     raeburn  12941: jsarray (reference to array of categories used to create Javascript arrays for
                   12942:          Domain Coordinator interface for editing Course Categories).
                   12943: 
1.665     raeburn  12944: subcats (reference to hash of arrays containing all subcategories within each 
                   12945:          category, -recursive)
                   12946: 
1.655     raeburn  12947: Returns: nothing
                   12948: 
                   12949: Side effects: populates trails and allitems hash references.
                   12950: 
                   12951: =cut
                   12952: 
                   12953: sub extract_categories {
1.665     raeburn  12954:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  12955:     if (ref($categories) eq 'HASH') {
                   12956:         &gather_categories($categories,$cats,$idx,$jsarray);
                   12957:         if (ref($cats->[0]) eq 'ARRAY') {
                   12958:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   12959:                 my $name = $cats->[0][$i];
                   12960:                 my $item = &escape($name).'::0';
                   12961:                 my $trailstr;
                   12962:                 if ($name eq 'instcode') {
                   12963:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  12964:                 } elsif ($name eq 'communities') {
                   12965:                     $trailstr = &mt('Communities');
1.655     raeburn  12966:                 } else {
                   12967:                     $trailstr = $name;
                   12968:                 }
                   12969:                 if ($allitems->{$item} eq '') {
                   12970:                     push(@{$trails},$trailstr);
                   12971:                     $allitems->{$item} = scalar(@{$trails})-1;
                   12972:                 }
                   12973:                 my @parents = ($name);
                   12974:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   12975:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   12976:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  12977:                         if (ref($subcats) eq 'HASH') {
                   12978:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   12979:                         }
                   12980:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   12981:                     }
                   12982:                 } else {
                   12983:                     if (ref($subcats) eq 'HASH') {
                   12984:                         $subcats->{$item} = [];
1.655     raeburn  12985:                     }
                   12986:                 }
                   12987:             }
                   12988:         }
                   12989:     }
                   12990:     return;
                   12991: }
                   12992: 
                   12993: =pod
                   12994: 
                   12995: =item *&recurse_categories()
                   12996: 
                   12997: Recursively used to generate breadcrumb trails for course categories.
                   12998: 
                   12999: Inputs:
1.663     raeburn  13000: 
1.655     raeburn  13001: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13002:       categories and subcategories).
1.663     raeburn  13003: 
1.655     raeburn  13004: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13005: 
                   13006: category (current course category, for which breadcrumb trail is being generated).
                   13007: 
                   13008: trails (reference to array of breadcrumb trails for each category).
                   13009: 
1.655     raeburn  13010: allitems (reference to hash - key is category key
                   13011:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13012: 
1.655     raeburn  13013: parents (array containing containers directories for current category, 
                   13014:          back to top level). 
                   13015: 
                   13016: Returns: nothing
                   13017: 
                   13018: Side effects: populates trails and allitems hash references
                   13019: 
                   13020: =cut
                   13021: 
                   13022: sub recurse_categories {
1.665     raeburn  13023:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13024:     my $shallower = $depth - 1;
                   13025:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13026:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13027:             my $name = $cats->[$depth]{$category}[$k];
                   13028:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13029:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13030:             if ($allitems->{$item} eq '') {
                   13031:                 push(@{$trails},$trailstr);
                   13032:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13033:             }
                   13034:             my $deeper = $depth+1;
                   13035:             push(@{$parents},$category);
1.665     raeburn  13036:             if (ref($subcats) eq 'HASH') {
                   13037:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13038:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13039:                     my $higher;
                   13040:                     if ($j > 0) {
                   13041:                         $higher = &escape($parents->[$j]).':'.
                   13042:                                   &escape($parents->[$j-1]).':'.$j;
                   13043:                     } else {
                   13044:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13045:                     }
                   13046:                     push(@{$subcats->{$higher}},$subcat);
                   13047:                 }
                   13048:             }
                   13049:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13050:                                 $subcats);
1.655     raeburn  13051:             pop(@{$parents});
                   13052:         }
                   13053:     } else {
                   13054:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13055:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13056:         if ($allitems->{$item} eq '') {
                   13057:             push(@{$trails},$trailstr);
                   13058:             $allitems->{$item} = scalar(@{$trails})-1;
                   13059:         }
                   13060:     }
                   13061:     return;
                   13062: }
                   13063: 
1.663     raeburn  13064: =pod
                   13065: 
                   13066: =item *&assign_categories_table()
                   13067: 
                   13068: Create a datatable for display of hierarchical categories in a domain,
                   13069: with checkboxes to allow a course to be categorized. 
                   13070: 
                   13071: Inputs:
                   13072: 
                   13073: cathash - reference to hash of categories defined for the domain (from
                   13074:           configuration.db)
                   13075: 
                   13076: currcat - scalar with an & separated list of categories assigned to a course. 
                   13077: 
1.919     raeburn  13078: type    - scalar contains course type (Course or Community).
                   13079: 
1.663     raeburn  13080: Returns: $output (markup to be displayed) 
                   13081: 
                   13082: =cut
                   13083: 
                   13084: sub assign_categories_table {
1.919     raeburn  13085:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13086:     my $output;
                   13087:     if (ref($cathash) eq 'HASH') {
                   13088:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13089:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13090:         $maxdepth = scalar(@cats);
                   13091:         if (@cats > 0) {
                   13092:             my $itemcount = 0;
                   13093:             if (ref($cats[0]) eq 'ARRAY') {
                   13094:                 my @currcategories;
                   13095:                 if ($currcat ne '') {
                   13096:                     @currcategories = split('&',$currcat);
                   13097:                 }
1.919     raeburn  13098:                 my $table;
1.663     raeburn  13099:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13100:                     my $parent = $cats[0][$i];
1.919     raeburn  13101:                     next if ($parent eq 'instcode');
                   13102:                     if ($type eq 'Community') {
                   13103:                         next unless ($parent eq 'communities');
                   13104:                     } else {
                   13105:                         next if ($parent eq 'communities');
                   13106:                     }
1.663     raeburn  13107:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13108:                     my $item = &escape($parent).'::0';
                   13109:                     my $checked = '';
                   13110:                     if (@currcategories > 0) {
                   13111:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13112:                             $checked = ' checked="checked"';
1.663     raeburn  13113:                         }
                   13114:                     }
1.919     raeburn  13115:                     my $parent_title = $parent;
                   13116:                     if ($parent eq 'communities') {
                   13117:                         $parent_title = &mt('Communities');
                   13118:                     }
                   13119:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13120:                               '<input type="checkbox" name="usecategory" value="'.
                   13121:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13122:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13123:                     my $depth = 1;
                   13124:                     push(@path,$parent);
1.919     raeburn  13125:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13126:                     pop(@path);
1.919     raeburn  13127:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13128:                     $itemcount ++;
                   13129:                 }
1.919     raeburn  13130:                 if ($itemcount) {
                   13131:                     $output = &Apache::loncommon::start_data_table().
                   13132:                               $table.
                   13133:                               &Apache::loncommon::end_data_table();
                   13134:                 }
1.663     raeburn  13135:             }
                   13136:         }
                   13137:     }
                   13138:     return $output;
                   13139: }
                   13140: 
                   13141: =pod
                   13142: 
                   13143: =item *&assign_category_rows()
                   13144: 
                   13145: Create a datatable row for display of nested categories in a domain,
                   13146: with checkboxes to allow a course to be categorized,called recursively.
                   13147: 
                   13148: Inputs:
                   13149: 
                   13150: itemcount - track row number for alternating colors
                   13151: 
                   13152: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13153:       categories and subcategories.
                   13154: 
                   13155: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13156: 
                   13157: parent - parent of current category item
                   13158: 
                   13159: path - Array containing all categories back up through the hierarchy from the
                   13160:        current category to the top level.
                   13161: 
                   13162: currcategories - reference to array of current categories assigned to the course
                   13163: 
                   13164: Returns: $output (markup to be displayed).
                   13165: 
                   13166: =cut
                   13167: 
                   13168: sub assign_category_rows {
                   13169:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13170:     my ($text,$name,$item,$chgstr);
                   13171:     if (ref($cats) eq 'ARRAY') {
                   13172:         my $maxdepth = scalar(@{$cats});
                   13173:         if (ref($cats->[$depth]) eq 'HASH') {
                   13174:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13175:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13176:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13177:                 $text .= '<td><table class="LC_datatable">';
                   13178:                 for (my $j=0; $j<$numchildren; $j++) {
                   13179:                     $name = $cats->[$depth]{$parent}[$j];
                   13180:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13181:                     my $deeper = $depth+1;
                   13182:                     my $checked = '';
                   13183:                     if (ref($currcategories) eq 'ARRAY') {
                   13184:                         if (@{$currcategories} > 0) {
                   13185:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13186:                                 $checked = ' checked="checked"';
1.663     raeburn  13187:                             }
                   13188:                         }
                   13189:                     }
1.664     raeburn  13190:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13191:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13192:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13193:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13194:                              '</td><td>';
1.663     raeburn  13195:                     if (ref($path) eq 'ARRAY') {
                   13196:                         push(@{$path},$name);
                   13197:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13198:                         pop(@{$path});
                   13199:                     }
                   13200:                     $text .= '</td></tr>';
                   13201:                 }
                   13202:                 $text .= '</table></td>';
                   13203:             }
                   13204:         }
                   13205:     }
                   13206:     return $text;
                   13207: }
                   13208: 
1.655     raeburn  13209: ############################################################
                   13210: ############################################################
                   13211: 
                   13212: 
1.443     albertel 13213: sub commit_customrole {
1.664     raeburn  13214:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13215:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13216:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13217:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13218:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13219:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13220:                  '</b><br />';
                   13221:     return $output;
                   13222: }
                   13223: 
                   13224: sub commit_standardrole {
1.1116    raeburn  13225:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13226:     my ($output,$logmsg,$linefeed);
                   13227:     if ($context eq 'auto') {
                   13228:         $linefeed = "\n";
                   13229:     } else {
                   13230:         $linefeed = "<br />\n";
                   13231:     }  
1.443     albertel 13232:     if ($three eq 'st') {
1.541     raeburn  13233:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  13234:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13235:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13236:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13237:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13238:         } else {
1.541     raeburn  13239:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13240:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13241:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13242:             if ($context eq 'auto') {
                   13243:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13244:             } else {
                   13245:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13246:                &mt('Add to classlist').': <b>ok</b>';
                   13247:             }
                   13248:             $output .= $linefeed;
1.443     albertel 13249:         }
                   13250:     } else {
                   13251:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13252:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13253:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13254:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13255:         if ($context eq 'auto') {
                   13256:             $output .= $result.$linefeed;
                   13257:         } else {
                   13258:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13259:         }
1.443     albertel 13260:     }
                   13261:     return $output;
                   13262: }
                   13263: 
                   13264: sub commit_studentrole {
1.1116    raeburn  13265:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13266:         $credits) = @_;
1.626     raeburn  13267:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13268:     if ($context eq 'auto') {
                   13269:         $linefeed = "\n";
                   13270:     } else {
                   13271:         $linefeed = '<br />'."\n";
                   13272:     }
1.443     albertel 13273:     if (defined($one) && defined($two)) {
                   13274:         my $cid=$one.'_'.$two;
                   13275:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13276:         my $secchange = 0;
                   13277:         my $expire_role_result;
                   13278:         my $modify_section_result;
1.628     raeburn  13279:         if ($oldsec ne '-1') { 
                   13280:             if ($oldsec ne $sec) {
1.443     albertel 13281:                 $secchange = 1;
1.628     raeburn  13282:                 my $now = time;
1.443     albertel 13283:                 my $uurl='/'.$cid;
                   13284:                 $uurl=~s/\_/\//g;
                   13285:                 if ($oldsec) {
                   13286:                     $uurl.='/'.$oldsec;
                   13287:                 }
1.626     raeburn  13288:                 $oldsecurl = $uurl;
1.628     raeburn  13289:                 $expire_role_result = 
1.652     raeburn  13290:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13291:                 if ($env{'request.course.sec'} ne '') { 
                   13292:                     if ($expire_role_result eq 'refused') {
                   13293:                         my @roles = ('st');
                   13294:                         my @statuses = ('previous');
                   13295:                         my @roledoms = ($one);
                   13296:                         my $withsec = 1;
                   13297:                         my %roleshash = 
                   13298:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13299:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13300:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13301:                             my ($oldstart,$oldend) = 
                   13302:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13303:                             if ($oldend > 0 && $oldend <= $now) {
                   13304:                                 $expire_role_result = 'ok';
                   13305:                             }
                   13306:                         }
                   13307:                     }
                   13308:                 }
1.443     albertel 13309:                 $result = $expire_role_result;
                   13310:             }
                   13311:         }
                   13312:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  13313:             $modify_section_result = 
                   13314:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13315:                                                            undef,undef,undef,$sec,
                   13316:                                                            $end,$start,'','',$cid,
                   13317:                                                            '',$context,$credits);
1.443     albertel 13318:             if ($modify_section_result =~ /^ok/) {
                   13319:                 if ($secchange == 1) {
1.628     raeburn  13320:                     if ($sec eq '') {
                   13321:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13322:                     } else {
                   13323:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13324:                     }
1.443     albertel 13325:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13326:                     if ($sec eq '') {
                   13327:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13328:                     } else {
                   13329:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13330:                     }
1.443     albertel 13331:                 } else {
1.628     raeburn  13332:                     if ($sec eq '') {
                   13333:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13334:                     } else {
                   13335:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13336:                     }
1.443     albertel 13337:                 }
                   13338:             } else {
1.1115    raeburn  13339:                 if ($secchange) { 
1.628     raeburn  13340:                     $$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;
                   13341:                 } else {
                   13342:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13343:                 }
1.443     albertel 13344:             }
                   13345:             $result = $modify_section_result;
                   13346:         } elsif ($secchange == 1) {
1.628     raeburn  13347:             if ($oldsec eq '') {
1.1103    raeburn  13348:                 $$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  13349:             } else {
                   13350:                 $$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;
                   13351:             }
1.626     raeburn  13352:             if ($expire_role_result eq 'refused') {
                   13353:                 my $newsecurl = '/'.$cid;
                   13354:                 $newsecurl =~ s/\_/\//g;
                   13355:                 if ($sec ne '') {
                   13356:                     $newsecurl.='/'.$sec;
                   13357:                 }
                   13358:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13359:                     if ($sec eq '') {
                   13360:                         $$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;
                   13361:                     } else {
                   13362:                         $$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;
                   13363:                     }
                   13364:                 }
                   13365:             }
1.443     albertel 13366:         }
                   13367:     } else {
1.626     raeburn  13368:         $$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 13369:         $result = "error: incomplete course id\n";
                   13370:     }
                   13371:     return $result;
                   13372: }
                   13373: 
1.1108    raeburn  13374: sub show_role_extent {
                   13375:     my ($scope,$context,$role) = @_;
                   13376:     $scope =~ s{^/}{};
                   13377:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   13378:     push(@courseroles,'co');
                   13379:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   13380:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   13381:         $scope =~ s{/}{_};
                   13382:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   13383:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   13384:         my ($audom,$auname) = split(/\//,$scope);
                   13385:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   13386:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   13387:     } else {
                   13388:         $scope =~ s{/$}{};
                   13389:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   13390:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   13391:     }
                   13392: }
                   13393: 
1.443     albertel 13394: ############################################################
                   13395: ############################################################
                   13396: 
1.566     albertel 13397: sub check_clone {
1.578     raeburn  13398:     my ($args,$linefeed) = @_;
1.566     albertel 13399:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13400:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13401:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13402:     my $clonemsg;
                   13403:     my $can_clone = 0;
1.944     raeburn  13404:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13405:     if ($lctype ne 'community') {
                   13406:         $lctype = 'course';
                   13407:     }
1.566     albertel 13408:     if ($clonehome eq 'no_host') {
1.944     raeburn  13409:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13410:             $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'});
                   13411:         } else {
                   13412:             $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'});
                   13413:         }     
1.566     albertel 13414:     } else {
                   13415: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13416:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13417:             if ($clonedesc{'type'} ne 'Community') {
                   13418:                  $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'});
                   13419:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13420:             }
                   13421:         }
1.882     raeburn  13422: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13423:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13424: 	    $can_clone = 1;
                   13425: 	} else {
                   13426: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13427: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13428: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13429:             if (grep(/^\*$/,@cloners)) {
                   13430:                 $can_clone = 1;
                   13431:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13432:                 $can_clone = 1;
                   13433:             } else {
1.908     raeburn  13434:                 my $ccrole = 'cc';
1.944     raeburn  13435:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13436:                     $ccrole = 'co';
                   13437:                 }
1.578     raeburn  13438: 	        my %roleshash =
                   13439: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13440: 					 $args->{'ccdomain'},
1.908     raeburn  13441:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13442: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13443: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13444:                     $can_clone = 1;
                   13445:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13446:                     $can_clone = 1;
                   13447:                 } else {
1.944     raeburn  13448:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13449:                         $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'});
                   13450:                     } else {
                   13451:                         $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'});
                   13452:                     }
1.578     raeburn  13453: 	        }
1.566     albertel 13454: 	    }
1.578     raeburn  13455:         }
1.566     albertel 13456:     }
                   13457:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13458: }
                   13459: 
1.444     albertel 13460: sub construct_course {
1.885     raeburn  13461:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 13462:     my $outcome;
1.541     raeburn  13463:     my $linefeed =  '<br />'."\n";
                   13464:     if ($context eq 'auto') {
                   13465:         $linefeed = "\n";
                   13466:     }
1.566     albertel 13467: 
                   13468: #
                   13469: # Are we cloning?
                   13470: #
                   13471:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13472:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13473: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13474: 	if ($context ne 'auto') {
1.578     raeburn  13475:             if ($clonemsg ne '') {
                   13476: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13477:             }
1.566     albertel 13478: 	}
                   13479: 	$outcome .= $clonemsg.$linefeed;
                   13480: 
                   13481:         if (!$can_clone) {
                   13482: 	    return (0,$outcome);
                   13483: 	}
                   13484:     }
                   13485: 
1.444     albertel 13486: #
                   13487: # Open course
                   13488: #
                   13489:     my $crstype = lc($args->{'crstype'});
                   13490:     my %cenv=();
                   13491:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13492:                                              $args->{'cdescr'},
                   13493:                                              $args->{'curl'},
                   13494:                                              $args->{'course_home'},
                   13495:                                              $args->{'nonstandard'},
                   13496:                                              $args->{'crscode'},
                   13497:                                              $args->{'ccuname'}.':'.
                   13498:                                              $args->{'ccdomain'},
1.882     raeburn  13499:                                              $args->{'crstype'},
1.885     raeburn  13500:                                              $cnum,$context,$category);
1.444     albertel 13501: 
                   13502:     # Note: The testing routines depend on this being output; see 
                   13503:     # Utils::Course. This needs to at least be output as a comment
                   13504:     # if anyone ever decides to not show this, and Utils::Course::new
                   13505:     # will need to be suitably modified.
1.541     raeburn  13506:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13507:     if ($$courseid =~ /^error:/) {
                   13508:         return (0,$outcome);
                   13509:     }
                   13510: 
1.444     albertel 13511: #
                   13512: # Check if created correctly
                   13513: #
1.479     albertel 13514:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13515:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13516:     if ($crsuhome eq 'no_host') {
                   13517:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13518:         return (0,$outcome);
                   13519:     }
1.541     raeburn  13520:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13521: 
1.444     albertel 13522: #
1.566     albertel 13523: # Do the cloning
                   13524: #   
                   13525:     if ($can_clone && $cloneid) {
                   13526: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13527: 	if ($context ne 'auto') {
                   13528: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13529: 	}
                   13530: 	$outcome .= $clonemsg.$linefeed;
                   13531: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13532: # Copy all files
1.637     www      13533: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13534: # Restore URL
1.566     albertel 13535: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13536: # Restore title
1.566     albertel 13537: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13538: # Restore creation date, creator and creation context.
                   13539:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13540:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13541:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13542: # Mark as cloned
1.566     albertel 13543: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13544: # Need to clone grading mode
                   13545:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13546:         $cenv{'grading'}=$newenv{'grading'};
                   13547: # Do not clone these environment entries
                   13548:         &Apache::lonnet::del('environment',
                   13549:                   ['default_enrollment_start_date',
                   13550:                    'default_enrollment_end_date',
                   13551:                    'question.email',
                   13552:                    'policy.email',
                   13553:                    'comment.email',
                   13554:                    'pch.users.denied',
1.725     raeburn  13555:                    'plc.users.denied',
                   13556:                    'hidefromcat',
1.1121    raeburn  13557:                    'checkforpriv',
1.725     raeburn  13558:                    'categories'],
1.638     www      13559:                    $$crsudom,$$crsunum);
1.444     albertel 13560:     }
1.566     albertel 13561: 
1.444     albertel 13562: #
                   13563: # Set environment (will override cloned, if existing)
                   13564: #
                   13565:     my @sections = ();
                   13566:     my @xlists = ();
                   13567:     if ($args->{'crstype'}) {
                   13568:         $cenv{'type'}=$args->{'crstype'};
                   13569:     }
                   13570:     if ($args->{'crsid'}) {
                   13571:         $cenv{'courseid'}=$args->{'crsid'};
                   13572:     }
                   13573:     if ($args->{'crscode'}) {
                   13574:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   13575:     }
                   13576:     if ($args->{'crsquota'} ne '') {
                   13577:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   13578:     } else {
                   13579:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   13580:     }
                   13581:     if ($args->{'ccuname'}) {
                   13582:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   13583:                                         ':'.$args->{'ccdomain'};
                   13584:     } else {
                   13585:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   13586:     }
1.1116    raeburn  13587:     if ($args->{'defaultcredits'}) {
                   13588:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   13589:     }
1.444     albertel 13590:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   13591:     if ($args->{'crssections'}) {
                   13592:         $cenv{'internal.sectionnums'} = '';
                   13593:         if ($args->{'crssections'} =~ m/,/) {
                   13594:             @sections = split/,/,$args->{'crssections'};
                   13595:         } else {
                   13596:             $sections[0] = $args->{'crssections'};
                   13597:         }
                   13598:         if (@sections > 0) {
                   13599:             foreach my $item (@sections) {
                   13600:                 my ($sec,$gp) = split/:/,$item;
                   13601:                 my $class = $args->{'crscode'}.$sec;
                   13602:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   13603:                 $cenv{'internal.sectionnums'} .= $item.',';
                   13604:                 unless ($addcheck eq 'ok') {
                   13605:                     push @badclasses, $class;
                   13606:                 }
                   13607:             }
                   13608:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   13609:         }
                   13610:     }
                   13611: # do not hide course coordinator from staff listing, 
                   13612: # even if privileged
                   13613:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  13614: # add course coordinator's domain to domains to check for privileged users
                   13615: # if different to course domain
                   13616:     if ($$crsudom ne $args->{'ccdomain'}) {
                   13617:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   13618:     }
1.444     albertel 13619: # add crosslistings
                   13620:     if ($args->{'crsxlist'}) {
                   13621:         $cenv{'internal.crosslistings'}='';
                   13622:         if ($args->{'crsxlist'} =~ m/,/) {
                   13623:             @xlists = split/,/,$args->{'crsxlist'};
                   13624:         } else {
                   13625:             $xlists[0] = $args->{'crsxlist'};
                   13626:         }
                   13627:         if (@xlists > 0) {
                   13628:             foreach my $item (@xlists) {
                   13629:                 my ($xl,$gp) = split/:/,$item;
                   13630:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   13631:                 $cenv{'internal.crosslistings'} .= $item.',';
                   13632:                 unless ($addcheck eq 'ok') {
                   13633:                     push @badclasses, $xl;
                   13634:                 }
                   13635:             }
                   13636:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   13637:         }
                   13638:     }
                   13639:     if ($args->{'autoadds'}) {
                   13640:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   13641:     }
                   13642:     if ($args->{'autodrops'}) {
                   13643:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   13644:     }
                   13645: # check for notification of enrollment changes
                   13646:     my @notified = ();
                   13647:     if ($args->{'notify_owner'}) {
                   13648:         if ($args->{'ccuname'} ne '') {
                   13649:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   13650:         }
                   13651:     }
                   13652:     if ($args->{'notify_dc'}) {
                   13653:         if ($uname ne '') { 
1.630     raeburn  13654:             push(@notified,$uname.':'.$udom);
1.444     albertel 13655:         }
                   13656:     }
                   13657:     if (@notified > 0) {
                   13658:         my $notifylist;
                   13659:         if (@notified > 1) {
                   13660:             $notifylist = join(',',@notified);
                   13661:         } else {
                   13662:             $notifylist = $notified[0];
                   13663:         }
                   13664:         $cenv{'internal.notifylist'} = $notifylist;
                   13665:     }
                   13666:     if (@badclasses > 0) {
                   13667:         my %lt=&Apache::lonlocal::texthash(
                   13668:                 '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',
                   13669:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   13670:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   13671:         );
1.541     raeburn  13672:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   13673:                            ' ('.$lt{'adby'}.')';
                   13674:         if ($context eq 'auto') {
                   13675:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 13676:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  13677:             foreach my $item (@badclasses) {
                   13678:                 if ($context eq 'auto') {
                   13679:                     $outcome .= " - $item\n";
                   13680:                 } else {
                   13681:                     $outcome .= "<li>$item</li>\n";
                   13682:                 }
                   13683:             }
                   13684:             if ($context eq 'auto') {
                   13685:                 $outcome .= $linefeed;
                   13686:             } else {
1.566     albertel 13687:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  13688:             }
                   13689:         } 
1.444     albertel 13690:     }
                   13691:     if ($args->{'no_end_date'}) {
                   13692:         $args->{'endaccess'} = 0;
                   13693:     }
                   13694:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   13695:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   13696:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   13697:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   13698:     if ($args->{'showphotos'}) {
                   13699:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   13700:     }
                   13701:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   13702:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   13703:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   13704:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  13705:             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'); 
                   13706:             if ($context eq 'auto') {
                   13707:                 $outcome .= $krb_msg;
                   13708:             } else {
1.566     albertel 13709:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  13710:             }
                   13711:             $outcome .= $linefeed;
1.444     albertel 13712:         }
                   13713:     }
                   13714:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   13715:        if ($args->{'setpolicy'}) {
                   13716:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13717:        }
                   13718:        if ($args->{'setcontent'}) {
                   13719:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13720:        }
                   13721:     }
                   13722:     if ($args->{'reshome'}) {
                   13723: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   13724: 	$cenv{'reshome'}=~s/\/+$/\//;
                   13725:     }
                   13726: #
                   13727: # course has keyed access
                   13728: #
                   13729:     if ($args->{'setkeys'}) {
                   13730:        $cenv{'keyaccess'}='yes';
                   13731:     }
                   13732: # if specified, key authority is not course, but user
                   13733: # only active if keyaccess is yes
                   13734:     if ($args->{'keyauth'}) {
1.487     albertel 13735: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   13736: 	$user = &LONCAPA::clean_username($user);
                   13737: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     13738: 	if ($user ne '' && $domain ne '') {
1.487     albertel 13739: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 13740: 	}
                   13741:     }
                   13742: 
                   13743:     if ($args->{'disresdis'}) {
                   13744:         $cenv{'pch.roles.denied'}='st';
                   13745:     }
                   13746:     if ($args->{'disablechat'}) {
                   13747:         $cenv{'plc.roles.denied'}='st';
                   13748:     }
                   13749: 
                   13750:     # Record we've not yet viewed the Course Initialization Helper for this 
                   13751:     # course
                   13752:     $cenv{'course.helper.not.run'} = 1;
                   13753:     #
                   13754:     # Use new Randomseed
                   13755:     #
                   13756:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   13757:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   13758:     #
                   13759:     # The encryption code and receipt prefix for this course
                   13760:     #
                   13761:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   13762:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   13763:     #
                   13764:     # By default, use standard grading
                   13765:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   13766: 
1.541     raeburn  13767:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   13768:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13769: #
                   13770: # Open all assignments
                   13771: #
                   13772:     if ($args->{'openall'}) {
                   13773:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   13774:        my %storecontent = ($storeunder         => time,
                   13775:                            $storeunder.'.type' => 'date_start');
                   13776:        
                   13777:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  13778:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13779:    }
                   13780: #
                   13781: # Set first page
                   13782: #
                   13783:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   13784: 	    || ($cloneid)) {
1.445     albertel 13785: 	use LONCAPA::map;
1.444     albertel 13786: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 13787: 
                   13788: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   13789:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   13790: 
1.444     albertel 13791:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   13792:         my $title; my $url;
                   13793:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   13794: 	    $title=&mt('Syllabus');
1.444     albertel 13795:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   13796:         } else {
1.963     raeburn  13797:             $title=&mt('Table of Contents');
1.444     albertel 13798:             $url='/adm/navmaps';
                   13799:         }
1.445     albertel 13800: 
                   13801:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   13802: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   13803: 
                   13804: 	if ($errtext) { $fatal=2; }
1.541     raeburn  13805:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 13806:     }
1.566     albertel 13807: 
                   13808:     return (1,$outcome);
1.444     albertel 13809: }
                   13810: 
                   13811: ############################################################
                   13812: ############################################################
                   13813: 
1.953     droeschl 13814: #SD
                   13815: # only Community and Course, or anything else?
1.378     raeburn  13816: sub course_type {
                   13817:     my ($cid) = @_;
                   13818:     if (!defined($cid)) {
                   13819:         $cid = $env{'request.course.id'};
                   13820:     }
1.404     albertel 13821:     if (defined($env{'course.'.$cid.'.type'})) {
                   13822:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  13823:     } else {
                   13824:         return 'Course';
1.377     raeburn  13825:     }
                   13826: }
1.156     albertel 13827: 
1.406     raeburn  13828: sub group_term {
                   13829:     my $crstype = &course_type();
                   13830:     my %names = (
                   13831:                   'Course' => 'group',
1.865     raeburn  13832:                   'Community' => 'group',
1.406     raeburn  13833:                 );
                   13834:     return $names{$crstype};
                   13835: }
                   13836: 
1.902     raeburn  13837: sub course_types {
                   13838:     my @types = ('official','unofficial','community');
                   13839:     my %typename = (
                   13840:                          official   => 'Official course',
                   13841:                          unofficial => 'Unofficial course',
                   13842:                          community  => 'Community',
                   13843:                    );
                   13844:     return (\@types,\%typename);
                   13845: }
                   13846: 
1.156     albertel 13847: sub icon {
                   13848:     my ($file)=@_;
1.505     albertel 13849:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 13850:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 13851:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 13852:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   13853: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   13854: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13855: 	            $curfext.".gif") {
                   13856: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13857: 		$curfext.".gif";
                   13858: 	}
                   13859:     }
1.249     albertel 13860:     return &lonhttpdurl($iconname);
1.154     albertel 13861: } 
1.84      albertel 13862: 
1.575     albertel 13863: sub lonhttpdurl {
1.692     www      13864: #
                   13865: # Had been used for "small fry" static images on separate port 8080.
                   13866: # Modify here if lightweight http functionality desired again.
                   13867: # Currently eliminated due to increasing firewall issues.
                   13868: #
1.575     albertel 13869:     my ($url)=@_;
1.692     www      13870:     return $url;
1.215     albertel 13871: }
                   13872: 
1.213     albertel 13873: sub connection_aborted {
                   13874:     my ($r)=@_;
                   13875:     $r->print(" ");$r->rflush();
                   13876:     my $c = $r->connection;
                   13877:     return $c->aborted();
                   13878: }
                   13879: 
1.221     foxr     13880: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     13881: #    strings as 'strings'.
                   13882: sub escape_single {
1.221     foxr     13883:     my ($input) = @_;
1.223     albertel 13884:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     13885:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   13886:     return $input;
                   13887: }
1.223     albertel 13888: 
1.222     foxr     13889: #  Same as escape_single, but escape's "'s  This 
                   13890: #  can be used for  "strings"
                   13891: sub escape_double {
                   13892:     my ($input) = @_;
                   13893:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   13894:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   13895:     return $input;
                   13896: }
1.223     albertel 13897:  
1.222     foxr     13898: #   Escapes the last element of a full URL.
                   13899: sub escape_url {
                   13900:     my ($url)   = @_;
1.238     raeburn  13901:     my @urlslices = split(/\//, $url,-1);
1.369     www      13902:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 13903:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     13904: }
1.462     albertel 13905: 
1.820     raeburn  13906: sub compare_arrays {
                   13907:     my ($arrayref1,$arrayref2) = @_;
                   13908:     my (@difference,%count);
                   13909:     @difference = ();
                   13910:     %count = ();
                   13911:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   13912:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   13913:         foreach my $element (keys(%count)) {
                   13914:             if ($count{$element} == 1) {
                   13915:                 push(@difference,$element);
                   13916:             }
                   13917:         }
                   13918:     }
                   13919:     return @difference;
                   13920: }
                   13921: 
1.817     bisitz   13922: # -------------------------------------------------------- Initialize user login
1.462     albertel 13923: sub init_user_environment {
1.463     albertel 13924:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 13925:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   13926: 
                   13927:     my $public=($username eq 'public' && $domain eq 'public');
                   13928: 
                   13929: # See if old ID present, if so, remove
                   13930: 
1.1062    raeburn  13931:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 13932:     my $now=time;
                   13933: 
                   13934:     if ($public) {
                   13935: 	my $max_public=100;
                   13936: 	my $oldest;
                   13937: 	my $oldest_time=0;
                   13938: 	for(my $next=1;$next<=$max_public;$next++) {
                   13939: 	    if (-e $lonids."/publicuser_$next.id") {
                   13940: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   13941: 		if ($mtime<$oldest_time || !$oldest_time) {
                   13942: 		    $oldest_time=$mtime;
                   13943: 		    $oldest=$next;
                   13944: 		}
                   13945: 	    } else {
                   13946: 		$cookie="publicuser_$next";
                   13947: 		last;
                   13948: 	    }
                   13949: 	}
                   13950: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   13951:     } else {
1.463     albertel 13952: 	# if this isn't a robot, kill any existing non-robot sessions
                   13953: 	if (!$args->{'robot'}) {
                   13954: 	    opendir(DIR,$lonids);
                   13955: 	    while ($filename=readdir(DIR)) {
                   13956: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   13957: 		    unlink($lonids.'/'.$filename);
                   13958: 		}
1.462     albertel 13959: 	    }
1.463     albertel 13960: 	    closedir(DIR);
1.462     albertel 13961: 	}
                   13962: # Give them a new cookie
1.463     albertel 13963: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      13964: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 13965: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 13966:     
                   13967: # Initialize roles
                   13968: 
1.1062    raeburn  13969: 	($userroles,$firstaccenv,$timerintenv) = 
                   13970:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 13971:     }
                   13972: # ------------------------------------ Check browser type and MathML capability
                   13973: 
                   13974:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   13975:         $clientunicode,$clientos) = &decode_user_agent($r);
                   13976: 
                   13977: # ------------------------------------------------------------- Get environment
                   13978: 
                   13979:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   13980:     my ($tmp) = keys(%userenv);
                   13981:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   13982:     } else {
                   13983: 	undef(%userenv);
                   13984:     }
                   13985:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   13986: 	$form->{'interface'}=$userenv{'interface'};
                   13987:     }
                   13988:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   13989: 
                   13990: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   13991:     foreach my $option ('interface','localpath','localres') {
                   13992:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 13993:     }
                   13994: # --------------------------------------------------------- Write first profile
                   13995: 
                   13996:     {
                   13997: 	my %initial_env = 
                   13998: 	    ("user.name"          => $username,
                   13999: 	     "user.domain"        => $domain,
                   14000: 	     "user.home"          => $authhost,
                   14001: 	     "browser.type"       => $clientbrowser,
                   14002: 	     "browser.version"    => $clientversion,
                   14003: 	     "browser.mathml"     => $clientmathml,
                   14004: 	     "browser.unicode"    => $clientunicode,
                   14005: 	     "browser.os"         => $clientos,
                   14006: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14007: 	     "request.course.fn"  => '',
                   14008: 	     "request.course.uri" => '',
                   14009: 	     "request.course.sec" => '',
                   14010: 	     "request.role"       => 'cm',
                   14011: 	     "request.role.adv"   => $env{'user.adv'},
                   14012: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14013: 
                   14014:         if ($form->{'localpath'}) {
                   14015: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14016: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14017:         }
                   14018: 	
                   14019: 	if ($form->{'interface'}) {
                   14020: 	    $form->{'interface'}=~s/\W//gs;
                   14021: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14022: 	    $env{'browser.interface'}=$form->{'interface'};
                   14023: 	}
                   14024: 
1.981     raeburn  14025:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14026:         my %domdef;
                   14027:         unless ($domain eq 'public') {
                   14028:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14029:         }
1.980     raeburn  14030: 
1.1081    raeburn  14031:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14032:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14033:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14034:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14035:         }
                   14036: 
1.864     raeburn  14037:         foreach my $crstype ('official','unofficial','community') {
1.765     raeburn  14038:             $userenv{'canrequest.'.$crstype} =
                   14039:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14040:                                                   'reload','requestcourses',
                   14041:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14042:         }
                   14043: 
1.1092    raeburn  14044:         $userenv{'canrequest.author'} =
                   14045:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14046:                                         'reload','requestauthor',
                   14047:                                         \%userenv,\%domdef,\%is_adv);
                   14048:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14049:                                              $domain,$username);
                   14050:         my $reqstatus = $reqauthor{'author_status'};
                   14051:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   14052:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14053:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14054:                                                   $reqauthor{'author'}{'timestamp'};
                   14055:             }
                   14056:         }
                   14057: 
1.462     albertel 14058: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14059: 
1.462     albertel 14060: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14061: 		 &GDBM_WRCREAT(),0640)) {
                   14062: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14063: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14064: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14065:             if (ref($firstaccenv) eq 'HASH') {
                   14066:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14067:             }
                   14068:             if (ref($timerintenv) eq 'HASH') {
                   14069:                 &_add_to_env(\%disk_env,$timerintenv);
                   14070:             }
1.463     albertel 14071: 	    if (ref($args->{'extra_env'})) {
                   14072: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14073: 	    }
1.462     albertel 14074: 	    untie(%disk_env);
                   14075: 	} else {
1.705     tempelho 14076: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14077: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14078: 	    return 'error: '.$!;
                   14079: 	}
                   14080:     }
                   14081:     $env{'request.role'}='cm';
                   14082:     $env{'request.role.adv'}=$env{'user.adv'};
                   14083:     $env{'browser.type'}=$clientbrowser;
                   14084: 
                   14085:     return $cookie;
                   14086: 
                   14087: }
                   14088: 
                   14089: sub _add_to_env {
                   14090:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14091:     if (ref($env_data) eq 'HASH') {
                   14092:         while (my ($key,$value) = each(%$env_data)) {
                   14093: 	    $idf->{$prefix.$key} = $value;
                   14094: 	    $env{$prefix.$key}   = $value;
                   14095:         }
1.462     albertel 14096:     }
                   14097: }
                   14098: 
1.685     tempelho 14099: # --- Get the symbolic name of a problem and the url
                   14100: sub get_symb {
                   14101:     my ($request,$silent) = @_;
1.726     raeburn  14102:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14103:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14104:     if ($symb eq '') {
                   14105:         if (!$silent) {
1.1071    raeburn  14106:             if (ref($request)) { 
                   14107:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14108:             }
1.685     tempelho 14109:             return ();
                   14110:         }
                   14111:     }
                   14112:     &Apache::lonenc::check_decrypt(\$symb);
                   14113:     return ($symb);
                   14114: }
                   14115: 
                   14116: # --------------------------------------------------------------Get annotation
                   14117: 
                   14118: sub get_annotation {
                   14119:     my ($symb,$enc) = @_;
                   14120: 
                   14121:     my $key = $symb;
                   14122:     if (!$enc) {
                   14123:         $key =
                   14124:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14125:     }
                   14126:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14127:     return $annotation{$key};
                   14128: }
                   14129: 
                   14130: sub clean_symb {
1.731     raeburn  14131:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14132: 
                   14133:     &Apache::lonenc::check_decrypt(\$symb);
                   14134:     my $enc = $env{'request.enc'};
1.731     raeburn  14135:     if ($delete_enc) {
1.730     raeburn  14136:         delete($env{'request.enc'});
                   14137:     }
1.685     tempelho 14138: 
                   14139:     return ($symb,$enc);
                   14140: }
1.462     albertel 14141: 
1.990     raeburn  14142: sub build_release_hashes {
                   14143:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14144:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14145:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14146:                   (ref($randomizetry) eq 'HASH'));
                   14147:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14148:         my ($item,$name,$value) = split(/:/,$key);
                   14149:         if ($item eq 'parameter') {
                   14150:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14151:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14152:                     push(@{$checkparms->{$name}},$value);
                   14153:                 }
                   14154:             } else {
                   14155:                 push(@{$checkparms->{$name}},$value);
                   14156:             }
                   14157:         } elsif ($item eq 'resourcetag') {
                   14158:             if ($name eq 'responsetype') {
                   14159:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14160:             }
                   14161:         } elsif ($item eq 'course') {
                   14162:             if ($name eq 'crstype') {
                   14163:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14164:             }
                   14165:         }
                   14166:     }
                   14167:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14168:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14169:     return;
                   14170: }
                   14171: 
1.1083    raeburn  14172: sub update_content_constraints {
                   14173:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14174:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14175:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14176:     my %checkresponsetypes;
                   14177:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14178:         my ($item,$name,$value) = split(/:/,$key);
                   14179:         if ($item eq 'resourcetag') {
                   14180:             if ($name eq 'responsetype') {
                   14181:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14182:             }
                   14183:         }
                   14184:     }
                   14185:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14186:     if (defined($navmap)) {
                   14187:         my %allresponses;
                   14188:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14189:             my %responses = $res->responseTypes();
                   14190:             foreach my $key (keys(%responses)) {
                   14191:                 next unless(exists($checkresponsetypes{$key}));
                   14192:                 $allresponses{$key} += $responses{$key};
                   14193:             }
                   14194:         }
                   14195:         foreach my $key (keys(%allresponses)) {
                   14196:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14197:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14198:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14199:             }
                   14200:         }
                   14201:         undef($navmap);
                   14202:     }
                   14203:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14204:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14205:     }
                   14206:     return;
                   14207: }
                   14208: 
1.1110    raeburn  14209: sub allmaps_incourse {
                   14210:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14211:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   14212:         $cid = $env{'request.course.id'};
                   14213:         $cdom = $env{'course.'.$cid.'.domain'};
                   14214:         $cnum = $env{'course.'.$cid.'.num'};
                   14215:         $chome = $env{'course.'.$cid.'.home'};
                   14216:     }
                   14217:     my %allmaps = ();
                   14218:     my $lastchange =
                   14219:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   14220:     if ($lastchange > $env{'request.course.tied'}) {
                   14221:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   14222:         unless ($ferr) {
                   14223:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   14224:         }
                   14225:     }
                   14226:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14227:     if (defined($navmap)) {
                   14228:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   14229:             $allmaps{$res->src()} = 1;
                   14230:         }
                   14231:     }
                   14232:     return \%allmaps;
                   14233: }
                   14234: 
1.1083    raeburn  14235: sub parse_supplemental_title {
                   14236:     my ($title) = @_;
                   14237: 
                   14238:     my ($foldertitle,$renametitle);
                   14239:     if ($title =~ /&amp;&amp;&amp;/) {
                   14240:         $title = &HTML::Entites::decode($title);
                   14241:     }
                   14242:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14243:         $renametitle=$4;
                   14244:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14245:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14246:         my $name =  &plainname($uname,$udom);
                   14247:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14248:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14249:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14250:             $name.': <br />'.$foldertitle;
                   14251:     }
                   14252:     if (wantarray) {
                   14253:         return ($title,$foldertitle,$renametitle);
                   14254:     }
                   14255:     return $title;
                   14256: }
                   14257: 
1.1101    raeburn  14258: sub symb_to_docspath {
                   14259:     my ($symb) = @_;
                   14260:     return unless ($symb);
                   14261:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14262:     if ($resurl=~/\.(sequence|page)$/) {
                   14263:         $mapurl=$resurl;
                   14264:     } elsif ($resurl eq 'adm/navmaps') {
                   14265:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14266:     }
                   14267:     my $mapresobj;
                   14268:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14269:     if (ref($navmap)) {
                   14270:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14271:     }
                   14272:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14273:     my $type=$2;
                   14274:     my $path;
                   14275:     if (ref($mapresobj)) {
                   14276:         my $pcslist = $mapresobj->map_hierarchy();
                   14277:         if ($pcslist ne '') {
                   14278:             foreach my $pc (split(/,/,$pcslist)) {
                   14279:                 next if ($pc <= 1);
                   14280:                 my $res = $navmap->getByMapPc($pc);
                   14281:                 if (ref($res)) {
                   14282:                     my $thisurl = $res->src();
                   14283:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14284:                     my $thistitle = $res->title();
                   14285:                     $path .= '&'.
                   14286:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   14287:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
                   14288:                              ':'.$res->randompick().
                   14289:                              ':'.$res->randomout().
                   14290:                              ':'.$res->encrypted().
                   14291:                              ':'.$res->randomorder().
                   14292:                              ':'.$res->is_page();
                   14293:                 }
                   14294:             }
                   14295:         }
                   14296:         $path =~ s/^\&//;
                   14297:         my $maptitle = $mapresobj->title();
                   14298:         if ($mapurl eq 'default') {
                   14299:             $maptitle = 'Main Course Documents';
                   14300:         }
                   14301:         $path .= (($path ne '')? '&' : '').
                   14302:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14303:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
                   14304:                  ':'.$mapresobj->randompick().
                   14305:                  ':'.$mapresobj->randomout().
                   14306:                  ':'.$mapresobj->encrypted().
                   14307:                  ':'.$mapresobj->randomorder().
                   14308:                  ':'.$mapresobj->is_page();
                   14309:     } else {
                   14310:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14311:         my $ispage = (($type eq 'page')? 1 : '');
                   14312:         if ($mapurl eq 'default') {
                   14313:             $maptitle = 'Main Course Documents';
                   14314:         }
                   14315:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14316:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   14317:     }
                   14318:     unless ($mapurl eq 'default') {
                   14319:         $path = 'default&'.
                   14320:                 &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   14321:                 ':::::&'.$path;
                   14322:     }
                   14323:     return $path;
                   14324: }
                   14325: 
1.1094    raeburn  14326: sub captcha_display {
                   14327:     my ($context,$lonhost) = @_;
                   14328:     my ($output,$error);
                   14329:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14330:     if ($captcha eq 'original') {
1.1094    raeburn  14331:         $output = &create_captcha();
                   14332:         unless ($output) {
                   14333:             $error = 'captcha'; 
                   14334:         }
                   14335:     } elsif ($captcha eq 'recaptcha') {
                   14336:         $output = &create_recaptcha($pubkey);
                   14337:         unless ($output) {
1.1095    raeburn  14338:             $error = 'recaptcha'; 
1.1094    raeburn  14339:         }
                   14340:     }
                   14341:     return ($output,$error);
                   14342: }
                   14343: 
                   14344: sub captcha_response {
                   14345:     my ($context,$lonhost) = @_;
                   14346:     my ($captcha_chk,$captcha_error);
                   14347:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14348:     if ($captcha eq 'original') {
1.1094    raeburn  14349:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14350:     } elsif ($captcha eq 'recaptcha') {
                   14351:         $captcha_chk = &check_recaptcha($privkey);
                   14352:     } else {
                   14353:         $captcha_chk = 1;
                   14354:     }
                   14355:     return ($captcha_chk,$captcha_error);
                   14356: }
                   14357: 
                   14358: sub get_captcha_config {
                   14359:     my ($context,$lonhost) = @_;
1.1095    raeburn  14360:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  14361:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14362:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14363:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  14364:     if ($context eq 'usercreation') {
                   14365:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14366:         if (ref($domconfig{$context}) eq 'HASH') {
                   14367:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14368:             if (ref($hashtocheck) eq 'HASH') {
                   14369:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14370:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14371:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14372:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14373:                     }
                   14374:                     if ($privkey && $pubkey) {
                   14375:                         $captcha = 'recaptcha';
                   14376:                     } else {
                   14377:                         $captcha = 'original';
                   14378:                     }
                   14379:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14380:                     $captcha = 'original';
                   14381:                 }
1.1094    raeburn  14382:             }
1.1095    raeburn  14383:         } else {
                   14384:             $captcha = 'captcha';
                   14385:         }
                   14386:     } elsif ($context eq 'login') {
                   14387:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14388:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14389:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14390:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  14391:             if ($privkey && $pubkey) {
                   14392:                 $captcha = 'recaptcha';
1.1095    raeburn  14393:             } else {
                   14394:                 $captcha = 'original';
1.1094    raeburn  14395:             }
1.1095    raeburn  14396:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14397:             $captcha = 'original';
1.1094    raeburn  14398:         }
                   14399:     }
                   14400:     return ($captcha,$pubkey,$privkey);
                   14401: }
                   14402: 
                   14403: sub create_captcha {
                   14404:     my %captcha_params = &captcha_settings();
                   14405:     my ($output,$maxtries,$tries) = ('',10,0);
                   14406:     while ($tries < $maxtries) {
                   14407:         $tries ++;
                   14408:         my $captcha = Authen::Captcha->new (
                   14409:                                            output_folder => $captcha_params{'output_dir'},
                   14410:                                            data_folder   => $captcha_params{'db_dir'},
                   14411:                                           );
                   14412:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14413: 
                   14414:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14415:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14416:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14417:                      '<input type="text" size="5" name="code" value="" /><br />'.
                   14418:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
                   14419:             last;
                   14420:         }
                   14421:     }
                   14422:     return $output;
                   14423: }
                   14424: 
                   14425: sub captcha_settings {
                   14426:     my %captcha_params = (
                   14427:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14428:                            www_output_dir => "/captchaspool",
                   14429:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14430:                            numchars       => '5',
                   14431:                          );
                   14432:     return %captcha_params;
                   14433: }
                   14434: 
                   14435: sub check_captcha {
                   14436:     my ($captcha_chk,$captcha_error);
                   14437:     my $code = $env{'form.code'};
                   14438:     my $md5sum = $env{'form.crypt'};
                   14439:     my %captcha_params = &captcha_settings();
                   14440:     my $captcha = Authen::Captcha->new(
                   14441:                       output_folder => $captcha_params{'output_dir'},
                   14442:                       data_folder   => $captcha_params{'db_dir'},
                   14443:                   );
1.1109    raeburn  14444:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  14445:     my %captcha_hash = (
                   14446:                         0       => 'Code not checked (file error)',
                   14447:                        -1      => 'Failed: code expired',
                   14448:                        -2      => 'Failed: invalid code (not in database)',
                   14449:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   14450:     );
                   14451:     if ($captcha_chk != 1) {
                   14452:         $captcha_error = $captcha_hash{$captcha_chk}
                   14453:     }
                   14454:     return ($captcha_chk,$captcha_error);
                   14455: }
                   14456: 
                   14457: sub create_recaptcha {
                   14458:     my ($pubkey) = @_;
                   14459:     my $captcha = Captcha::reCAPTCHA->new;
                   14460:     return $captcha->get_options_setter({theme => 'white'})."\n".
                   14461:            $captcha->get_html($pubkey).
                   14462:            &mt('If either word is hard to read, [_1] will replace them.',
                   14463:                '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   14464:            '<br /><br />';
                   14465: }
                   14466: 
                   14467: sub check_recaptcha {
                   14468:     my ($privkey) = @_;
                   14469:     my $captcha_chk;
                   14470:     my $captcha = Captcha::reCAPTCHA->new;
                   14471:     my $captcha_result =
                   14472:         $captcha->check_answer(
                   14473:                                 $privkey,
                   14474:                                 $ENV{'REMOTE_ADDR'},
                   14475:                                 $env{'form.recaptcha_challenge_field'},
                   14476:                                 $env{'form.recaptcha_response_field'},
                   14477:                               );
                   14478:     if ($captcha_result->{is_valid}) {
                   14479:         $captcha_chk = 1;
                   14480:     }
                   14481:     return $captcha_chk;
                   14482: }
                   14483: 
1.41      ng       14484: =pod
                   14485: 
                   14486: =back
                   14487: 
1.112     bowersj2 14488: =cut
1.41      ng       14489: 
1.112     bowersj2 14490: 1;
                   14491: __END__;
1.41      ng       14492: 

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