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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1134  ! raeburn     4: # $Id: loncommon.pm,v 1.1133 2013/06/05 12:39:34 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.1132    raeburn  4935: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  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
1.1132    raeburn  4998:          To be included on Authoring Space pages
1.822     bisitz   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?
1.1132    raeburn  5029:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   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.1131    raeburn  5158:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5159: 
1.1130    raeburn  5160:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5161:         return $bodytag;
1.1130    raeburn  5162:     }
1.359     albertel 5163: 
1.954     raeburn  5164:     if ($public) {
1.433     albertel 5165: 	undef($role);
                   5166:     }
1.359     albertel 5167:     
1.762     bisitz   5168:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5169:     #
                   5170:     # Extra info if you are the DC
                   5171:     my $dc_info = '';
                   5172:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5173:                         $env{'course.'.$env{'request.course.id'}.
                   5174:                                  '.domain'}.'/'})) {
                   5175:         my $cid = $env{'request.course.id'};
1.917     raeburn  5176:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5177:         $dc_info =~ s/\s+$//;
1.359     albertel 5178:     }
                   5179: 
1.898     raeburn  5180:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5181: 
1.903     droeschl 5182:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5183: 
                   5184:         #    if ($env{'request.state'} eq 'construct') {
                   5185:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5186:         #    }
                   5187: 
1.1130    raeburn  5188:         $bodytag .= Apache::lonhtmlcommon::scripttag(
                   5189:             Apache::lonmenu::utilityfunctions(), 'start');
1.359     albertel 5190: 
1.1130    raeburn  5191:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.359     albertel 5192: 
1.916     droeschl 5193:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5194:              if ($dc_info) {
                   5195:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5196:              }
1.1130    raeburn  5197:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5198:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5199:             return $bodytag;
                   5200:         }
1.894     droeschl 5201: 
1.927     raeburn  5202:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5203:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5204:         }
1.916     droeschl 5205: 
1.1130    raeburn  5206:         $bodytag .= $right;
1.852     droeschl 5207: 
1.917     raeburn  5208:         if ($dc_info) {
                   5209:             $dc_info = &dc_courseid_toggle($dc_info);
                   5210:         }
                   5211:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5212: 
1.903     droeschl 5213:         #don't show menus for public users
1.954     raeburn  5214:         if (!$public){
1.903     droeschl 5215:             $bodytag .= Apache::lonmenu::secondary_menu();
                   5216:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5217:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5218:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5219:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5220:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5221:             } elsif ($forcereg) {
                   5222:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5223:                                                             $args->{'group'});
                   5224:             } else {
                   5225:                 $bodytag .= 
                   5226:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5227:                                                         $forcereg,$args->{'group'},
                   5228:                                                         $args->{'bread_crumbs'},
                   5229:                                                         $advtoolsref);
1.920     raeburn  5230:             }
1.903     droeschl 5231:         }else{
                   5232:             # this is to seperate menu from content when there's no secondary
                   5233:             # menu. Especially needed for public accessible ressources.
                   5234:             $bodytag .= '<hr style="clear:both" />';
                   5235:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5236:         }
1.903     droeschl 5237: 
1.235     raeburn  5238:         return $bodytag;
1.182     matthew  5239: }
                   5240: 
1.917     raeburn  5241: sub dc_courseid_toggle {
                   5242:     my ($dc_info) = @_;
1.980     raeburn  5243:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5244:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5245:            &mt('(More ...)').'</a></span>'.
                   5246:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5247: }
                   5248: 
1.330     albertel 5249: sub make_attr_string {
                   5250:     my ($register,$attr_ref) = @_;
                   5251: 
                   5252:     if ($attr_ref && !ref($attr_ref)) {
                   5253: 	die("addentries Must be a hash ref ".
                   5254: 	    join(':',caller(1))." ".
                   5255: 	    join(':',caller(0))." ");
                   5256:     }
                   5257: 
                   5258:     if ($register) {
1.339     albertel 5259: 	my ($on_load,$on_unload);
                   5260: 	foreach my $key (keys(%{$attr_ref})) {
                   5261: 	    if      (lc($key) eq 'onload') {
                   5262: 		$on_load.=$attr_ref->{$key}.';';
                   5263: 		delete($attr_ref->{$key});
                   5264: 
                   5265: 	    } elsif (lc($key) eq 'onunload') {
                   5266: 		$on_unload.=$attr_ref->{$key}.';';
                   5267: 		delete($attr_ref->{$key});
                   5268: 	    }
                   5269: 	}
1.953     droeschl 5270: 	$attr_ref->{'onload'}  = $on_load;
                   5271: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5272:     }
1.339     albertel 5273: 
1.330     albertel 5274:     my $attr_string;
                   5275:     foreach my $attr (keys(%$attr_ref)) {
                   5276: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5277:     }
                   5278:     return $attr_string;
                   5279: }
                   5280: 
                   5281: 
1.182     matthew  5282: ###############################################
1.251     albertel 5283: ###############################################
                   5284: 
                   5285: =pod
                   5286: 
                   5287: =item * &endbodytag()
                   5288: 
                   5289: Returns a uniform footer for LON-CAPA web pages.
                   5290: 
1.635     raeburn  5291: Inputs: 1 - optional reference to an args hash
                   5292: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5293: a 'Continue' link is not displayed if the page contains an
                   5294: internal redirect in the <head></head> section,
                   5295: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5296: 
                   5297: =cut
                   5298: 
                   5299: sub endbodytag {
1.635     raeburn  5300:     my ($args) = @_;
1.1080    raeburn  5301:     my $endbodytag;
                   5302:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5303:         $endbodytag='</body>';
                   5304:     }
1.269     albertel 5305:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5306:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5307:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5308: 	    $endbodytag=
                   5309: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5310: 	        &mt('Continue').'</a>'.
                   5311: 	        $endbodytag;
                   5312:         }
1.315     albertel 5313:     }
1.251     albertel 5314:     return $endbodytag;
                   5315: }
                   5316: 
1.352     albertel 5317: =pod
                   5318: 
                   5319: =item * &standard_css()
                   5320: 
                   5321: Returns a style sheet
                   5322: 
                   5323: Inputs: (all optional)
                   5324:             domain         -> force to color decorate a page for a specific
                   5325:                                domain
                   5326:             function       -> force usage of a specific rolish color scheme
                   5327:             bgcolor        -> override the default page bgcolor
                   5328: 
                   5329: =cut
                   5330: 
1.343     albertel 5331: sub standard_css {
1.345     albertel 5332:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5333:     $function  = &get_users_function() if (!$function);
                   5334:     my $img    = &designparm($function.'.img',   $domain);
                   5335:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5336:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5337:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5338: #second colour for later usage
1.345     albertel 5339:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5340:     my $pgbg_or_bgcolor =
                   5341: 	         $bgcolor ||
1.352     albertel 5342: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5343:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5344:     my $alink  = &designparm($function.'.alink', $domain);
                   5345:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5346:     my $link   = &designparm($function.'.link',  $domain);
                   5347: 
1.602     albertel 5348:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5349:     my $mono                 = 'monospace';
1.850     bisitz   5350:     my $data_table_head      = $sidebg;
                   5351:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5352:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5353:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5354:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5355:     my $mail_new             = '#FFBB77';
                   5356:     my $mail_new_hover       = '#DD9955';
                   5357:     my $mail_read            = '#BBBB77';
                   5358:     my $mail_read_hover      = '#999944';
                   5359:     my $mail_replied         = '#AAAA88';
                   5360:     my $mail_replied_hover   = '#888855';
                   5361:     my $mail_other           = '#99BBBB';
                   5362:     my $mail_other_hover     = '#669999';
1.391     albertel 5363:     my $table_header         = '#DDDDDD';
1.489     raeburn  5364:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5365:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5366:     my $button_hover         = '#BF2317';
1.392     albertel 5367: 
1.608     albertel 5368:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5369:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5370:                                              : '0 3px 0 4px';
1.448     albertel 5371: 
1.523     albertel 5372: 
1.343     albertel 5373:     return <<END;
1.947     droeschl 5374: 
                   5375: /* needed for iframe to allow 100% height in FF */
                   5376: body, html { 
                   5377:     margin: 0;
                   5378:     padding: 0 0.5%;
                   5379:     height: 99%; /* to avoid scrollbars */
                   5380: }
                   5381: 
1.795     www      5382: body {
1.911     bisitz   5383:   font-family: $sans;
                   5384:   line-height:130%;
                   5385:   font-size:0.83em;
                   5386:   color:$font;
1.795     www      5387: }
                   5388: 
1.959     onken    5389: a:focus,
                   5390: a:focus img {
1.795     www      5391:   color: red;
                   5392: }
1.698     harmsja  5393: 
1.911     bisitz   5394: form, .inline {
                   5395:   display: inline;
1.795     www      5396: }
1.721     harmsja  5397: 
1.795     www      5398: .LC_right {
1.911     bisitz   5399:   text-align:right;
1.795     www      5400: }
                   5401: 
                   5402: .LC_middle {
1.911     bisitz   5403:   vertical-align:middle;
1.795     www      5404: }
1.721     harmsja  5405: 
1.1130    raeburn  5406: .LC_floatleft {
                   5407:   float: left;
                   5408: }
                   5409: 
                   5410: .LC_floatright {
                   5411:   float: right;
                   5412: }
                   5413: 
1.911     bisitz   5414: .LC_400Box {
                   5415:   width:400px;
                   5416: }
1.721     harmsja  5417: 
1.947     droeschl 5418: .LC_iframecontainer {
                   5419:     width: 98%;
                   5420:     margin: 0;
                   5421:     position: fixed;
                   5422:     top: 8.5em;
                   5423:     bottom: 0;
                   5424: }
                   5425: 
                   5426: .LC_iframecontainer iframe{
                   5427:     border: none;
                   5428:     width: 100%;
                   5429:     height: 100%;
                   5430: }
                   5431: 
1.778     bisitz   5432: .LC_filename {
                   5433:   font-family: $mono;
                   5434:   white-space:pre;
1.921     bisitz   5435:   font-size: 120%;
1.778     bisitz   5436: }
                   5437: 
                   5438: .LC_fileicon {
                   5439:   border: none;
                   5440:   height: 1.3em;
                   5441:   vertical-align: text-bottom;
                   5442:   margin-right: 0.3em;
                   5443:   text-decoration:none;
                   5444: }
                   5445: 
1.1008    www      5446: .LC_setting {
                   5447:   text-decoration:underline;
                   5448: }
                   5449: 
1.350     albertel 5450: .LC_error {
                   5451:   color: red;
                   5452: }
1.795     www      5453: 
1.1097    bisitz   5454: .LC_warning {
                   5455:   color: darkorange;
                   5456: }
                   5457: 
1.457     albertel 5458: .LC_diff_removed {
1.733     bisitz   5459:   color: red;
1.394     albertel 5460: }
1.532     albertel 5461: 
                   5462: .LC_info,
1.457     albertel 5463: .LC_success,
                   5464: .LC_diff_added {
1.350     albertel 5465:   color: green;
                   5466: }
1.795     www      5467: 
1.802     bisitz   5468: div.LC_confirm_box {
                   5469:   background-color: #FAFAFA;
                   5470:   border: 1px solid $lg_border_color;
                   5471:   margin-right: 0;
                   5472:   padding: 5px;
                   5473: }
                   5474: 
                   5475: div.LC_confirm_box .LC_error img,
                   5476: div.LC_confirm_box .LC_success img {
                   5477:   vertical-align: middle;
                   5478: }
                   5479: 
1.440     albertel 5480: .LC_icon {
1.771     droeschl 5481:   border: none;
1.790     droeschl 5482:   vertical-align: middle;
1.771     droeschl 5483: }
                   5484: 
1.543     albertel 5485: .LC_docs_spacer {
                   5486:   width: 25px;
                   5487:   height: 1px;
1.771     droeschl 5488:   border: none;
1.543     albertel 5489: }
1.346     albertel 5490: 
1.532     albertel 5491: .LC_internal_info {
1.735     bisitz   5492:   color: #999999;
1.532     albertel 5493: }
                   5494: 
1.794     www      5495: .LC_discussion {
1.1050    www      5496:   background: $data_table_dark;
1.911     bisitz   5497:   border: 1px solid black;
                   5498:   margin: 2px;
1.794     www      5499: }
                   5500: 
                   5501: .LC_disc_action_left {
1.1050    www      5502:   background: $sidebg;
1.911     bisitz   5503:   text-align: left;
1.1050    www      5504:   padding: 4px;
                   5505:   margin: 2px;
1.794     www      5506: }
                   5507: 
                   5508: .LC_disc_action_right {
1.1050    www      5509:   background: $sidebg;
1.911     bisitz   5510:   text-align: right;
1.1050    www      5511:   padding: 4px;
                   5512:   margin: 2px;
1.794     www      5513: }
                   5514: 
                   5515: .LC_disc_new_item {
1.911     bisitz   5516:   background: white;
                   5517:   border: 2px solid red;
1.1050    www      5518:   margin: 4px;
                   5519:   padding: 4px;
1.794     www      5520: }
                   5521: 
                   5522: .LC_disc_old_item {
1.911     bisitz   5523:   background: white;
1.1050    www      5524:   margin: 4px;
                   5525:   padding: 4px;
1.794     www      5526: }
                   5527: 
1.458     albertel 5528: table.LC_pastsubmission {
                   5529:   border: 1px solid black;
                   5530:   margin: 2px;
                   5531: }
                   5532: 
1.924     bisitz   5533: table#LC_menubuttons {
1.345     albertel 5534:   width: 100%;
                   5535:   background: $pgbg;
1.392     albertel 5536:   border: 2px;
1.402     albertel 5537:   border-collapse: separate;
1.803     bisitz   5538:   padding: 0;
1.345     albertel 5539: }
1.392     albertel 5540: 
1.801     tempelho 5541: table#LC_title_bar a {
                   5542:   color: $fontmenu;
                   5543: }
1.836     bisitz   5544: 
1.807     droeschl 5545: table#LC_title_bar {
1.819     tempelho 5546:   clear: both;
1.836     bisitz   5547:   display: none;
1.807     droeschl 5548: }
                   5549: 
1.795     www      5550: table#LC_title_bar,
1.933     droeschl 5551: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5552: table#LC_title_bar.LC_with_remote {
1.359     albertel 5553:   width: 100%;
1.392     albertel 5554:   border-color: $pgbg;
                   5555:   border-style: solid;
                   5556:   border-width: $border;
1.379     albertel 5557:   background: $pgbg;
1.801     tempelho 5558:   color: $fontmenu;
1.392     albertel 5559:   border-collapse: collapse;
1.803     bisitz   5560:   padding: 0;
1.819     tempelho 5561:   margin: 0;
1.359     albertel 5562: }
1.795     www      5563: 
1.933     droeschl 5564: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5565:     margin: 0;
                   5566:     padding: 0;
1.933     droeschl 5567:     position: relative;
                   5568:     list-style: none;
1.913     droeschl 5569: }
1.933     droeschl 5570: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5571:     display: inline;
                   5572: }
1.933     droeschl 5573: 
                   5574: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5575:     padding: 0;
1.933     droeschl 5576:     margin: 0;
                   5577:     float: left;
1.913     droeschl 5578: }
1.933     droeschl 5579: .LC_breadcrumb_tools_tools {
                   5580:     padding: 0;
                   5581:     margin: 0;
1.913     droeschl 5582:     float: right;
                   5583: }
                   5584: 
1.359     albertel 5585: table#LC_title_bar td {
                   5586:   background: $tabbg;
                   5587: }
1.795     www      5588: 
1.911     bisitz   5589: table#LC_menubuttons img {
1.803     bisitz   5590:   border: none;
1.346     albertel 5591: }
1.795     www      5592: 
1.842     droeschl 5593: .LC_breadcrumbs_component {
1.911     bisitz   5594:   float: right;
                   5595:   margin: 0 1em;
1.357     albertel 5596: }
1.842     droeschl 5597: .LC_breadcrumbs_component img {
1.911     bisitz   5598:   vertical-align: middle;
1.777     tempelho 5599: }
1.795     www      5600: 
1.383     albertel 5601: td.LC_table_cell_checkbox {
                   5602:   text-align: center;
                   5603: }
1.795     www      5604: 
                   5605: .LC_fontsize_small {
1.911     bisitz   5606:   font-size: 70%;
1.705     tempelho 5607: }
                   5608: 
1.844     bisitz   5609: #LC_breadcrumbs {
1.911     bisitz   5610:   clear:both;
                   5611:   background: $sidebg;
                   5612:   border-bottom: 1px solid $lg_border_color;
                   5613:   line-height: 2.5em;
1.933     droeschl 5614:   overflow: hidden;
1.911     bisitz   5615:   margin: 0;
                   5616:   padding: 0;
1.995     raeburn  5617:   text-align: left;
1.819     tempelho 5618: }
1.862     bisitz   5619: 
1.1098    bisitz   5620: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5621:   clear:both;
                   5622:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5623:   border: 1px solid $sidebg;
1.1098    bisitz   5624:   margin: 0 0 10px 0;
1.966     bisitz   5625:   padding: 3px;
1.995     raeburn  5626:   text-align: left;
1.822     bisitz   5627: }
                   5628: 
1.795     www      5629: .LC_fontsize_medium {
1.911     bisitz   5630:   font-size: 85%;
1.705     tempelho 5631: }
                   5632: 
1.795     www      5633: .LC_fontsize_large {
1.911     bisitz   5634:   font-size: 120%;
1.705     tempelho 5635: }
                   5636: 
1.346     albertel 5637: .LC_menubuttons_inline_text {
                   5638:   color: $font;
1.698     harmsja  5639:   font-size: 90%;
1.701     harmsja  5640:   padding-left:3px;
1.346     albertel 5641: }
                   5642: 
1.934     droeschl 5643: .LC_menubuttons_inline_text img{
                   5644:   vertical-align: middle;
                   5645: }
                   5646: 
1.1051    www      5647: li.LC_menubuttons_inline_text img {
1.951     onken    5648:   cursor:pointer;
1.1002    droeschl 5649:   text-decoration: none;
1.951     onken    5650: }
                   5651: 
1.526     www      5652: .LC_menubuttons_link {
                   5653:   text-decoration: none;
                   5654: }
1.795     www      5655: 
1.522     albertel 5656: .LC_menubuttons_category {
1.521     www      5657:   color: $font;
1.526     www      5658:   background: $pgbg;
1.521     www      5659:   font-size: larger;
                   5660:   font-weight: bold;
                   5661: }
                   5662: 
1.346     albertel 5663: td.LC_menubuttons_text {
1.911     bisitz   5664:   color: $font;
1.346     albertel 5665: }
1.706     harmsja  5666: 
1.346     albertel 5667: .LC_current_location {
                   5668:   background: $tabbg;
                   5669: }
1.795     www      5670: 
1.938     bisitz   5671: table.LC_data_table {
1.347     albertel 5672:   border: 1px solid #000000;
1.402     albertel 5673:   border-collapse: separate;
1.426     albertel 5674:   border-spacing: 1px;
1.610     albertel 5675:   background: $pgbg;
1.347     albertel 5676: }
1.795     www      5677: 
1.422     albertel 5678: .LC_data_table_dense {
                   5679:   font-size: small;
                   5680: }
1.795     www      5681: 
1.507     raeburn  5682: table.LC_nested_outer {
                   5683:   border: 1px solid #000000;
1.589     raeburn  5684:   border-collapse: collapse;
1.803     bisitz   5685:   border-spacing: 0;
1.507     raeburn  5686:   width: 100%;
                   5687: }
1.795     www      5688: 
1.879     raeburn  5689: table.LC_innerpickbox,
1.507     raeburn  5690: table.LC_nested {
1.803     bisitz   5691:   border: none;
1.589     raeburn  5692:   border-collapse: collapse;
1.803     bisitz   5693:   border-spacing: 0;
1.507     raeburn  5694:   width: 100%;
                   5695: }
1.795     www      5696: 
1.911     bisitz   5697: table.LC_data_table tr th,
                   5698: table.LC_calendar tr th,
1.879     raeburn  5699: table.LC_prior_tries tr th,
                   5700: table.LC_innerpickbox tr th {
1.349     albertel 5701:   font-weight: bold;
                   5702:   background-color: $data_table_head;
1.801     tempelho 5703:   color:$fontmenu;
1.701     harmsja  5704:   font-size:90%;
1.347     albertel 5705: }
1.795     www      5706: 
1.879     raeburn  5707: table.LC_innerpickbox tr th,
                   5708: table.LC_innerpickbox tr td {
                   5709:   vertical-align: top;
                   5710: }
                   5711: 
1.711     raeburn  5712: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5713:   background-color: #CCCCCC;
1.711     raeburn  5714:   font-weight: bold;
                   5715:   text-align: left;
                   5716: }
1.795     www      5717: 
1.912     bisitz   5718: table.LC_data_table tr.LC_odd_row > td {
                   5719:   background-color: $data_table_light;
                   5720:   padding: 2px;
                   5721:   vertical-align: top;
                   5722: }
                   5723: 
1.809     bisitz   5724: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5725:   background-color: $data_table_light;
1.912     bisitz   5726:   vertical-align: top;
                   5727: }
                   5728: 
                   5729: table.LC_data_table tr.LC_even_row > td {
                   5730:   background-color: $data_table_dark;
1.425     albertel 5731:   padding: 2px;
1.900     bisitz   5732:   vertical-align: top;
1.347     albertel 5733: }
1.795     www      5734: 
1.809     bisitz   5735: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5736:   background-color: $data_table_dark;
1.900     bisitz   5737:   vertical-align: top;
1.347     albertel 5738: }
1.795     www      5739: 
1.425     albertel 5740: table.LC_data_table tr.LC_data_table_highlight td {
                   5741:   background-color: $data_table_darker;
                   5742: }
1.795     www      5743: 
1.639     raeburn  5744: table.LC_data_table tr td.LC_leftcol_header {
                   5745:   background-color: $data_table_head;
                   5746:   font-weight: bold;
                   5747: }
1.795     www      5748: 
1.451     albertel 5749: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5750: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5751:   font-weight: bold;
                   5752:   font-style: italic;
                   5753:   text-align: center;
                   5754:   padding: 8px;
1.347     albertel 5755: }
1.795     www      5756: 
1.1114    raeburn  5757: table.LC_data_table tr.LC_empty_row td,
                   5758: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5759:   background-color: $sidebg;
                   5760: }
                   5761: 
                   5762: table.LC_nested tr.LC_empty_row td {
                   5763:   background-color: #FFFFFF;
                   5764: }
                   5765: 
1.890     droeschl 5766: table.LC_caption {
                   5767: }
                   5768: 
1.507     raeburn  5769: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5770:   padding: 4ex
                   5771: }
1.795     www      5772: 
1.507     raeburn  5773: table.LC_nested_outer tr th {
                   5774:   font-weight: bold;
1.801     tempelho 5775:   color:$fontmenu;
1.507     raeburn  5776:   background-color: $data_table_head;
1.701     harmsja  5777:   font-size: small;
1.507     raeburn  5778:   border-bottom: 1px solid #000000;
                   5779: }
1.795     www      5780: 
1.507     raeburn  5781: table.LC_nested_outer tr td.LC_subheader {
                   5782:   background-color: $data_table_head;
                   5783:   font-weight: bold;
                   5784:   font-size: small;
                   5785:   border-bottom: 1px solid #000000;
                   5786:   text-align: right;
1.451     albertel 5787: }
1.795     www      5788: 
1.507     raeburn  5789: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5790:   background-color: #CCCCCC;
1.451     albertel 5791:   font-weight: bold;
                   5792:   font-size: small;
1.507     raeburn  5793:   text-align: center;
                   5794: }
1.795     www      5795: 
1.589     raeburn  5796: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5797: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5798:   text-align: left;
1.451     albertel 5799: }
1.795     www      5800: 
1.507     raeburn  5801: table.LC_nested td {
1.735     bisitz   5802:   background-color: #FFFFFF;
1.451     albertel 5803:   font-size: small;
1.507     raeburn  5804: }
1.795     www      5805: 
1.507     raeburn  5806: table.LC_nested_outer tr th.LC_right_item,
                   5807: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5808: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5809: table.LC_nested tr td.LC_right_item {
1.451     albertel 5810:   text-align: right;
                   5811: }
                   5812: 
1.507     raeburn  5813: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5814:   background-color: #EEEEEE;
1.451     albertel 5815: }
                   5816: 
1.473     raeburn  5817: table.LC_createuser {
                   5818: }
                   5819: 
                   5820: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5821:   font-size: small;
1.473     raeburn  5822: }
                   5823: 
                   5824: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5825:   background-color: #CCCCCC;
1.473     raeburn  5826:   font-weight: bold;
                   5827:   text-align: center;
                   5828: }
                   5829: 
1.349     albertel 5830: table.LC_calendar {
                   5831:   border: 1px solid #000000;
                   5832:   border-collapse: collapse;
1.917     raeburn  5833:   width: 98%;
1.349     albertel 5834: }
1.795     www      5835: 
1.349     albertel 5836: table.LC_calendar_pickdate {
                   5837:   font-size: xx-small;
                   5838: }
1.795     www      5839: 
1.349     albertel 5840: table.LC_calendar tr td {
                   5841:   border: 1px solid #000000;
                   5842:   vertical-align: top;
1.917     raeburn  5843:   width: 14%;
1.349     albertel 5844: }
1.795     www      5845: 
1.349     albertel 5846: table.LC_calendar tr td.LC_calendar_day_empty {
                   5847:   background-color: $data_table_dark;
                   5848: }
1.795     www      5849: 
1.779     bisitz   5850: table.LC_calendar tr td.LC_calendar_day_current {
                   5851:   background-color: $data_table_highlight;
1.777     tempelho 5852: }
1.795     www      5853: 
1.938     bisitz   5854: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5855:   background-color: $mail_new;
                   5856: }
1.795     www      5857: 
1.938     bisitz   5858: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5859:   background-color: $mail_new_hover;
                   5860: }
1.795     www      5861: 
1.938     bisitz   5862: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5863:   background-color: $mail_read;
                   5864: }
1.795     www      5865: 
1.938     bisitz   5866: /*
                   5867: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5868:   background-color: $mail_read_hover;
                   5869: }
1.938     bisitz   5870: */
1.795     www      5871: 
1.938     bisitz   5872: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5873:   background-color: $mail_replied;
                   5874: }
1.795     www      5875: 
1.938     bisitz   5876: /*
                   5877: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5878:   background-color: $mail_replied_hover;
                   5879: }
1.938     bisitz   5880: */
1.795     www      5881: 
1.938     bisitz   5882: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5883:   background-color: $mail_other;
                   5884: }
1.795     www      5885: 
1.938     bisitz   5886: /*
                   5887: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5888:   background-color: $mail_other_hover;
                   5889: }
1.938     bisitz   5890: */
1.494     raeburn  5891: 
1.777     tempelho 5892: table.LC_data_table tr > td.LC_browser_file,
                   5893: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5894:   background: #AAEE77;
1.389     albertel 5895: }
1.795     www      5896: 
1.777     tempelho 5897: table.LC_data_table tr > td.LC_browser_file_locked,
                   5898: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5899:   background: #FFAA99;
1.387     albertel 5900: }
1.795     www      5901: 
1.777     tempelho 5902: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5903:   background: #888888;
1.779     bisitz   5904: }
1.795     www      5905: 
1.777     tempelho 5906: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5907: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5908:   background: #F8F866;
1.777     tempelho 5909: }
1.795     www      5910: 
1.696     bisitz   5911: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5912:   background: #E0E8FF;
1.387     albertel 5913: }
1.696     bisitz   5914: 
1.707     bisitz   5915: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5916:   /* background: #77FF77; */
1.707     bisitz   5917: }
1.795     www      5918: 
1.707     bisitz   5919: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5920:   border-right: 8px solid #FFFF77;
1.707     bisitz   5921: }
1.795     www      5922: 
1.707     bisitz   5923: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5924:   border-right: 8px solid #FFAA77;
1.707     bisitz   5925: }
1.795     www      5926: 
1.707     bisitz   5927: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5928:   border-right: 8px solid #FF7777;
1.707     bisitz   5929: }
1.795     www      5930: 
1.707     bisitz   5931: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5932:   border-right: 8px solid #AAFF77;
1.707     bisitz   5933: }
1.795     www      5934: 
1.707     bisitz   5935: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5936:   border-right: 8px solid #11CC55;
1.707     bisitz   5937: }
                   5938: 
1.388     albertel 5939: span.LC_current_location {
1.701     harmsja  5940:   font-size:larger;
1.388     albertel 5941:   background: $pgbg;
                   5942: }
1.387     albertel 5943: 
1.1029    www      5944: span.LC_current_nav_location {
                   5945:   font-weight:bold;
                   5946:   background: $sidebg;
                   5947: }
                   5948: 
1.395     albertel 5949: span.LC_parm_menu_item {
                   5950:   font-size: larger;
                   5951: }
1.795     www      5952: 
1.395     albertel 5953: span.LC_parm_scope_all {
                   5954:   color: red;
                   5955: }
1.795     www      5956: 
1.395     albertel 5957: span.LC_parm_scope_folder {
                   5958:   color: green;
                   5959: }
1.795     www      5960: 
1.395     albertel 5961: span.LC_parm_scope_resource {
                   5962:   color: orange;
                   5963: }
1.795     www      5964: 
1.395     albertel 5965: span.LC_parm_part {
                   5966:   color: blue;
                   5967: }
1.795     www      5968: 
1.911     bisitz   5969: span.LC_parm_folder,
                   5970: span.LC_parm_symb {
1.395     albertel 5971:   font-size: x-small;
                   5972:   font-family: $mono;
                   5973:   color: #AAAAAA;
                   5974: }
                   5975: 
1.977     bisitz   5976: ul.LC_parm_parmlist li {
                   5977:   display: inline-block;
                   5978:   padding: 0.3em 0.8em;
                   5979:   vertical-align: top;
                   5980:   width: 150px;
                   5981:   border-top:1px solid $lg_border_color;
                   5982: }
                   5983: 
1.795     www      5984: td.LC_parm_overview_level_menu,
                   5985: td.LC_parm_overview_map_menu,
                   5986: td.LC_parm_overview_parm_selectors,
                   5987: td.LC_parm_overview_restrictions  {
1.396     albertel 5988:   border: 1px solid black;
                   5989:   border-collapse: collapse;
                   5990: }
1.795     www      5991: 
1.396     albertel 5992: table.LC_parm_overview_restrictions td {
                   5993:   border-width: 1px 4px 1px 4px;
                   5994:   border-style: solid;
                   5995:   border-color: $pgbg;
                   5996:   text-align: center;
                   5997: }
1.795     www      5998: 
1.396     albertel 5999: table.LC_parm_overview_restrictions th {
                   6000:   background: $tabbg;
                   6001:   border-width: 1px 4px 1px 4px;
                   6002:   border-style: solid;
                   6003:   border-color: $pgbg;
                   6004: }
1.795     www      6005: 
1.398     albertel 6006: table#LC_helpmenu {
1.803     bisitz   6007:   border: none;
1.398     albertel 6008:   height: 55px;
1.803     bisitz   6009:   border-spacing: 0;
1.398     albertel 6010: }
                   6011: 
                   6012: table#LC_helpmenu fieldset legend {
                   6013:   font-size: larger;
                   6014: }
1.795     www      6015: 
1.397     albertel 6016: table#LC_helpmenu_links {
                   6017:   width: 100%;
                   6018:   border: 1px solid black;
                   6019:   background: $pgbg;
1.803     bisitz   6020:   padding: 0;
1.397     albertel 6021:   border-spacing: 1px;
                   6022: }
1.795     www      6023: 
1.397     albertel 6024: table#LC_helpmenu_links tr td {
                   6025:   padding: 1px;
                   6026:   background: $tabbg;
1.399     albertel 6027:   text-align: center;
                   6028:   font-weight: bold;
1.397     albertel 6029: }
1.396     albertel 6030: 
1.795     www      6031: table#LC_helpmenu_links a:link,
                   6032: table#LC_helpmenu_links a:visited,
1.397     albertel 6033: table#LC_helpmenu_links a:active {
                   6034:   text-decoration: none;
                   6035:   color: $font;
                   6036: }
1.795     www      6037: 
1.397     albertel 6038: table#LC_helpmenu_links a:hover {
                   6039:   text-decoration: underline;
                   6040:   color: $vlink;
                   6041: }
1.396     albertel 6042: 
1.417     albertel 6043: .LC_chrt_popup_exists {
                   6044:   border: 1px solid #339933;
                   6045:   margin: -1px;
                   6046: }
1.795     www      6047: 
1.417     albertel 6048: .LC_chrt_popup_up {
                   6049:   border: 1px solid yellow;
                   6050:   margin: -1px;
                   6051: }
1.795     www      6052: 
1.417     albertel 6053: .LC_chrt_popup {
                   6054:   border: 1px solid #8888FF;
                   6055:   background: #CCCCFF;
                   6056: }
1.795     www      6057: 
1.421     albertel 6058: table.LC_pick_box {
                   6059:   border-collapse: separate;
                   6060:   background: white;
                   6061:   border: 1px solid black;
                   6062:   border-spacing: 1px;
                   6063: }
1.795     www      6064: 
1.421     albertel 6065: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6066:   background: $sidebg;
1.421     albertel 6067:   font-weight: bold;
1.900     bisitz   6068:   text-align: left;
1.740     bisitz   6069:   vertical-align: top;
1.421     albertel 6070:   width: 184px;
                   6071:   padding: 8px;
                   6072: }
1.795     www      6073: 
1.579     raeburn  6074: table.LC_pick_box td.LC_pick_box_value {
                   6075:   text-align: left;
                   6076:   padding: 8px;
                   6077: }
1.795     www      6078: 
1.579     raeburn  6079: table.LC_pick_box td.LC_pick_box_select {
                   6080:   text-align: left;
                   6081:   padding: 8px;
                   6082: }
1.795     www      6083: 
1.424     albertel 6084: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6085:   padding: 0;
1.421     albertel 6086:   height: 1px;
                   6087:   background: black;
                   6088: }
1.795     www      6089: 
1.421     albertel 6090: table.LC_pick_box td.LC_pick_box_submit {
                   6091:   text-align: right;
                   6092: }
1.795     www      6093: 
1.579     raeburn  6094: table.LC_pick_box td.LC_evenrow_value {
                   6095:   text-align: left;
                   6096:   padding: 8px;
                   6097:   background-color: $data_table_light;
                   6098: }
1.795     www      6099: 
1.579     raeburn  6100: table.LC_pick_box td.LC_oddrow_value {
                   6101:   text-align: left;
                   6102:   padding: 8px;
                   6103:   background-color: $data_table_light;
                   6104: }
1.795     www      6105: 
1.579     raeburn  6106: span.LC_helpform_receipt_cat {
                   6107:   font-weight: bold;
                   6108: }
1.795     www      6109: 
1.424     albertel 6110: table.LC_group_priv_box {
                   6111:   background: white;
                   6112:   border: 1px solid black;
                   6113:   border-spacing: 1px;
                   6114: }
1.795     www      6115: 
1.424     albertel 6116: table.LC_group_priv_box td.LC_pick_box_title {
                   6117:   background: $tabbg;
                   6118:   font-weight: bold;
                   6119:   text-align: right;
                   6120:   width: 184px;
                   6121: }
1.795     www      6122: 
1.424     albertel 6123: table.LC_group_priv_box td.LC_groups_fixed {
                   6124:   background: $data_table_light;
                   6125:   text-align: center;
                   6126: }
1.795     www      6127: 
1.424     albertel 6128: table.LC_group_priv_box td.LC_groups_optional {
                   6129:   background: $data_table_dark;
                   6130:   text-align: center;
                   6131: }
1.795     www      6132: 
1.424     albertel 6133: table.LC_group_priv_box td.LC_groups_functionality {
                   6134:   background: $data_table_darker;
                   6135:   text-align: center;
                   6136:   font-weight: bold;
                   6137: }
1.795     www      6138: 
1.424     albertel 6139: table.LC_group_priv td {
                   6140:   text-align: left;
1.803     bisitz   6141:   padding: 0;
1.424     albertel 6142: }
                   6143: 
                   6144: .LC_navbuttons {
                   6145:   margin: 2ex 0ex 2ex 0ex;
                   6146: }
1.795     www      6147: 
1.423     albertel 6148: .LC_topic_bar {
                   6149:   font-weight: bold;
                   6150:   background: $tabbg;
1.918     wenzelju 6151:   margin: 1em 0em 1em 2em;
1.805     bisitz   6152:   padding: 3px;
1.918     wenzelju 6153:   font-size: 1.2em;
1.423     albertel 6154: }
1.795     www      6155: 
1.423     albertel 6156: .LC_topic_bar span {
1.918     wenzelju 6157:   left: 0.5em;
                   6158:   position: absolute;
1.423     albertel 6159:   vertical-align: middle;
1.918     wenzelju 6160:   font-size: 1.2em;
1.423     albertel 6161: }
1.795     www      6162: 
1.423     albertel 6163: table.LC_course_group_status {
                   6164:   margin: 20px;
                   6165: }
1.795     www      6166: 
1.423     albertel 6167: table.LC_status_selector td {
                   6168:   vertical-align: top;
                   6169:   text-align: center;
1.424     albertel 6170:   padding: 4px;
                   6171: }
1.795     www      6172: 
1.599     albertel 6173: div.LC_feedback_link {
1.616     albertel 6174:   clear: both;
1.829     kalberla 6175:   background: $sidebg;
1.779     bisitz   6176:   width: 100%;
1.829     kalberla 6177:   padding-bottom: 10px;
                   6178:   border: 1px $tabbg solid;
1.833     kalberla 6179:   height: 22px;
                   6180:   line-height: 22px;
                   6181:   padding-top: 5px;
                   6182: }
                   6183: 
                   6184: div.LC_feedback_link img {
                   6185:   height: 22px;
1.867     kalberla 6186:   vertical-align:middle;
1.829     kalberla 6187: }
                   6188: 
1.911     bisitz   6189: div.LC_feedback_link a {
1.829     kalberla 6190:   text-decoration: none;
1.489     raeburn  6191: }
1.795     www      6192: 
1.867     kalberla 6193: div.LC_comblock {
1.911     bisitz   6194:   display:inline;
1.867     kalberla 6195:   color:$font;
                   6196:   font-size:90%;
                   6197: }
                   6198: 
                   6199: div.LC_feedback_link div.LC_comblock {
                   6200:   padding-left:5px;
                   6201: }
                   6202: 
                   6203: div.LC_feedback_link div.LC_comblock a {
                   6204:   color:$font;
                   6205: }
                   6206: 
1.489     raeburn  6207: span.LC_feedback_link {
1.858     bisitz   6208:   /* background: $feedback_link_bg; */
1.599     albertel 6209:   font-size: larger;
                   6210: }
1.795     www      6211: 
1.599     albertel 6212: span.LC_message_link {
1.858     bisitz   6213:   /* background: $feedback_link_bg; */
1.599     albertel 6214:   font-size: larger;
                   6215:   position: absolute;
                   6216:   right: 1em;
1.489     raeburn  6217: }
1.421     albertel 6218: 
1.515     albertel 6219: table.LC_prior_tries {
1.524     albertel 6220:   border: 1px solid #000000;
                   6221:   border-collapse: separate;
                   6222:   border-spacing: 1px;
1.515     albertel 6223: }
1.523     albertel 6224: 
1.515     albertel 6225: table.LC_prior_tries td {
1.524     albertel 6226:   padding: 2px;
1.515     albertel 6227: }
1.523     albertel 6228: 
                   6229: .LC_answer_correct {
1.795     www      6230:   background: lightgreen;
                   6231:   color: darkgreen;
                   6232:   padding: 6px;
1.523     albertel 6233: }
1.795     www      6234: 
1.523     albertel 6235: .LC_answer_charged_try {
1.797     www      6236:   background: #FFAAAA;
1.795     www      6237:   color: darkred;
                   6238:   padding: 6px;
1.523     albertel 6239: }
1.795     www      6240: 
1.779     bisitz   6241: .LC_answer_not_charged_try,
1.523     albertel 6242: .LC_answer_no_grade,
                   6243: .LC_answer_late {
1.795     www      6244:   background: lightyellow;
1.523     albertel 6245:   color: black;
1.795     www      6246:   padding: 6px;
1.523     albertel 6247: }
1.795     www      6248: 
1.523     albertel 6249: .LC_answer_previous {
1.795     www      6250:   background: lightblue;
                   6251:   color: darkblue;
                   6252:   padding: 6px;
1.523     albertel 6253: }
1.795     www      6254: 
1.779     bisitz   6255: .LC_answer_no_message {
1.777     tempelho 6256:   background: #FFFFFF;
                   6257:   color: black;
1.795     www      6258:   padding: 6px;
1.779     bisitz   6259: }
1.795     www      6260: 
1.779     bisitz   6261: .LC_answer_unknown {
                   6262:   background: orange;
                   6263:   color: black;
1.795     www      6264:   padding: 6px;
1.777     tempelho 6265: }
1.795     www      6266: 
1.529     albertel 6267: span.LC_prior_numerical,
                   6268: span.LC_prior_string,
                   6269: span.LC_prior_custom,
                   6270: span.LC_prior_reaction,
                   6271: span.LC_prior_math {
1.925     bisitz   6272:   font-family: $mono;
1.523     albertel 6273:   white-space: pre;
                   6274: }
                   6275: 
1.525     albertel 6276: span.LC_prior_string {
1.925     bisitz   6277:   font-family: $mono;
1.525     albertel 6278:   white-space: pre;
                   6279: }
                   6280: 
1.523     albertel 6281: table.LC_prior_option {
                   6282:   width: 100%;
                   6283:   border-collapse: collapse;
                   6284: }
1.795     www      6285: 
1.911     bisitz   6286: table.LC_prior_rank,
1.795     www      6287: table.LC_prior_match {
1.528     albertel 6288:   border-collapse: collapse;
                   6289: }
1.795     www      6290: 
1.528     albertel 6291: table.LC_prior_option tr td,
                   6292: table.LC_prior_rank tr td,
                   6293: table.LC_prior_match tr td {
1.524     albertel 6294:   border: 1px solid #000000;
1.515     albertel 6295: }
                   6296: 
1.855     bisitz   6297: .LC_nobreak {
1.544     albertel 6298:   white-space: nowrap;
1.519     raeburn  6299: }
                   6300: 
1.576     raeburn  6301: span.LC_cusr_emph {
                   6302:   font-style: italic;
                   6303: }
                   6304: 
1.633     raeburn  6305: span.LC_cusr_subheading {
                   6306:   font-weight: normal;
                   6307:   font-size: 85%;
                   6308: }
                   6309: 
1.861     bisitz   6310: div.LC_docs_entry_move {
1.859     bisitz   6311:   border: 1px solid #BBBBBB;
1.545     albertel 6312:   background: #DDDDDD;
1.861     bisitz   6313:   width: 22px;
1.859     bisitz   6314:   padding: 1px;
                   6315:   margin: 0;
1.545     albertel 6316: }
                   6317: 
1.861     bisitz   6318: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6319: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6320:   font-size: x-small;
                   6321: }
1.795     www      6322: 
1.861     bisitz   6323: .LC_docs_entry_parameter {
                   6324:   white-space: nowrap;
                   6325: }
                   6326: 
1.544     albertel 6327: .LC_docs_copy {
1.545     albertel 6328:   color: #000099;
1.544     albertel 6329: }
1.795     www      6330: 
1.544     albertel 6331: .LC_docs_cut {
1.545     albertel 6332:   color: #550044;
1.544     albertel 6333: }
1.795     www      6334: 
1.544     albertel 6335: .LC_docs_rename {
1.545     albertel 6336:   color: #009900;
1.544     albertel 6337: }
1.795     www      6338: 
1.544     albertel 6339: .LC_docs_remove {
1.545     albertel 6340:   color: #990000;
                   6341: }
                   6342: 
1.547     albertel 6343: .LC_docs_reinit_warn,
                   6344: .LC_docs_ext_edit {
                   6345:   font-size: x-small;
                   6346: }
                   6347: 
1.545     albertel 6348: table.LC_docs_adddocs td,
                   6349: table.LC_docs_adddocs th {
                   6350:   border: 1px solid #BBBBBB;
                   6351:   padding: 4px;
                   6352:   background: #DDDDDD;
1.543     albertel 6353: }
                   6354: 
1.584     albertel 6355: table.LC_sty_begin {
                   6356:   background: #BBFFBB;
                   6357: }
1.795     www      6358: 
1.584     albertel 6359: table.LC_sty_end {
                   6360:   background: #FFBBBB;
                   6361: }
                   6362: 
1.589     raeburn  6363: table.LC_double_column {
1.803     bisitz   6364:   border-width: 0;
1.589     raeburn  6365:   border-collapse: collapse;
                   6366:   width: 100%;
                   6367:   padding: 2px;
                   6368: }
                   6369: 
                   6370: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6371:   top: 2px;
1.589     raeburn  6372:   left: 2px;
                   6373:   width: 47%;
                   6374:   vertical-align: top;
                   6375: }
                   6376: 
                   6377: table.LC_double_column tr td.LC_right_col {
                   6378:   top: 2px;
1.779     bisitz   6379:   right: 2px;
1.589     raeburn  6380:   width: 47%;
                   6381:   vertical-align: top;
                   6382: }
                   6383: 
1.591     raeburn  6384: div.LC_left_float {
                   6385:   float: left;
                   6386:   padding-right: 5%;
1.597     albertel 6387:   padding-bottom: 4px;
1.591     raeburn  6388: }
                   6389: 
                   6390: div.LC_clear_float_header {
1.597     albertel 6391:   padding-bottom: 2px;
1.591     raeburn  6392: }
                   6393: 
                   6394: div.LC_clear_float_footer {
1.597     albertel 6395:   padding-top: 10px;
1.591     raeburn  6396:   clear: both;
                   6397: }
                   6398: 
1.597     albertel 6399: div.LC_grade_show_user {
1.941     bisitz   6400: /*  border-left: 5px solid $sidebg; */
                   6401:   border-top: 5px solid #000000;
                   6402:   margin: 50px 0 0 0;
1.936     bisitz   6403:   padding: 15px 0 5px 10px;
1.597     albertel 6404: }
1.795     www      6405: 
1.936     bisitz   6406: div.LC_grade_show_user_odd_row {
1.941     bisitz   6407: /*  border-left: 5px solid #000000; */
                   6408: }
                   6409: 
                   6410: div.LC_grade_show_user div.LC_Box {
                   6411:   margin-right: 50px;
1.597     albertel 6412: }
                   6413: 
                   6414: div.LC_grade_submissions,
                   6415: div.LC_grade_message_center,
1.936     bisitz   6416: div.LC_grade_info_links {
1.597     albertel 6417:   margin: 5px;
                   6418:   width: 99%;
                   6419:   background: #FFFFFF;
                   6420: }
1.795     www      6421: 
1.597     albertel 6422: div.LC_grade_submissions_header,
1.936     bisitz   6423: div.LC_grade_message_center_header {
1.705     tempelho 6424:   font-weight: bold;
                   6425:   font-size: large;
1.597     albertel 6426: }
1.795     www      6427: 
1.597     albertel 6428: div.LC_grade_submissions_body,
1.936     bisitz   6429: div.LC_grade_message_center_body {
1.597     albertel 6430:   border: 1px solid black;
                   6431:   width: 99%;
                   6432:   background: #FFFFFF;
                   6433: }
1.795     www      6434: 
1.613     albertel 6435: table.LC_scantron_action {
                   6436:   width: 100%;
                   6437: }
1.795     www      6438: 
1.613     albertel 6439: table.LC_scantron_action tr th {
1.698     harmsja  6440:   font-weight:bold;
                   6441:   font-style:normal;
1.613     albertel 6442: }
1.795     www      6443: 
1.779     bisitz   6444: .LC_edit_problem_header,
1.614     albertel 6445: div.LC_edit_problem_footer {
1.705     tempelho 6446:   font-weight: normal;
                   6447:   font-size:  medium;
1.602     albertel 6448:   margin: 2px;
1.1060    bisitz   6449:   background-color: $sidebg;
1.600     albertel 6450: }
1.795     www      6451: 
1.600     albertel 6452: div.LC_edit_problem_header,
1.602     albertel 6453: div.LC_edit_problem_header div,
1.614     albertel 6454: div.LC_edit_problem_footer,
                   6455: div.LC_edit_problem_footer div,
1.602     albertel 6456: div.LC_edit_problem_editxml_header,
                   6457: div.LC_edit_problem_editxml_header div {
1.600     albertel 6458:   margin-top: 5px;
                   6459: }
1.795     www      6460: 
1.600     albertel 6461: div.LC_edit_problem_header_title {
1.705     tempelho 6462:   font-weight: bold;
                   6463:   font-size: larger;
1.602     albertel 6464:   background: $tabbg;
                   6465:   padding: 3px;
1.1060    bisitz   6466:   margin: 0 0 5px 0;
1.602     albertel 6467: }
1.795     www      6468: 
1.602     albertel 6469: table.LC_edit_problem_header_title {
                   6470:   width: 100%;
1.600     albertel 6471:   background: $tabbg;
1.602     albertel 6472: }
                   6473: 
                   6474: div.LC_edit_problem_discards {
                   6475:   float: left;
                   6476:   padding-bottom: 5px;
                   6477: }
1.795     www      6478: 
1.602     albertel 6479: div.LC_edit_problem_saves {
                   6480:   float: right;
                   6481:   padding-bottom: 5px;
1.600     albertel 6482: }
1.795     www      6483: 
1.1124    bisitz   6484: .LC_edit_opt {
                   6485:   padding-left: 1em;
                   6486:   white-space: nowrap;
                   6487: }
                   6488: 
1.911     bisitz   6489: img.stift {
1.803     bisitz   6490:   border-width: 0;
                   6491:   vertical-align: middle;
1.677     riegler  6492: }
1.680     riegler  6493: 
1.923     bisitz   6494: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6495:   vertical-align: top;
1.777     tempelho 6496: }
1.795     www      6497: 
1.716     raeburn  6498: div.LC_createcourse {
1.911     bisitz   6499:   margin: 10px 10px 10px 10px;
1.716     raeburn  6500: }
                   6501: 
1.917     raeburn  6502: .LC_dccid {
1.1130    raeburn  6503:   float: right;
1.917     raeburn  6504:   margin: 0.2em 0 0 0;
                   6505:   padding: 0;
                   6506:   font-size: 90%;
                   6507:   display:none;
                   6508: }
                   6509: 
1.897     wenzelju 6510: ol.LC_primary_menu a:hover,
1.721     harmsja  6511: ol#LC_MenuBreadcrumbs a:hover,
                   6512: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6513: ul#LC_secondary_menu a:hover,
1.721     harmsja  6514: .LC_FormSectionClearButton input:hover
1.795     www      6515: ul.LC_TabContent   li:hover a {
1.952     onken    6516:   color:$button_hover;
1.911     bisitz   6517:   text-decoration:none;
1.693     droeschl 6518: }
                   6519: 
1.779     bisitz   6520: h1 {
1.911     bisitz   6521:   padding: 0;
                   6522:   line-height:130%;
1.693     droeschl 6523: }
1.698     harmsja  6524: 
1.911     bisitz   6525: h2,
                   6526: h3,
                   6527: h4,
                   6528: h5,
                   6529: h6 {
                   6530:   margin: 5px 0 5px 0;
                   6531:   padding: 0;
                   6532:   line-height:130%;
1.693     droeschl 6533: }
1.795     www      6534: 
                   6535: .LC_hcell {
1.911     bisitz   6536:   padding:3px 15px 3px 15px;
                   6537:   margin: 0;
                   6538:   background-color:$tabbg;
                   6539:   color:$fontmenu;
                   6540:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6541: }
1.795     www      6542: 
1.840     bisitz   6543: .LC_Box > .LC_hcell {
1.911     bisitz   6544:   margin: 0 -10px 10px -10px;
1.835     bisitz   6545: }
                   6546: 
1.721     harmsja  6547: .LC_noBorder {
1.911     bisitz   6548:   border: 0;
1.698     harmsja  6549: }
1.693     droeschl 6550: 
1.721     harmsja  6551: .LC_FormSectionClearButton input {
1.911     bisitz   6552:   background-color:transparent;
                   6553:   border: none;
                   6554:   cursor:pointer;
                   6555:   text-decoration:underline;
1.693     droeschl 6556: }
1.763     bisitz   6557: 
                   6558: .LC_help_open_topic {
1.911     bisitz   6559:   color: #FFFFFF;
                   6560:   background-color: #EEEEFF;
                   6561:   margin: 1px;
                   6562:   padding: 4px;
                   6563:   border: 1px solid #000033;
                   6564:   white-space: nowrap;
                   6565:   /* vertical-align: middle; */
1.759     neumanie 6566: }
1.693     droeschl 6567: 
1.911     bisitz   6568: dl,
                   6569: ul,
                   6570: div,
                   6571: fieldset {
                   6572:   margin: 10px 10px 10px 0;
                   6573:   /* overflow: hidden; */
1.693     droeschl 6574: }
1.795     www      6575: 
1.838     bisitz   6576: fieldset > legend {
1.911     bisitz   6577:   font-weight: bold;
                   6578:   padding: 0 5px 0 5px;
1.838     bisitz   6579: }
                   6580: 
1.813     bisitz   6581: #LC_nav_bar {
1.911     bisitz   6582:   float: left;
1.995     raeburn  6583:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6584:   margin: 0 0 2px 0;
1.807     droeschl 6585: }
                   6586: 
1.916     droeschl 6587: #LC_realm {
                   6588:   margin: 0.2em 0 0 0;
                   6589:   padding: 0;
                   6590:   font-weight: bold;
                   6591:   text-align: center;
1.995     raeburn  6592:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6593: }
                   6594: 
1.911     bisitz   6595: #LC_nav_bar em {
                   6596:   font-weight: bold;
                   6597:   font-style: normal;
1.807     droeschl 6598: }
                   6599: 
1.897     wenzelju 6600: ol.LC_primary_menu {
1.934     droeschl 6601:   margin: 0;
1.1076    raeburn  6602:   padding: 0;
1.995     raeburn  6603:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6604: }
                   6605: 
1.852     droeschl 6606: ol#LC_PathBreadcrumbs {
1.911     bisitz   6607:   margin: 0;
1.693     droeschl 6608: }
                   6609: 
1.897     wenzelju 6610: ol.LC_primary_menu li {
1.1076    raeburn  6611:   color: RGB(80, 80, 80);
                   6612:   vertical-align: middle;
                   6613:   text-align: left;
                   6614:   list-style: none;
                   6615:   float: left;
                   6616: }
                   6617: 
                   6618: ol.LC_primary_menu li a {
                   6619:   display: block;
                   6620:   margin: 0;
                   6621:   padding: 0 5px 0 10px;
                   6622:   text-decoration: none;
                   6623: }
                   6624: 
                   6625: ol.LC_primary_menu li ul {
                   6626:   display: none;
                   6627:   width: 10em;
                   6628:   background-color: $data_table_light;
                   6629: }
                   6630: 
                   6631: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6632:   display: block;
                   6633:   position: absolute;
                   6634:   margin: 0;
                   6635:   padding: 0;
1.1078    raeburn  6636:   z-index: 2;
1.1076    raeburn  6637: }
                   6638: 
                   6639: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6640:   font-size: 90%;
1.911     bisitz   6641:   vertical-align: top;
1.1076    raeburn  6642:   float: none;
1.1079    raeburn  6643:   border-left: 1px solid black;
                   6644:   border-right: 1px solid black;
1.1076    raeburn  6645: }
                   6646: 
                   6647: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1078    raeburn  6648:   background-color:$data_table_light;
1.1076    raeburn  6649: }
                   6650: 
                   6651: ol.LC_primary_menu li li a:hover {
                   6652:    color:$button_hover;
                   6653:    background-color:$data_table_dark;
1.693     droeschl 6654: }
                   6655: 
1.897     wenzelju 6656: ol.LC_primary_menu li img {
1.911     bisitz   6657:   vertical-align: bottom;
1.934     droeschl 6658:   height: 1.1em;
1.1077    raeburn  6659:   margin: 0.2em 0 0 0;
1.693     droeschl 6660: }
                   6661: 
1.897     wenzelju 6662: ol.LC_primary_menu a {
1.911     bisitz   6663:   color: RGB(80, 80, 80);
                   6664:   text-decoration: none;
1.693     droeschl 6665: }
1.795     www      6666: 
1.949     droeschl 6667: ol.LC_primary_menu a.LC_new_message {
                   6668:   font-weight:bold;
                   6669:   color: darkred;
                   6670: }
                   6671: 
1.975     raeburn  6672: ol.LC_docs_parameters {
                   6673:   margin-left: 0;
                   6674:   padding: 0;
                   6675:   list-style: none;
                   6676: }
                   6677: 
                   6678: ol.LC_docs_parameters li {
                   6679:   margin: 0;
                   6680:   padding-right: 20px;
                   6681:   display: inline;
                   6682: }
                   6683: 
1.976     raeburn  6684: ol.LC_docs_parameters li:before {
                   6685:   content: "\\002022 \\0020";
                   6686: }
                   6687: 
                   6688: li.LC_docs_parameters_title {
                   6689:   font-weight: bold;
                   6690: }
                   6691: 
                   6692: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6693:   content: "";
                   6694: }
                   6695: 
1.897     wenzelju 6696: ul#LC_secondary_menu {
1.1107    raeburn  6697:   clear: right;
1.911     bisitz   6698:   color: $fontmenu;
                   6699:   background: $tabbg;
                   6700:   list-style: none;
                   6701:   padding: 0;
                   6702:   margin: 0;
                   6703:   width: 100%;
1.995     raeburn  6704:   text-align: left;
1.1107    raeburn  6705:   float: left;
1.808     droeschl 6706: }
                   6707: 
1.897     wenzelju 6708: ul#LC_secondary_menu li {
1.911     bisitz   6709:   font-weight: bold;
                   6710:   line-height: 1.8em;
1.1107    raeburn  6711:   border-right: 1px solid black;
                   6712:   float: left;
                   6713: }
                   6714: 
                   6715: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6716:   background-color: $data_table_light;
                   6717: }
                   6718: 
                   6719: ul#LC_secondary_menu li a {
1.911     bisitz   6720:   padding: 0 0.8em;
1.1107    raeburn  6721: }
                   6722: 
                   6723: ul#LC_secondary_menu li ul {
                   6724:   display: none;
                   6725: }
                   6726: 
                   6727: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6728:   display: block;
                   6729:   position: absolute;
                   6730:   margin: 0;
                   6731:   padding: 0;
                   6732:   list-style:none;
                   6733:   float: none;
                   6734:   background-color: $data_table_light;
                   6735:   z-index: 2;
                   6736:   margin-left: -1px;
                   6737: }
                   6738: 
                   6739: ul#LC_secondary_menu li ul li {
                   6740:   font-size: 90%;
                   6741:   vertical-align: top;
                   6742:   border-left: 1px solid black;
1.911     bisitz   6743:   border-right: 1px solid black;
1.1119    raeburn  6744:   background-color: $data_table_light;
1.1107    raeburn  6745:   list-style:none;
                   6746:   float: none;
                   6747: }
                   6748: 
                   6749: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6750:   background-color: $data_table_dark;
1.807     droeschl 6751: }
                   6752: 
1.847     tempelho 6753: ul.LC_TabContent {
1.911     bisitz   6754:   display:block;
                   6755:   background: $sidebg;
                   6756:   border-bottom: solid 1px $lg_border_color;
                   6757:   list-style:none;
1.1020    raeburn  6758:   margin: -1px -10px 0 -10px;
1.911     bisitz   6759:   padding: 0;
1.693     droeschl 6760: }
                   6761: 
1.795     www      6762: ul.LC_TabContent li,
                   6763: ul.LC_TabContentBigger li {
1.911     bisitz   6764:   float:left;
1.741     harmsja  6765: }
1.795     www      6766: 
1.897     wenzelju 6767: ul#LC_secondary_menu li a {
1.911     bisitz   6768:   color: $fontmenu;
                   6769:   text-decoration: none;
1.693     droeschl 6770: }
1.795     www      6771: 
1.721     harmsja  6772: ul.LC_TabContent {
1.952     onken    6773:   min-height:20px;
1.721     harmsja  6774: }
1.795     www      6775: 
                   6776: ul.LC_TabContent li {
1.911     bisitz   6777:   vertical-align:middle;
1.959     onken    6778:   padding: 0 16px 0 10px;
1.911     bisitz   6779:   background-color:$tabbg;
                   6780:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6781:   border-left: solid 1px $font;
1.721     harmsja  6782: }
1.795     www      6783: 
1.847     tempelho 6784: ul.LC_TabContent .right {
1.911     bisitz   6785:   float:right;
1.847     tempelho 6786: }
                   6787: 
1.911     bisitz   6788: ul.LC_TabContent li a,
                   6789: ul.LC_TabContent li {
                   6790:   color:rgb(47,47,47);
                   6791:   text-decoration:none;
                   6792:   font-size:95%;
                   6793:   font-weight:bold;
1.952     onken    6794:   min-height:20px;
                   6795: }
                   6796: 
1.959     onken    6797: ul.LC_TabContent li a:hover,
                   6798: ul.LC_TabContent li a:focus {
1.952     onken    6799:   color: $button_hover;
1.959     onken    6800:   background:none;
                   6801:   outline:none;
1.952     onken    6802: }
                   6803: 
                   6804: ul.LC_TabContent li:hover {
                   6805:   color: $button_hover;
                   6806:   cursor:pointer;
1.721     harmsja  6807: }
1.795     www      6808: 
1.911     bisitz   6809: ul.LC_TabContent li.active {
1.952     onken    6810:   color: $font;
1.911     bisitz   6811:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6812:   border-bottom:solid 1px #FFFFFF;
                   6813:   cursor: default;
1.744     ehlerst  6814: }
1.795     www      6815: 
1.959     onken    6816: ul.LC_TabContent li.active a {
                   6817:   color:$font;
                   6818:   background:#FFFFFF;
                   6819:   outline: none;
                   6820: }
1.1047    raeburn  6821: 
                   6822: ul.LC_TabContent li.goback {
                   6823:   float: left;
                   6824:   border-left: none;
                   6825: }
                   6826: 
1.870     tempelho 6827: #maincoursedoc {
1.911     bisitz   6828:   clear:both;
1.870     tempelho 6829: }
                   6830: 
                   6831: ul.LC_TabContentBigger {
1.911     bisitz   6832:   display:block;
                   6833:   list-style:none;
                   6834:   padding: 0;
1.870     tempelho 6835: }
                   6836: 
1.795     www      6837: ul.LC_TabContentBigger li {
1.911     bisitz   6838:   vertical-align:bottom;
                   6839:   height: 30px;
                   6840:   font-size:110%;
                   6841:   font-weight:bold;
                   6842:   color: #737373;
1.841     tempelho 6843: }
                   6844: 
1.957     onken    6845: ul.LC_TabContentBigger li.active {
                   6846:   position: relative;
                   6847:   top: 1px;
                   6848: }
                   6849: 
1.870     tempelho 6850: ul.LC_TabContentBigger li a {
1.911     bisitz   6851:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6852:   height: 30px;
                   6853:   line-height: 30px;
                   6854:   text-align: center;
                   6855:   display: block;
                   6856:   text-decoration: none;
1.958     onken    6857:   outline: none;  
1.741     harmsja  6858: }
1.795     www      6859: 
1.870     tempelho 6860: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6861:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6862:   color:$font;
1.744     ehlerst  6863: }
1.795     www      6864: 
1.870     tempelho 6865: ul.LC_TabContentBigger li b {
1.911     bisitz   6866:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6867:   display: block;
                   6868:   float: left;
                   6869:   padding: 0 30px;
1.957     onken    6870:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6871: }
                   6872: 
1.956     onken    6873: ul.LC_TabContentBigger li:hover b {
                   6874:   color:$button_hover;
                   6875: }
                   6876: 
1.870     tempelho 6877: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6878:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6879:   color:$font;
1.957     onken    6880:   border: 0;
1.741     harmsja  6881: }
1.693     droeschl 6882: 
1.870     tempelho 6883: 
1.862     bisitz   6884: ul.LC_CourseBreadcrumbs {
                   6885:   background: $sidebg;
1.1020    raeburn  6886:   height: 2em;
1.862     bisitz   6887:   padding-left: 10px;
1.1020    raeburn  6888:   margin: 0;
1.862     bisitz   6889:   list-style-position: inside;
                   6890: }
                   6891: 
1.911     bisitz   6892: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6893: ol#LC_PathBreadcrumbs {
1.911     bisitz   6894:   padding-left: 10px;
                   6895:   margin: 0;
1.933     droeschl 6896:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6897: }
                   6898: 
1.911     bisitz   6899: ol#LC_MenuBreadcrumbs li,
                   6900: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6901: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6902:   display: inline;
1.933     droeschl 6903:   white-space: normal;  
1.693     droeschl 6904: }
                   6905: 
1.823     bisitz   6906: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6907: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6908:   text-decoration: none;
                   6909:   font-size:90%;
1.693     droeschl 6910: }
1.795     www      6911: 
1.969     droeschl 6912: ol#LC_MenuBreadcrumbs h1 {
                   6913:   display: inline;
                   6914:   font-size: 90%;
                   6915:   line-height: 2.5em;
                   6916:   margin: 0;
                   6917:   padding: 0;
                   6918: }
                   6919: 
1.795     www      6920: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6921:   text-decoration:none;
                   6922:   font-size:100%;
                   6923:   font-weight:bold;
1.693     droeschl 6924: }
1.795     www      6925: 
1.840     bisitz   6926: .LC_Box {
1.911     bisitz   6927:   border: solid 1px $lg_border_color;
                   6928:   padding: 0 10px 10px 10px;
1.746     neumanie 6929: }
1.795     www      6930: 
1.1020    raeburn  6931: .LC_DocsBox {
                   6932:   border: solid 1px $lg_border_color;
                   6933:   padding: 0 0 10px 10px;
                   6934: }
                   6935: 
1.795     www      6936: .LC_AboutMe_Image {
1.911     bisitz   6937:   float:left;
                   6938:   margin-right:10px;
1.747     neumanie 6939: }
1.795     www      6940: 
                   6941: .LC_Clear_AboutMe_Image {
1.911     bisitz   6942:   clear:left;
1.747     neumanie 6943: }
1.795     www      6944: 
1.721     harmsja  6945: dl.LC_ListStyleClean dt {
1.911     bisitz   6946:   padding-right: 5px;
                   6947:   display: table-header-group;
1.693     droeschl 6948: }
                   6949: 
1.721     harmsja  6950: dl.LC_ListStyleClean dd {
1.911     bisitz   6951:   display: table-row;
1.693     droeschl 6952: }
                   6953: 
1.721     harmsja  6954: .LC_ListStyleClean,
                   6955: .LC_ListStyleSimple,
                   6956: .LC_ListStyleNormal,
1.795     www      6957: .LC_ListStyleSpecial {
1.911     bisitz   6958:   /* display:block; */
                   6959:   list-style-position: inside;
                   6960:   list-style-type: none;
                   6961:   overflow: hidden;
                   6962:   padding: 0;
1.693     droeschl 6963: }
                   6964: 
1.721     harmsja  6965: .LC_ListStyleSimple li,
                   6966: .LC_ListStyleSimple dd,
                   6967: .LC_ListStyleNormal li,
                   6968: .LC_ListStyleNormal dd,
                   6969: .LC_ListStyleSpecial li,
1.795     www      6970: .LC_ListStyleSpecial dd {
1.911     bisitz   6971:   margin: 0;
                   6972:   padding: 5px 5px 5px 10px;
                   6973:   clear: both;
1.693     droeschl 6974: }
                   6975: 
1.721     harmsja  6976: .LC_ListStyleClean li,
                   6977: .LC_ListStyleClean dd {
1.911     bisitz   6978:   padding-top: 0;
                   6979:   padding-bottom: 0;
1.693     droeschl 6980: }
                   6981: 
1.721     harmsja  6982: .LC_ListStyleSimple dd,
1.795     www      6983: .LC_ListStyleSimple li {
1.911     bisitz   6984:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6985: }
                   6986: 
1.721     harmsja  6987: .LC_ListStyleSpecial li,
                   6988: .LC_ListStyleSpecial dd {
1.911     bisitz   6989:   list-style-type: none;
                   6990:   background-color: RGB(220, 220, 220);
                   6991:   margin-bottom: 4px;
1.693     droeschl 6992: }
                   6993: 
1.721     harmsja  6994: table.LC_SimpleTable {
1.911     bisitz   6995:   margin:5px;
                   6996:   border:solid 1px $lg_border_color;
1.795     www      6997: }
1.693     droeschl 6998: 
1.721     harmsja  6999: table.LC_SimpleTable tr {
1.911     bisitz   7000:   padding: 0;
                   7001:   border:solid 1px $lg_border_color;
1.693     droeschl 7002: }
1.795     www      7003: 
                   7004: table.LC_SimpleTable thead {
1.911     bisitz   7005:   background:rgb(220,220,220);
1.693     droeschl 7006: }
                   7007: 
1.721     harmsja  7008: div.LC_columnSection {
1.911     bisitz   7009:   display: block;
                   7010:   clear: both;
                   7011:   overflow: hidden;
                   7012:   margin: 0;
1.693     droeschl 7013: }
                   7014: 
1.721     harmsja  7015: div.LC_columnSection>* {
1.911     bisitz   7016:   float: left;
                   7017:   margin: 10px 20px 10px 0;
                   7018:   overflow:hidden;
1.693     droeschl 7019: }
1.721     harmsja  7020: 
1.795     www      7021: table em {
1.911     bisitz   7022:   font-weight: bold;
                   7023:   font-style: normal;
1.748     schulted 7024: }
1.795     www      7025: 
1.779     bisitz   7026: table.LC_tableBrowseRes,
1.795     www      7027: table.LC_tableOfContent {
1.911     bisitz   7028:   border:none;
                   7029:   border-spacing: 1px;
                   7030:   padding: 3px;
                   7031:   background-color: #FFFFFF;
                   7032:   font-size: 90%;
1.753     droeschl 7033: }
1.789     droeschl 7034: 
1.911     bisitz   7035: table.LC_tableOfContent {
                   7036:   border-collapse: collapse;
1.789     droeschl 7037: }
                   7038: 
1.771     droeschl 7039: table.LC_tableBrowseRes a,
1.768     schulted 7040: table.LC_tableOfContent a {
1.911     bisitz   7041:   background-color: transparent;
                   7042:   text-decoration: none;
1.753     droeschl 7043: }
                   7044: 
1.795     www      7045: table.LC_tableOfContent img {
1.911     bisitz   7046:   border: none;
                   7047:   height: 1.3em;
                   7048:   vertical-align: text-bottom;
                   7049:   margin-right: 0.3em;
1.753     droeschl 7050: }
1.757     schulted 7051: 
1.795     www      7052: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7053:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7054: }
                   7055: 
1.795     www      7056: a#LC_content_toolbar_everything {
1.911     bisitz   7057:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7058: }
                   7059: 
1.795     www      7060: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7061:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7062: }
                   7063: 
1.795     www      7064: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7065:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7066: }
                   7067: 
1.795     www      7068: a#LC_content_toolbar_changefolder {
1.911     bisitz   7069:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7070: }
                   7071: 
1.795     www      7072: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7073:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7074: }
                   7075: 
1.1043    raeburn  7076: a#LC_content_toolbar_edittoplevel {
                   7077:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7078: }
                   7079: 
1.795     www      7080: ul#LC_toolbar li a:hover {
1.911     bisitz   7081:   background-position: bottom center;
1.757     schulted 7082: }
                   7083: 
1.795     www      7084: ul#LC_toolbar {
1.911     bisitz   7085:   padding: 0;
                   7086:   margin: 2px;
                   7087:   list-style:none;
                   7088:   position:relative;
                   7089:   background-color:white;
1.1082    raeburn  7090:   overflow: auto;
1.757     schulted 7091: }
                   7092: 
1.795     www      7093: ul#LC_toolbar li {
1.911     bisitz   7094:   border:1px solid white;
                   7095:   padding: 0;
                   7096:   margin: 0;
                   7097:   float: left;
                   7098:   display:inline;
                   7099:   vertical-align:middle;
1.1082    raeburn  7100:   white-space: nowrap;
1.911     bisitz   7101: }
1.757     schulted 7102: 
1.783     amueller 7103: 
1.795     www      7104: a.LC_toolbarItem {
1.911     bisitz   7105:   display:block;
                   7106:   padding: 0;
                   7107:   margin: 0;
                   7108:   height: 32px;
                   7109:   width: 32px;
                   7110:   color:white;
                   7111:   border: none;
                   7112:   background-repeat:no-repeat;
                   7113:   background-color:transparent;
1.757     schulted 7114: }
                   7115: 
1.915     droeschl 7116: ul.LC_funclist {
                   7117:     margin: 0;
                   7118:     padding: 0.5em 1em 0.5em 0;
                   7119: }
                   7120: 
1.933     droeschl 7121: ul.LC_funclist > li:first-child {
                   7122:     font-weight:bold; 
                   7123:     margin-left:0.8em;
                   7124: }
                   7125: 
1.915     droeschl 7126: ul.LC_funclist + ul.LC_funclist {
                   7127:     /* 
                   7128:        left border as a seperator if we have more than
                   7129:        one list 
                   7130:     */
                   7131:     border-left: 1px solid $sidebg;
                   7132:     /* 
                   7133:        this hides the left border behind the border of the 
                   7134:        outer box if element is wrapped to the next 'line' 
                   7135:     */
                   7136:     margin-left: -1px;
                   7137: }
                   7138: 
1.843     bisitz   7139: ul.LC_funclist li {
1.915     droeschl 7140:   display: inline;
1.782     bisitz   7141:   white-space: nowrap;
1.915     droeschl 7142:   margin: 0 0 0 25px;
                   7143:   line-height: 150%;
1.782     bisitz   7144: }
                   7145: 
1.974     wenzelju 7146: .LC_hidden {
                   7147:   display: none;
                   7148: }
                   7149: 
1.1030    www      7150: .LCmodal-overlay {
                   7151: 		position:fixed;
                   7152: 		top:0;
                   7153: 		right:0;
                   7154: 		bottom:0;
                   7155: 		left:0;
                   7156: 		height:100%;
                   7157: 		width:100%;
                   7158: 		margin:0;
                   7159: 		padding:0;
                   7160: 		background:#999;
                   7161: 		opacity:.75;
                   7162: 		filter: alpha(opacity=75);
                   7163: 		-moz-opacity: 0.75;
                   7164: 		z-index:101;
                   7165: }
                   7166: 
                   7167: * html .LCmodal-overlay {   
                   7168: 		position: absolute;
                   7169: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7170: }
                   7171: 
                   7172: .LCmodal-window {
                   7173: 		position:fixed;
                   7174: 		top:50%;
                   7175: 		left:50%;
                   7176: 		margin:0;
                   7177: 		padding:0;
                   7178: 		z-index:102;
                   7179: 	}
                   7180: 
                   7181: * html .LCmodal-window {
                   7182: 		position:absolute;
                   7183: }
                   7184: 
                   7185: .LCclose-window {
                   7186: 		position:absolute;
                   7187: 		width:32px;
                   7188: 		height:32px;
                   7189: 		right:8px;
                   7190: 		top:8px;
                   7191: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7192: 		text-indent:-99999px;
                   7193: 		overflow:hidden;
                   7194: 		cursor:pointer;
                   7195: }
                   7196: 
1.1100    raeburn  7197: /*
                   7198:   styles used by TTH when "Default set of options to pass to tth/m
                   7199:   when converting TeX" in course settings has been set
                   7200: 
                   7201:   option passed: -t
                   7202: 
                   7203: */
                   7204: 
                   7205: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7206: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7207: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7208: td div.norm {line-height:normal;}
                   7209: 
                   7210: /*
                   7211:   option passed -y3
                   7212: */
                   7213: 
                   7214: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7215: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7216: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7217: 
1.343     albertel 7218: END
                   7219: }
                   7220: 
1.306     albertel 7221: =pod
                   7222: 
                   7223: =item * &headtag()
                   7224: 
                   7225: Returns a uniform footer for LON-CAPA web pages.
                   7226: 
1.307     albertel 7227: Inputs: $title - optional title for the head
                   7228:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7229:         $args - optional arguments
1.319     albertel 7230:             force_register - if is true call registerurl so the remote is 
                   7231:                              informed
1.415     albertel 7232:             redirect       -> array ref of
                   7233:                                    1- seconds before redirect occurs
                   7234:                                    2- url to redirect to
                   7235:                                    3- whether the side effect should occur
1.315     albertel 7236:                            (side effect of setting 
                   7237:                                $env{'internal.head.redirect'} to the url 
                   7238:                                redirected too)
1.352     albertel 7239:             domain         -> force to color decorate a page for a specific
                   7240:                                domain
                   7241:             function       -> force usage of a specific rolish color scheme
                   7242:             bgcolor        -> override the default page bgcolor
1.460     albertel 7243:             no_auto_mt_title
                   7244:                            -> prevent &mt()ing the title arg
1.464     albertel 7245: 
1.306     albertel 7246: =cut
                   7247: 
                   7248: sub headtag {
1.313     albertel 7249:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7250:     
1.363     albertel 7251:     my $function = $args->{'function'} || &get_users_function();
                   7252:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7253:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 7254:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7255: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7256: 		   #time(),
1.418     albertel 7257: 		   $env{'environment.color.timestamp'},
1.363     albertel 7258: 		   $function,$domain,$bgcolor);
                   7259: 
1.369     www      7260:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7261: 
1.308     albertel 7262:     my $result =
                   7263: 	'<head>'.
1.461     albertel 7264: 	&font_settings();
1.319     albertel 7265: 
1.1064    raeburn  7266:     my $inhibitprint = &print_suppression();
                   7267: 
1.461     albertel 7268:     if (!$args->{'frameset'}) {
                   7269: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7270:     }
1.962     droeschl 7271:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7272:         $result .= Apache::lonxml::display_title();
1.319     albertel 7273:     }
1.436     albertel 7274:     if (!$args->{'no_nav_bar'} 
                   7275: 	&& !$args->{'only_body'}
                   7276: 	&& !$args->{'frameset'}) {
                   7277: 	$result .= &help_menu_js();
1.1032    www      7278:         $result.=&modal_window();
1.1038    www      7279:         $result.=&togglebox_script();
1.1034    www      7280:         $result.=&wishlist_window();
1.1041    www      7281:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7282:     } else {
                   7283:         if ($args->{'add_modal'}) {
                   7284:            $result.=&modal_window();
                   7285:         }
                   7286:         if ($args->{'add_wishlist'}) {
                   7287:            $result.=&wishlist_window();
                   7288:         }
1.1038    www      7289:         if ($args->{'add_togglebox'}) {
                   7290:            $result.=&togglebox_script();
                   7291:         }
1.1041    www      7292:         if ($args->{'add_progressbar'}) {
                   7293:            $result.=&LCprogressbarUpdate_script();
                   7294:         }
1.436     albertel 7295:     }
1.314     albertel 7296:     if (ref($args->{'redirect'})) {
1.414     albertel 7297: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7298: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7299: 	if (!$inhibit_continue) {
                   7300: 	    $env{'internal.head.redirect'} = $url;
                   7301: 	}
1.313     albertel 7302: 	$result.=<<ADDMETA
                   7303: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7304: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7305: ADDMETA
                   7306:     }
1.306     albertel 7307:     if (!defined($title)) {
                   7308: 	$title = 'The LearningOnline Network with CAPA';
                   7309:     }
1.460     albertel 7310:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7311:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7312: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7313:         .$inhibitprint
1.414     albertel 7314: 	.$head_extra;
1.962     droeschl 7315:     return $result.'</head>';
1.306     albertel 7316: }
                   7317: 
                   7318: =pod
                   7319: 
1.340     albertel 7320: =item * &font_settings()
                   7321: 
                   7322: Returns neccessary <meta> to set the proper encoding
                   7323: 
                   7324: Inputs: none
                   7325: 
                   7326: =cut
                   7327: 
                   7328: sub font_settings {
                   7329:     my $headerstring='';
1.647     www      7330:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 7331: 	$headerstring.=
                   7332: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   7333:     }
                   7334:     return $headerstring;
                   7335: }
                   7336: 
1.341     albertel 7337: =pod
                   7338: 
1.1064    raeburn  7339: =item * &print_suppression()
                   7340: 
                   7341: In course context returns css which causes the body to be blank when media="print",
                   7342: if printout generation is unavailable for the current resource.
                   7343: 
                   7344: This could be because:
                   7345: 
                   7346: (a) printstartdate is in the future
                   7347: 
                   7348: (b) printenddate is in the past
                   7349: 
                   7350: (c) there is an active exam block with "printout"
                   7351: functionality blocked
                   7352: 
                   7353: Users with pav, pfo or evb privileges are exempt.
                   7354: 
                   7355: Inputs: none
                   7356: 
                   7357: =cut
                   7358: 
                   7359: 
                   7360: sub print_suppression {
                   7361:     my $noprint;
                   7362:     if ($env{'request.course.id'}) {
                   7363:         my $scope = $env{'request.course.id'};
                   7364:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7365:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7366:             return;
                   7367:         }
                   7368:         if ($env{'request.course.sec'} ne '') {
                   7369:             $scope .= "/$env{'request.course.sec'}";
                   7370:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7371:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7372:                 return;
1.1064    raeburn  7373:             }
                   7374:         }
                   7375:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7376:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7377:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7378:         if ($blocked) {
                   7379:             my $checkrole = "cm./$cdom/$cnum";
                   7380:             if ($env{'request.course.sec'} ne '') {
                   7381:                 $checkrole .= "/$env{'request.course.sec'}";
                   7382:             }
                   7383:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7384:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7385:                 $noprint = 1;
                   7386:             }
                   7387:         }
                   7388:         unless ($noprint) {
                   7389:             my $symb = &Apache::lonnet::symbread();
                   7390:             if ($symb ne '') {
                   7391:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7392:                 if (ref($navmap)) {
                   7393:                     my $res = $navmap->getBySymb($symb);
                   7394:                     if (ref($res)) {
                   7395:                         if (!$res->resprintable()) {
                   7396:                             $noprint = 1;
                   7397:                         }
                   7398:                     }
                   7399:                 }
                   7400:             }
                   7401:         }
                   7402:         if ($noprint) {
                   7403:             return <<"ENDSTYLE";
                   7404: <style type="text/css" media="print">
                   7405:     body { display:none }
                   7406: </style>
                   7407: ENDSTYLE
                   7408:         }
                   7409:     }
                   7410:     return;
                   7411: }
                   7412: 
                   7413: =pod
                   7414: 
1.341     albertel 7415: =item * &xml_begin()
                   7416: 
                   7417: Returns the needed doctype and <html>
                   7418: 
                   7419: Inputs: none
                   7420: 
                   7421: =cut
                   7422: 
                   7423: sub xml_begin {
                   7424:     my $output='';
                   7425: 
                   7426:     if ($env{'browser.mathml'}) {
                   7427: 	$output='<?xml version="1.0"?>'
                   7428:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7429: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7430:             
                   7431: #	    .'<!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">] >'
                   7432: 	    .'<!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">'
                   7433:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7434: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7435:     } else {
1.849     bisitz   7436: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                   7437:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 7438:     }
                   7439:     return $output;
                   7440: }
1.340     albertel 7441: 
                   7442: =pod
                   7443: 
1.306     albertel 7444: =item * &start_page()
                   7445: 
                   7446: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7447: 
1.648     raeburn  7448: Inputs:
                   7449: 
                   7450: =over 4
                   7451: 
                   7452: $title - optional title for the page
                   7453: 
                   7454: $head_extra - optional extra HTML to incude inside the <head>
                   7455: 
                   7456: $args - additional optional args supported are:
                   7457: 
                   7458: =over 8
                   7459: 
                   7460:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7461:                                     arg on
1.814     bisitz   7462:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7463:              add_entries    -> additional attributes to add to the  <body>
                   7464:              domain         -> force to color decorate a page for a 
1.317     albertel 7465:                                     specific domain
1.648     raeburn  7466:              function       -> force usage of a specific rolish color
1.317     albertel 7467:                                     scheme
1.648     raeburn  7468:              redirect       -> see &headtag()
                   7469:              bgcolor        -> override the default page bg color
                   7470:              js_ready       -> return a string ready for being used in 
1.317     albertel 7471:                                     a javascript writeln
1.648     raeburn  7472:              html_encode    -> return a string ready for being used in 
1.320     albertel 7473:                                     a html attribute
1.648     raeburn  7474:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7475:                                     $forcereg arg
1.648     raeburn  7476:              frameset       -> if true will start with a <frameset>
1.330     albertel 7477:                                     rather than <body>
1.648     raeburn  7478:              skip_phases    -> hash ref of 
1.338     albertel 7479:                                     head -> skip the <html><head> generation
                   7480:                                     body -> skip all <body> generation
1.648     raeburn  7481:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7482:              inherit_jsmath -> when creating popup window in a page,
                   7483:                                     should it have jsmath forced on by the
                   7484:                                     current page
1.867     kalberla 7485:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7486:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7487:              group          -> includes the current group, if page is for a 
                   7488:                                specific group  
1.361     albertel 7489: 
1.648     raeburn  7490: =back
1.460     albertel 7491: 
1.648     raeburn  7492: =back
1.562     albertel 7493: 
1.306     albertel 7494: =cut
                   7495: 
                   7496: sub start_page {
1.309     albertel 7497:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7498:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7499: 
1.315     albertel 7500:     $env{'internal.start_page'}++;
1.1096    raeburn  7501:     my ($result,@advtools);
1.964     droeschl 7502: 
1.338     albertel 7503:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7504:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7505:     }
                   7506:     
                   7507:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7508: 	if ($args->{'frameset'}) {
                   7509: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7510: 						$args->{'add_entries'});
                   7511: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7512:         } else {
                   7513:             $result .=
                   7514:                 &bodytag($title, 
                   7515:                          $args->{'function'},       $args->{'add_entries'},
                   7516:                          $args->{'only_body'},      $args->{'domain'},
                   7517:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  7518:                          $args->{'bgcolor'},        $args,
                   7519:                          \@advtools);
1.831     bisitz   7520:         }
1.330     albertel 7521:     }
1.338     albertel 7522: 
1.315     albertel 7523:     if ($args->{'js_ready'}) {
1.713     kaisler  7524: 		$result = &js_ready($result);
1.315     albertel 7525:     }
1.320     albertel 7526:     if ($args->{'html_encode'}) {
1.713     kaisler  7527: 		$result = &html_encode($result);
                   7528:     }
                   7529: 
1.813     bisitz   7530:     # Preparation for new and consistent functionlist at top of screen
                   7531:     # if ($args->{'functionlist'}) {
                   7532:     #            $result .= &build_functionlist();
                   7533:     #}
                   7534: 
1.964     droeschl 7535:     # Don't add anything more if only_body wanted or in const space
                   7536:     return $result if    $args->{'only_body'} 
                   7537:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7538: 
                   7539:     #Breadcrumbs
1.758     kaisler  7540:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7541: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7542: 		#if any br links exists, add them to the breadcrumbs
                   7543: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7544: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7545: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7546: 			}
                   7547: 		}
1.1096    raeburn  7548:                 # if @advtools array contains items add then to the breadcrumbs
                   7549:                 if (@advtools > 0) {
                   7550:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7551:                 }
1.758     kaisler  7552: 
                   7553: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7554: 		if(exists($args->{'bread_crumbs_component'})){
                   7555: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7556: 		}else{
                   7557: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7558: 		}
1.320     albertel 7559:     }
1.315     albertel 7560:     return $result;
1.306     albertel 7561: }
                   7562: 
                   7563: sub end_page {
1.315     albertel 7564:     my ($args) = @_;
                   7565:     $env{'internal.end_page'}++;
1.330     albertel 7566:     my $result;
1.335     albertel 7567:     if ($args->{'discussion'}) {
                   7568: 	my ($target,$parser);
                   7569: 	if (ref($args->{'discussion'})) {
                   7570: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7571: 				$args->{'discussion'}{'parser'});
                   7572: 	}
                   7573: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7574:     }
1.330     albertel 7575:     if ($args->{'frameset'}) {
                   7576: 	$result .= '</frameset>';
                   7577:     } else {
1.635     raeburn  7578: 	$result .= &endbodytag($args);
1.330     albertel 7579:     }
1.1080    raeburn  7580:     unless ($args->{'notbody'}) {
                   7581:         $result .= "\n</html>";
                   7582:     }
1.330     albertel 7583: 
1.315     albertel 7584:     if ($args->{'js_ready'}) {
1.317     albertel 7585: 	$result = &js_ready($result);
1.315     albertel 7586:     }
1.335     albertel 7587: 
1.320     albertel 7588:     if ($args->{'html_encode'}) {
                   7589: 	$result = &html_encode($result);
                   7590:     }
1.335     albertel 7591: 
1.315     albertel 7592:     return $result;
                   7593: }
                   7594: 
1.1034    www      7595: sub wishlist_window {
                   7596:     return(<<'ENDWISHLIST');
1.1046    raeburn  7597: <script type="text/javascript">
1.1034    www      7598: // <![CDATA[
                   7599: // <!-- BEGIN LON-CAPA Internal
                   7600: function set_wishlistlink(title, path) {
                   7601:     if (!title) {
                   7602:         title = document.title;
                   7603:         title = title.replace(/^LON-CAPA /,'');
                   7604:     }
                   7605:     if (!path) {
                   7606:         path = location.pathname;
                   7607:     }
                   7608:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7609:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7610: }
                   7611: // END LON-CAPA Internal -->
                   7612: // ]]>
                   7613: </script>
                   7614: ENDWISHLIST
                   7615: }
                   7616: 
1.1030    www      7617: sub modal_window {
                   7618:     return(<<'ENDMODAL');
1.1046    raeburn  7619: <script type="text/javascript">
1.1030    www      7620: // <![CDATA[
                   7621: // <!-- BEGIN LON-CAPA Internal
                   7622: var modalWindow = {
                   7623: 	parent:"body",
                   7624: 	windowId:null,
                   7625: 	content:null,
                   7626: 	width:null,
                   7627: 	height:null,
                   7628: 	close:function()
                   7629: 	{
                   7630: 	        $(".LCmodal-window").remove();
                   7631: 	        $(".LCmodal-overlay").remove();
                   7632: 	},
                   7633: 	open:function()
                   7634: 	{
                   7635: 		var modal = "";
                   7636: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7637: 		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;\">";
                   7638: 		modal += this.content;
                   7639: 		modal += "</div>";	
                   7640: 
                   7641: 		$(this.parent).append(modal);
                   7642: 
                   7643: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7644: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7645: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7646: 	}
                   7647: };
1.1031    www      7648: 	var openMyModal = function(source,width,height,scrolling)
1.1030    www      7649: 	{
                   7650: 		modalWindow.windowId = "myModal";
                   7651: 		modalWindow.width = width;
                   7652: 		modalWindow.height = height;
1.1031    www      7653: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
1.1030    www      7654: 		modalWindow.open();
                   7655: 	};	
                   7656: // END LON-CAPA Internal -->
                   7657: // ]]>
                   7658: </script>
                   7659: ENDMODAL
                   7660: }
                   7661: 
                   7662: sub modal_link {
1.1052    www      7663:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
1.1030    www      7664:     unless ($width) { $width=480; }
                   7665:     unless ($height) { $height=400; }
1.1031    www      7666:     unless ($scrolling) { $scrolling='yes'; }
1.1074    raeburn  7667:     my $target_attr;
                   7668:     if (defined($target)) {
                   7669:         $target_attr = 'target="'.$target.'"';
                   7670:     }
                   7671:     return <<"ENDLINK";
                   7672: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
                   7673:            $linktext</a>
                   7674: ENDLINK
1.1030    www      7675: }
                   7676: 
1.1032    www      7677: sub modal_adhoc_script {
                   7678:     my ($funcname,$width,$height,$content)=@_;
                   7679:     return (<<ENDADHOC);
1.1046    raeburn  7680: <script type="text/javascript">
1.1032    www      7681: // <![CDATA[
                   7682:         var $funcname = function()
                   7683:         {
                   7684:                 modalWindow.windowId = "myModal";
                   7685:                 modalWindow.width = $width;
                   7686:                 modalWindow.height = $height;
                   7687:                 modalWindow.content = '$content';
                   7688:                 modalWindow.open();
                   7689:         };  
                   7690: // ]]>
                   7691: </script>
                   7692: ENDADHOC
                   7693: }
                   7694: 
1.1041    www      7695: sub modal_adhoc_inner {
                   7696:     my ($funcname,$width,$height,$content)=@_;
                   7697:     my $innerwidth=$width-20;
                   7698:     $content=&js_ready(
1.1042    www      7699:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1041    www      7700:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
                   7701:                     $content.
                   7702:                  &end_scrollbox().
                   7703:                &end_page()
                   7704:              );
                   7705:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7706: }
                   7707: 
                   7708: sub modal_adhoc_window {
                   7709:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7710:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7711:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7712: }
                   7713: 
                   7714: sub modal_adhoc_launch {
                   7715:     my ($funcname,$width,$height,$content)=@_;
                   7716:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7717: <script type="text/javascript">
                   7718: // <![CDATA[
                   7719: $funcname();
                   7720: // ]]>
                   7721: </script>
                   7722: ENDLAUNCH
                   7723: }
                   7724: 
                   7725: sub modal_adhoc_close {
                   7726:     return (<<ENDCLOSE);
                   7727: <script type="text/javascript">
                   7728: // <![CDATA[
                   7729: modalWindow.close();
                   7730: // ]]>
                   7731: </script>
                   7732: ENDCLOSE
                   7733: }
                   7734: 
1.1038    www      7735: sub togglebox_script {
                   7736:    return(<<ENDTOGGLE);
                   7737: <script type="text/javascript"> 
                   7738: // <![CDATA[
                   7739: function LCtoggleDisplay(id,hidetext,showtext) {
                   7740:    link = document.getElementById(id + "link").childNodes[0];
                   7741:    with (document.getElementById(id).style) {
                   7742:       if (display == "none" ) {
                   7743:           display = "inline";
                   7744:           link.nodeValue = hidetext;
                   7745:         } else {
                   7746:           display = "none";
                   7747:           link.nodeValue = showtext;
                   7748:        }
                   7749:    }
                   7750: }
                   7751: // ]]>
                   7752: </script>
                   7753: ENDTOGGLE
                   7754: }
                   7755: 
1.1039    www      7756: sub start_togglebox {
                   7757:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7758:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7759:     unless ($showtext) { $showtext=&mt('show'); }
                   7760:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7761:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7762:     return &start_data_table().
                   7763:            &start_data_table_header_row().
                   7764:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7765:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7766:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7767:            &end_data_table_header_row().
                   7768:            '<tr id="'.$id.'" style="display:none""><td>';
                   7769: }
                   7770: 
                   7771: sub end_togglebox {
                   7772:     return '</td></tr>'.&end_data_table();
                   7773: }
                   7774: 
1.1041    www      7775: sub LCprogressbar_script {
1.1045    www      7776:    my ($id)=@_;
1.1041    www      7777:    return(<<ENDPROGRESS);
                   7778: <script type="text/javascript">
                   7779: // <![CDATA[
1.1045    www      7780: \$('#progressbar$id').progressbar({
1.1041    www      7781:   value: 0,
                   7782:   change: function(event, ui) {
                   7783:     var newVal = \$(this).progressbar('option', 'value');
                   7784:     \$('.pblabel', this).text(LCprogressTxt);
                   7785:   }
                   7786: });
                   7787: // ]]>
                   7788: </script>
                   7789: ENDPROGRESS
                   7790: }
                   7791: 
                   7792: sub LCprogressbarUpdate_script {
                   7793:    return(<<ENDPROGRESSUPDATE);
                   7794: <style type="text/css">
                   7795: .ui-progressbar { position:relative; }
                   7796: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7797: </style>
                   7798: <script type="text/javascript">
                   7799: // <![CDATA[
1.1045    www      7800: var LCprogressTxt='---';
                   7801: 
                   7802: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7803:    LCprogressTxt=progresstext;
1.1045    www      7804:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7805: }
                   7806: // ]]>
                   7807: </script>
                   7808: ENDPROGRESSUPDATE
                   7809: }
                   7810: 
1.1042    www      7811: my $LClastpercent;
1.1045    www      7812: my $LCidcnt;
                   7813: my $LCcurrentid;
1.1042    www      7814: 
1.1041    www      7815: sub LCprogressbar {
1.1042    www      7816:     my ($r)=(@_);
                   7817:     $LClastpercent=0;
1.1045    www      7818:     $LCidcnt++;
                   7819:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7820:     my $starting=&mt('Starting');
                   7821:     my $content=(<<ENDPROGBAR);
1.1045    www      7822:   <div id="progressbar$LCcurrentid">
1.1041    www      7823:     <span class="pblabel">$starting</span>
                   7824:   </div>
                   7825: ENDPROGBAR
1.1045    www      7826:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7827: }
                   7828: 
                   7829: sub LCprogressbarUpdate {
1.1042    www      7830:     my ($r,$val,$text)=@_;
                   7831:     unless ($val) { 
                   7832:        if ($LClastpercent) {
                   7833:            $val=$LClastpercent;
                   7834:        } else {
                   7835:            $val=0;
                   7836:        }
                   7837:     }
1.1041    www      7838:     if ($val<0) { $val=0; }
                   7839:     if ($val>100) { $val=0; }
1.1042    www      7840:     $LClastpercent=$val;
1.1041    www      7841:     unless ($text) { $text=$val.'%'; }
                   7842:     $text=&js_ready($text);
1.1044    www      7843:     &r_print($r,<<ENDUPDATE);
1.1041    www      7844: <script type="text/javascript">
                   7845: // <![CDATA[
1.1045    www      7846: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7847: // ]]>
                   7848: </script>
                   7849: ENDUPDATE
1.1035    www      7850: }
                   7851: 
1.1042    www      7852: sub LCprogressbarClose {
                   7853:     my ($r)=@_;
                   7854:     $LClastpercent=0;
1.1044    www      7855:     &r_print($r,<<ENDCLOSE);
1.1042    www      7856: <script type="text/javascript">
                   7857: // <![CDATA[
1.1045    www      7858: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7859: // ]]>
                   7860: </script>
                   7861: ENDCLOSE
1.1044    www      7862: }
                   7863: 
                   7864: sub r_print {
                   7865:     my ($r,$to_print)=@_;
                   7866:     if ($r) {
                   7867:       $r->print($to_print);
                   7868:       $r->rflush();
                   7869:     } else {
                   7870:       print($to_print);
                   7871:     }
1.1042    www      7872: }
                   7873: 
1.320     albertel 7874: sub html_encode {
                   7875:     my ($result) = @_;
                   7876: 
1.322     albertel 7877:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7878:     
                   7879:     return $result;
                   7880: }
1.1044    www      7881: 
1.317     albertel 7882: sub js_ready {
                   7883:     my ($result) = @_;
                   7884: 
1.323     albertel 7885:     $result =~ s/[\n\r]/ /xmsg;
                   7886:     $result =~ s/\\/\\\\/xmsg;
                   7887:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7888:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7889:     
                   7890:     return $result;
                   7891: }
                   7892: 
1.315     albertel 7893: sub validate_page {
                   7894:     if (  exists($env{'internal.start_page'})
1.316     albertel 7895: 	  &&     $env{'internal.start_page'} > 1) {
                   7896: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7897: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7898: 				 $ENV{'request.filename'});
1.315     albertel 7899:     }
                   7900:     if (  exists($env{'internal.end_page'})
1.316     albertel 7901: 	  &&     $env{'internal.end_page'} > 1) {
                   7902: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7903: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7904: 				 $env{'request.filename'});
1.315     albertel 7905:     }
                   7906:     if (     exists($env{'internal.start_page'})
                   7907: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7908: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7909: 				 $env{'request.filename'});
1.315     albertel 7910:     }
                   7911:     if (   ! exists($env{'internal.start_page'})
                   7912: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7913: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7914: 				 $env{'request.filename'});
1.315     albertel 7915:     }
1.306     albertel 7916: }
1.315     albertel 7917: 
1.996     www      7918: 
                   7919: sub start_scrollbox {
1.1075    raeburn  7920:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
1.998     raeburn  7921:     unless ($outerwidth) { $outerwidth='520px'; }
                   7922:     unless ($width) { $width='500px'; }
                   7923:     unless ($height) { $height='200px'; }
1.1075    raeburn  7924:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7925:     if ($id ne '') {
1.1020    raeburn  7926:         $table_id = " id='table_$id'";
                   7927:         $div_id = " id='div_$id'";
1.1018    raeburn  7928:     }
1.1075    raeburn  7929:     if ($bgcolor ne '') {
                   7930:         $tdcol = "background-color: $bgcolor;";
                   7931:     }
                   7932:     return <<"END";
                   7933: <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>
                   7934: END
1.996     www      7935: }
                   7936: 
                   7937: sub end_scrollbox {
1.1036    www      7938:     return '</div></td></tr></table>';
1.996     www      7939: }
                   7940: 
1.318     albertel 7941: sub simple_error_page {
                   7942:     my ($r,$title,$msg) = @_;
                   7943:     my $page =
                   7944: 	&Apache::loncommon::start_page($title).
1.1097    bisitz   7945: 	'<p class="LC_error">'.&mt($msg).'</p>'.
1.318     albertel 7946: 	&Apache::loncommon::end_page();
                   7947:     if (ref($r)) {
                   7948: 	$r->print($page);
1.327     albertel 7949: 	return;
1.318     albertel 7950:     }
                   7951:     return $page;
                   7952: }
1.347     albertel 7953: 
                   7954: {
1.610     albertel 7955:     my @row_count;
1.961     onken    7956: 
                   7957:     sub start_data_table_count {
                   7958:         unshift(@row_count, 0);
                   7959:         return;
                   7960:     }
                   7961: 
                   7962:     sub end_data_table_count {
                   7963:         shift(@row_count);
                   7964:         return;
                   7965:     }
                   7966: 
1.347     albertel 7967:     sub start_data_table {
1.1018    raeburn  7968: 	my ($add_class,$id) = @_;
1.422     albertel 7969: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  7970:         my $table_id;
                   7971:         if (defined($id)) {
                   7972:             $table_id = ' id="'.$id.'"';
                   7973:         }
1.961     onken    7974: 	&start_data_table_count();
1.1018    raeburn  7975: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 7976:     }
                   7977: 
                   7978:     sub end_data_table {
1.961     onken    7979: 	&end_data_table_count();
1.389     albertel 7980: 	return '</table>'."\n";;
1.347     albertel 7981:     }
                   7982: 
                   7983:     sub start_data_table_row {
1.974     wenzelju 7984: 	my ($add_class, $id) = @_;
1.610     albertel 7985: 	$row_count[0]++;
                   7986: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   7987: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 7988:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7989:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 7990:     }
1.471     banghart 7991:     
                   7992:     sub continue_data_table_row {
1.974     wenzelju 7993: 	my ($add_class, $id) = @_;
1.610     albertel 7994: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 7995: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   7996:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7997:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 7998:     }
1.347     albertel 7999: 
                   8000:     sub end_data_table_row {
1.389     albertel 8001: 	return '</tr>'."\n";;
1.347     albertel 8002:     }
1.367     www      8003: 
1.421     albertel 8004:     sub start_data_table_empty_row {
1.707     bisitz   8005: #	$row_count[0]++;
1.421     albertel 8006: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8007:     }
                   8008: 
                   8009:     sub end_data_table_empty_row {
                   8010: 	return '</tr>'."\n";;
                   8011:     }
                   8012: 
1.367     www      8013:     sub start_data_table_header_row {
1.389     albertel 8014: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8015:     }
                   8016: 
                   8017:     sub end_data_table_header_row {
1.389     albertel 8018: 	return '</tr>'."\n";;
1.367     www      8019:     }
1.890     droeschl 8020: 
                   8021:     sub data_table_caption {
                   8022:         my $caption = shift;
                   8023:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8024:     }
1.347     albertel 8025: }
                   8026: 
1.548     albertel 8027: =pod
                   8028: 
                   8029: =item * &inhibit_menu_check($arg)
                   8030: 
                   8031: Checks for a inhibitmenu state and generates output to preserve it
                   8032: 
                   8033: Inputs:         $arg - can be any of
                   8034:                      - undef - in which case the return value is a string 
                   8035:                                to add  into arguments list of a uri
                   8036:                      - 'input' - in which case the return value is a HTML
                   8037:                                  <form> <input> field of type hidden to
                   8038:                                  preserve the value
                   8039:                      - a url - in which case the return value is the url with
                   8040:                                the neccesary cgi args added to preserve the
                   8041:                                inhibitmenu state
                   8042:                      - a ref to a url - no return value, but the string is
                   8043:                                         updated to include the neccessary cgi
                   8044:                                         args to preserve the inhibitmenu state
                   8045: 
                   8046: =cut
                   8047: 
                   8048: sub inhibit_menu_check {
                   8049:     my ($arg) = @_;
                   8050:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8051:     if ($arg eq 'input') {
                   8052: 	if ($env{'form.inhibitmenu'}) {
                   8053: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8054: 	} else {
                   8055: 	    return
                   8056: 	}
                   8057:     }
                   8058:     if ($env{'form.inhibitmenu'}) {
                   8059: 	if (ref($arg)) {
                   8060: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8061: 	} elsif ($arg eq '') {
                   8062: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8063: 	} else {
                   8064: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8065: 	}
                   8066:     }
                   8067:     if (!ref($arg)) {
                   8068: 	return $arg;
                   8069:     }
                   8070: }
                   8071: 
1.251     albertel 8072: ###############################################
1.182     matthew  8073: 
                   8074: =pod
                   8075: 
1.549     albertel 8076: =back
                   8077: 
                   8078: =head1 User Information Routines
                   8079: 
                   8080: =over 4
                   8081: 
1.405     albertel 8082: =item * &get_users_function()
1.182     matthew  8083: 
                   8084: Used by &bodytag to determine the current users primary role.
                   8085: Returns either 'student','coordinator','admin', or 'author'.
                   8086: 
                   8087: =cut
                   8088: 
                   8089: ###############################################
                   8090: sub get_users_function {
1.815     tempelho 8091:     my $function = 'norole';
1.818     tempelho 8092:     if ($env{'request.role'}=~/^(st)/) {
                   8093:         $function='student';
                   8094:     }
1.907     raeburn  8095:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8096:         $function='coordinator';
                   8097:     }
1.258     albertel 8098:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8099:         $function='admin';
                   8100:     }
1.826     bisitz   8101:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8102:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8103:         $function='author';
                   8104:     }
                   8105:     return $function;
1.54      www      8106: }
1.99      www      8107: 
                   8108: ###############################################
                   8109: 
1.233     raeburn  8110: =pod
                   8111: 
1.821     raeburn  8112: =item * &show_course()
                   8113: 
                   8114: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8115: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8116: 
                   8117: Inputs:
                   8118: None
                   8119: 
                   8120: Outputs:
                   8121: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8122: 
                   8123: =cut
                   8124: 
                   8125: ###############################################
                   8126: sub show_course {
                   8127:     my $course = !$env{'user.adv'};
                   8128:     if (!$env{'user.adv'}) {
                   8129:         foreach my $env (keys(%env)) {
                   8130:             next if ($env !~ m/^user\.priv\./);
                   8131:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8132:                 $course = 0;
                   8133:                 last;
                   8134:             }
                   8135:         }
                   8136:     }
                   8137:     return $course;
                   8138: }
                   8139: 
                   8140: ###############################################
                   8141: 
                   8142: =pod
                   8143: 
1.542     raeburn  8144: =item * &check_user_status()
1.274     raeburn  8145: 
                   8146: Determines current status of supplied role for a
                   8147: specific user. Roles can be active, previous or future.
                   8148: 
                   8149: Inputs: 
                   8150: user's domain, user's username, course's domain,
1.375     raeburn  8151: course's number, optional section ID.
1.274     raeburn  8152: 
                   8153: Outputs:
                   8154: role status: active, previous or future. 
                   8155: 
                   8156: =cut
                   8157: 
                   8158: sub check_user_status {
1.412     raeburn  8159:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8160:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8161:     my @uroles = keys %userinfo;
                   8162:     my $srchstr;
                   8163:     my $active_chk = 'none';
1.412     raeburn  8164:     my $now = time;
1.274     raeburn  8165:     if (@uroles > 0) {
1.908     raeburn  8166:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8167:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8168:         } else {
1.412     raeburn  8169:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8170:         }
                   8171:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8172:             my $role_end = 0;
                   8173:             my $role_start = 0;
                   8174:             $active_chk = 'active';
1.412     raeburn  8175:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8176:                 $role_end = $1;
                   8177:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8178:                     $role_start = $1;
1.274     raeburn  8179:                 }
                   8180:             }
                   8181:             if ($role_start > 0) {
1.412     raeburn  8182:                 if ($now < $role_start) {
1.274     raeburn  8183:                     $active_chk = 'future';
                   8184:                 }
                   8185:             }
                   8186:             if ($role_end > 0) {
1.412     raeburn  8187:                 if ($now > $role_end) {
1.274     raeburn  8188:                     $active_chk = 'previous';
                   8189:                 }
                   8190:             }
                   8191:         }
                   8192:     }
                   8193:     return $active_chk;
                   8194: }
                   8195: 
                   8196: ###############################################
                   8197: 
                   8198: =pod
                   8199: 
1.405     albertel 8200: =item * &get_sections()
1.233     raeburn  8201: 
                   8202: Determines all the sections for a course including
                   8203: sections with students and sections containing other roles.
1.419     raeburn  8204: Incoming parameters: 
                   8205: 
                   8206: 1. domain
                   8207: 2. course number 
                   8208: 3. reference to array containing roles for which sections should 
                   8209: be gathered (optional).
                   8210: 4. reference to array containing status types for which sections 
                   8211: should be gathered (optional).
                   8212: 
                   8213: If the third argument is undefined, sections are gathered for any role. 
                   8214: If the fourth argument is undefined, sections are gathered for any status.
                   8215: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8216:  
1.374     raeburn  8217: Returns section hash (keys are section IDs, values are
                   8218: number of users in each section), subject to the
1.419     raeburn  8219: optional roles filter, optional status filter 
1.233     raeburn  8220: 
                   8221: =cut
                   8222: 
                   8223: ###############################################
                   8224: sub get_sections {
1.419     raeburn  8225:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8226:     if (!defined($cdom) || !defined($cnum)) {
                   8227:         my $cid =  $env{'request.course.id'};
                   8228: 
                   8229: 	return if (!defined($cid));
                   8230: 
                   8231:         $cdom = $env{'course.'.$cid.'.domain'};
                   8232:         $cnum = $env{'course.'.$cid.'.num'};
                   8233:     }
                   8234: 
                   8235:     my %sectioncount;
1.419     raeburn  8236:     my $now = time;
1.240     albertel 8237: 
1.1118    raeburn  8238:     my $check_students = 1;
                   8239:     my $only_students = 0;
                   8240:     if (ref($possible_roles) eq 'ARRAY') {
                   8241:         if (grep(/^st$/,@{$possible_roles})) {
                   8242:             if (@{$possible_roles} == 1) {
                   8243:                 $only_students = 1;
                   8244:             }
                   8245:         } else {
                   8246:             $check_students = 0;
                   8247:         }
                   8248:     }
                   8249: 
                   8250:     if ($check_students) { 
1.276     albertel 8251: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8252: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8253: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8254:         my $start_index = &Apache::loncoursedata::CL_START();
                   8255:         my $end_index = &Apache::loncoursedata::CL_END();
                   8256:         my $status;
1.366     albertel 8257: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8258: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8259: 				                     $data->[$status_index],
                   8260:                                                      $data->[$start_index],
                   8261:                                                      $data->[$end_index]);
                   8262:             if ($stu_status eq 'Active') {
                   8263:                 $status = 'active';
                   8264:             } elsif ($end < $now) {
                   8265:                 $status = 'previous';
                   8266:             } elsif ($start > $now) {
                   8267:                 $status = 'future';
                   8268:             } 
                   8269: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8270:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8271:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8272: 		    $sectioncount{$section}++;
                   8273:                 }
1.240     albertel 8274: 	    }
                   8275: 	}
                   8276:     }
1.1118    raeburn  8277:     if ($only_students) {
                   8278:         return %sectioncount;
                   8279:     }
1.240     albertel 8280:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8281:     foreach my $user (sort(keys(%courseroles))) {
                   8282: 	if ($user !~ /^(\w{2})/) { next; }
                   8283: 	my ($role) = ($user =~ /^(\w{2})/);
                   8284: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8285: 	my ($section,$status);
1.240     albertel 8286: 	if ($role eq 'cr' &&
                   8287: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8288: 	    $section=$1;
                   8289: 	}
                   8290: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8291: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8292:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8293:         if ($end == -1 && $start == -1) {
                   8294:             next; #deleted role
                   8295:         }
                   8296:         if (!defined($possible_status)) { 
                   8297:             $sectioncount{$section}++;
                   8298:         } else {
                   8299:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8300:                 $status = 'active';
                   8301:             } elsif ($end < $now) {
                   8302:                 $status = 'future';
                   8303:             } elsif ($start > $now) {
                   8304:                 $status = 'previous';
                   8305:             }
                   8306:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8307:                 $sectioncount{$section}++;
                   8308:             }
                   8309:         }
1.233     raeburn  8310:     }
1.366     albertel 8311:     return %sectioncount;
1.233     raeburn  8312: }
                   8313: 
1.274     raeburn  8314: ###############################################
1.294     raeburn  8315: 
                   8316: =pod
1.405     albertel 8317: 
                   8318: =item * &get_course_users()
                   8319: 
1.275     raeburn  8320: Retrieves usernames:domains for users in the specified course
                   8321: with specific role(s), and access status. 
                   8322: 
                   8323: Incoming parameters:
1.277     albertel 8324: 1. course domain
                   8325: 2. course number
                   8326: 3. access status: users must have - either active, 
1.275     raeburn  8327: previous, future, or all.
1.277     albertel 8328: 4. reference to array of permissible roles
1.288     raeburn  8329: 5. reference to array of section restrictions (optional)
                   8330: 6. reference to results object (hash of hashes).
                   8331: 7. reference to optional userdata hash
1.609     raeburn  8332: 8. reference to optional statushash
1.630     raeburn  8333: 9. flag if privileged users (except those set to unhide in
                   8334:    course settings) should be excluded    
1.609     raeburn  8335: Keys of top level results hash are roles.
1.275     raeburn  8336: Keys of inner hashes are username:domain, with 
                   8337: values set to access type.
1.288     raeburn  8338: Optional userdata hash returns an array with arguments in the 
                   8339: same order as loncoursedata::get_classlist() for student data.
                   8340: 
1.609     raeburn  8341: Optional statushash returns
                   8342: 
1.288     raeburn  8343: Entries for end, start, section and status are blank because
                   8344: of the possibility of multiple values for non-student roles.
                   8345: 
1.275     raeburn  8346: =cut
1.405     albertel 8347: 
1.275     raeburn  8348: ###############################################
1.405     albertel 8349: 
1.275     raeburn  8350: sub get_course_users {
1.630     raeburn  8351:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8352:     my %idx = ();
1.419     raeburn  8353:     my %seclists;
1.288     raeburn  8354: 
                   8355:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8356:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8357:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8358:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8359:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8360:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8361:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8362:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8363: 
1.290     albertel 8364:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8365:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8366:         my $now = time;
1.277     albertel 8367:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8368:             my $match = 0;
1.412     raeburn  8369:             my $secmatch = 0;
1.419     raeburn  8370:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8371:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8372:             if ($section eq '') {
                   8373:                 $section = 'none';
                   8374:             }
1.291     albertel 8375:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8376:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8377:                     $secmatch = 1;
                   8378:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8379:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8380:                         $secmatch = 1;
                   8381:                     }
                   8382:                 } else {  
1.419     raeburn  8383: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8384: 		        $secmatch = 1;
                   8385:                     }
1.290     albertel 8386: 		}
1.412     raeburn  8387:                 if (!$secmatch) {
                   8388:                     next;
                   8389:                 }
1.419     raeburn  8390:             }
1.275     raeburn  8391:             if (defined($$types{'active'})) {
1.288     raeburn  8392:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8393:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8394:                     $match = 1;
1.275     raeburn  8395:                 }
                   8396:             }
                   8397:             if (defined($$types{'previous'})) {
1.609     raeburn  8398:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8399:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8400:                     $match = 1;
1.275     raeburn  8401:                 }
                   8402:             }
                   8403:             if (defined($$types{'future'})) {
1.609     raeburn  8404:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8405:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8406:                     $match = 1;
1.275     raeburn  8407:                 }
                   8408:             }
1.609     raeburn  8409:             if ($match) {
                   8410:                 push(@{$seclists{$student}},$section);
                   8411:                 if (ref($userdata) eq 'HASH') {
                   8412:                     $$userdata{$student} = $$classlist{$student};
                   8413:                 }
                   8414:                 if (ref($statushash) eq 'HASH') {
                   8415:                     $statushash->{$student}{'st'}{$section} = $status;
                   8416:                 }
1.288     raeburn  8417:             }
1.275     raeburn  8418:         }
                   8419:     }
1.412     raeburn  8420:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8421:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8422:         my $now = time;
1.609     raeburn  8423:         my %displaystatus = ( previous => 'Expired',
                   8424:                               active   => 'Active',
                   8425:                               future   => 'Future',
                   8426:                             );
1.1121    raeburn  8427:         my (%nothide,@possdoms);
1.630     raeburn  8428:         if ($hidepriv) {
                   8429:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8430:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8431:                 if ($user !~ /:/) {
                   8432:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8433:                 } else {
                   8434:                     $nothide{$user} = 1;
                   8435:                 }
                   8436:             }
1.1121    raeburn  8437:             my @possdoms = ($cdom);
                   8438:             if ($coursehash{'checkforpriv'}) {
                   8439:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8440:             }
1.630     raeburn  8441:         }
1.439     raeburn  8442:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8443:             my $match = 0;
1.412     raeburn  8444:             my $secmatch = 0;
1.439     raeburn  8445:             my $status;
1.412     raeburn  8446:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8447:             $user =~ s/:$//;
1.439     raeburn  8448:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8449:             if ($end == -1 || $start == -1) {
                   8450:                 next;
                   8451:             }
                   8452:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8453:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8454:                 my ($uname,$udom) = split(/:/,$user);
                   8455:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8456:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8457:                         $secmatch = 1;
                   8458:                     } elsif ($usec eq '') {
1.420     albertel 8459:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8460:                             $secmatch = 1;
                   8461:                         }
                   8462:                     } else {
                   8463:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8464:                             $secmatch = 1;
                   8465:                         }
                   8466:                     }
                   8467:                     if (!$secmatch) {
                   8468:                         next;
                   8469:                     }
1.288     raeburn  8470:                 }
1.419     raeburn  8471:                 if ($usec eq '') {
                   8472:                     $usec = 'none';
                   8473:                 }
1.275     raeburn  8474:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8475:                     if ($hidepriv) {
1.1121    raeburn  8476:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8477:                             (!$nothide{$uname.':'.$udom})) {
                   8478:                             next;
                   8479:                         }
                   8480:                     }
1.503     raeburn  8481:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8482:                         $status = 'previous';
                   8483:                     } elsif ($start > $now) {
                   8484:                         $status = 'future';
                   8485:                     } else {
                   8486:                         $status = 'active';
                   8487:                     }
1.277     albertel 8488:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8489:                         if ($status eq $type) {
1.420     albertel 8490:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8491:                                 push(@{$$users{$role}{$user}},$type);
                   8492:                             }
1.288     raeburn  8493:                             $match = 1;
                   8494:                         }
                   8495:                     }
1.419     raeburn  8496:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8497:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8498: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8499:                         }
1.420     albertel 8500:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8501:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8502:                         }
1.609     raeburn  8503:                         if (ref($statushash) eq 'HASH') {
                   8504:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8505:                         }
1.275     raeburn  8506:                     }
                   8507:                 }
                   8508:             }
                   8509:         }
1.290     albertel 8510:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8511:             if ((defined($cdom)) && (defined($cnum))) {
                   8512:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8513:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8514:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8515:                     next if ($owner eq '');
                   8516:                     my ($ownername,$ownerdom);
                   8517:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8518:                         $ownername = $1;
                   8519:                         $ownerdom = $2;
                   8520:                     } else {
                   8521:                         $ownername = $owner;
                   8522:                         $ownerdom = $cdom;
                   8523:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8524:                     }
                   8525:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8526:                     if (defined($userdata) && 
1.609     raeburn  8527: 			!exists($$userdata{$owner})) {
                   8528: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8529:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8530:                             push(@{$seclists{$owner}},'none');
                   8531:                         }
                   8532:                         if (ref($statushash) eq 'HASH') {
                   8533:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8534:                         }
1.290     albertel 8535: 		    }
1.279     raeburn  8536:                 }
                   8537:             }
                   8538:         }
1.419     raeburn  8539:         foreach my $user (keys(%seclists)) {
                   8540:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8541:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8542:         }
1.275     raeburn  8543:     }
                   8544:     return;
                   8545: }
                   8546: 
1.288     raeburn  8547: sub get_user_info {
                   8548:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8549:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8550: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8551:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8552:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8553:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8554:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8555:     return;
                   8556: }
1.275     raeburn  8557: 
1.472     raeburn  8558: ###############################################
                   8559: 
                   8560: =pod
                   8561: 
                   8562: =item * &get_user_quota()
                   8563: 
1.1134  ! raeburn  8564: Retrieves quota assigned for storage of user files.
        !          8565: Default is to report quota for portfolio files.
1.472     raeburn  8566: 
                   8567: Incoming parameters:
                   8568: 1. user's username
                   8569: 2. user's domain
1.1134  ! raeburn  8570: 3. quota name - portfolio, author, or course
        !          8571:    (if no quota name provided, defaults to portfolio).  
1.472     raeburn  8572: 
                   8573: Returns:
1.536     raeburn  8574: 1. Disk quota (in Mb) assigned to student.
                   8575: 2. (Optional) Type of setting: custom or default
                   8576:    (individually assigned or default for user's 
                   8577:    institutional status).
                   8578: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8579:    or student - types as defined in localenroll::inst_usertypes 
                   8580:    for user's domain, which determines default quota for user.
                   8581: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8582: 
                   8583: If a value has been stored in the user's environment, 
1.536     raeburn  8584: it will return that, otherwise it returns the maximal default
1.1134  ! raeburn  8585: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8586: 
                   8587: =cut
                   8588: 
                   8589: ###############################################
                   8590: 
                   8591: 
                   8592: sub get_user_quota {
1.1134  ! raeburn  8593:     my ($uname,$udom,$quotaname) = @_;
1.536     raeburn  8594:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8595:     if (!defined($udom)) {
                   8596:         $udom = $env{'user.domain'};
                   8597:     }
                   8598:     if (!defined($uname)) {
                   8599:         $uname = $env{'user.name'};
                   8600:     }
                   8601:     if (($udom eq '' || $uname eq '') ||
                   8602:         ($udom eq 'public') && ($uname eq 'public')) {
                   8603:         $quota = 0;
1.536     raeburn  8604:         $quotatype = 'default';
                   8605:         $defquota = 0; 
1.472     raeburn  8606:     } else {
1.536     raeburn  8607:         my $inststatus;
1.1134  ! raeburn  8608:         if ($quotaname eq 'course') {
        !          8609:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
        !          8610:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
        !          8611:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
        !          8612:             } else {
        !          8613:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
        !          8614:                 $quota = $cenv{'internal.uploadquota'};
        !          8615:             }
1.536     raeburn  8616:         } else {
1.1134  ! raeburn  8617:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
        !          8618:                 if ($quotaname eq 'author') {
        !          8619:                     $quota = $env{'environment.authorquota'};
        !          8620:                 } else {
        !          8621:                     $quota = $env{'environment.portfolioquota'};
        !          8622:                 }
        !          8623:                 $inststatus = $env{'environment.inststatus'};
        !          8624:             } else {
        !          8625:                 my %userenv = 
        !          8626:                     &Apache::lonnet::get('environment',['portfolioquota',
        !          8627:                                          'authorquota','inststatus'],$udom,$uname);
        !          8628:                 my ($tmp) = keys(%userenv);
        !          8629:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
        !          8630:                     if ($quotaname eq 'author') {
        !          8631:                         $quota = $userenv{'authorquota'};
        !          8632:                     } else {
        !          8633:                         $quota = $userenv{'portfolioquota'};
        !          8634:                     }
        !          8635:                     $inststatus = $userenv{'inststatus'};
        !          8636:                 } else {
        !          8637:                     undef(%userenv);
        !          8638:                 }
        !          8639:             }
        !          8640:         }
        !          8641:         if ($quota eq '' || wantarray) {
        !          8642:             if ($quotaname eq 'course') {
        !          8643:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
        !          8644:                 $defquota = $domdefs{'uploadquota'};
        !          8645:             } else {
        !          8646:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
        !          8647:             }
        !          8648:             if ($quota eq '') {
        !          8649:                 $quota = $defquota;
        !          8650:                 $quotatype = 'default';
        !          8651:             } else {
        !          8652:                 $quotatype = 'custom';
        !          8653:             }
1.472     raeburn  8654:         }
                   8655:     }
1.536     raeburn  8656:     if (wantarray) {
                   8657:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8658:     } else {
                   8659:         return $quota;
                   8660:     }
1.472     raeburn  8661: }
                   8662: 
                   8663: ###############################################
                   8664: 
                   8665: =pod
                   8666: 
                   8667: =item * &default_quota()
                   8668: 
1.536     raeburn  8669: Retrieves default quota assigned for storage of user portfolio files,
                   8670: given an (optional) user's institutional status.
1.472     raeburn  8671: 
                   8672: Incoming parameters:
                   8673: 1. domain
1.536     raeburn  8674: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8675:    status types (e.g., faculty, staff, student etc.)
                   8676:    which apply to the user for whom the default is being retrieved.
                   8677:    If the institutional status string in undefined, the domain
1.1134  ! raeburn  8678:    default quota will be returned.
        !          8679: 3.  quota name - portfolio, author, or course
        !          8680:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  8681: 
                   8682: Returns:
                   8683: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  8684: 2. (Optional) institutional type which determined the value of the
                   8685:    default quota.
1.472     raeburn  8686: 
                   8687: If a value has been stored in the domain's configuration db,
                   8688: it will return that, otherwise it returns 20 (for backwards 
                   8689: compatibility with domains which have not set up a configuration
                   8690: db file; the original statically defined portfolio quota was 20 Mb). 
                   8691: 
1.536     raeburn  8692: If the user's status includes multiple types (e.g., staff and student),
                   8693: the largest default quota which applies to the user determines the
                   8694: default quota returned.
                   8695: 
1.780     raeburn  8696: =back
                   8697: 
1.472     raeburn  8698: =cut
                   8699: 
                   8700: ###############################################
                   8701: 
                   8702: 
                   8703: sub default_quota {
1.1134  ! raeburn  8704:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  8705:     my ($defquota,$settingstatus);
                   8706:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8707:                                             ['quotas'],$udom);
1.1134  ! raeburn  8708:     my $key = 'defaultquota';
        !          8709:     if ($quotaname eq 'author') {
        !          8710:         $key = 'authorquota';
        !          8711:     }
1.622     raeburn  8712:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8713:         if ($inststatus ne '') {
1.765     raeburn  8714:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8715:             foreach my $item (@statuses) {
1.1134  ! raeburn  8716:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
        !          8717:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  8718:                         if ($defquota eq '') {
1.1134  ! raeburn  8719:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8720:                             $settingstatus = $item;
1.1134  ! raeburn  8721:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
        !          8722:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8723:                             $settingstatus = $item;
                   8724:                         }
                   8725:                     }
1.1134  ! raeburn  8726:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  8727:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8728:                         if ($defquota eq '') {
                   8729:                             $defquota = $quotahash{'quotas'}{$item};
                   8730:                             $settingstatus = $item;
                   8731:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8732:                             $defquota = $quotahash{'quotas'}{$item};
                   8733:                             $settingstatus = $item;
                   8734:                         }
1.536     raeburn  8735:                     }
                   8736:                 }
                   8737:             }
                   8738:         }
                   8739:         if ($defquota eq '') {
1.1134  ! raeburn  8740:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
        !          8741:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
        !          8742:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  8743:                 $defquota = $quotahash{'quotas'}{'default'};
                   8744:             }
1.536     raeburn  8745:             $settingstatus = 'default';
                   8746:         }
                   8747:     } else {
                   8748:         $settingstatus = 'default';
1.1134  ! raeburn  8749:         if ($quotaname eq 'author') {
        !          8750:             $defquota = 500;
        !          8751:         } else {
        !          8752:             $defquota = 20;
        !          8753:         }
1.536     raeburn  8754:     }
                   8755:     if (wantarray) {
                   8756:         return ($defquota,$settingstatus);
1.472     raeburn  8757:     } else {
1.536     raeburn  8758:         return $defquota;
1.472     raeburn  8759:     }
                   8760: }
                   8761: 
1.384     raeburn  8762: sub get_secgrprole_info {
                   8763:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8764:     my %sections_count = &get_sections($cdom,$cnum);
                   8765:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8766:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8767:     my @groups = sort(keys(%curr_groups));
                   8768:     my $allroles = [];
                   8769:     my $rolehash;
                   8770:     my $accesshash = {
                   8771:                      active => 'Currently has access',
                   8772:                      future => 'Will have future access',
                   8773:                      previous => 'Previously had access',
                   8774:                   };
                   8775:     if ($needroles) {
                   8776:         $rolehash = {'all' => 'all'};
1.385     albertel 8777:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8778: 	if (&Apache::lonnet::error(%user_roles)) {
                   8779: 	    undef(%user_roles);
                   8780: 	}
                   8781:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8782:             my ($role)=split(/\:/,$item,2);
                   8783:             if ($role eq 'cr') { next; }
                   8784:             if ($role =~ /^cr/) {
                   8785:                 $$rolehash{$role} = (split('/',$role))[3];
                   8786:             } else {
                   8787:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8788:             }
                   8789:         }
                   8790:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8791:             push(@{$allroles},$key);
                   8792:         }
                   8793:         push (@{$allroles},'st');
                   8794:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8795:     }
                   8796:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8797: }
                   8798: 
1.555     raeburn  8799: sub user_picker {
1.994     raeburn  8800:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8801:     my $currdom = $dom;
                   8802:     my %curr_selected = (
                   8803:                         srchin => 'dom',
1.580     raeburn  8804:                         srchby => 'lastname',
1.555     raeburn  8805:                       );
                   8806:     my $srchterm;
1.625     raeburn  8807:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  8808:         if ($srch->{'srchby'} ne '') {
                   8809:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   8810:         }
                   8811:         if ($srch->{'srchin'} ne '') {
                   8812:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   8813:         }
                   8814:         if ($srch->{'srchtype'} ne '') {
                   8815:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   8816:         }
                   8817:         if ($srch->{'srchdomain'} ne '') {
                   8818:             $currdom = $srch->{'srchdomain'};
                   8819:         }
                   8820:         $srchterm = $srch->{'srchterm'};
                   8821:     }
                   8822:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  8823:                     'usr'       => 'Search criteria',
1.563     raeburn  8824:                     'doma'      => 'Domain/institution to search',
1.558     albertel 8825:                     'uname'     => 'username',
                   8826:                     'lastname'  => 'last name',
1.555     raeburn  8827:                     'lastfirst' => 'last name, first name',
1.558     albertel 8828:                     'crs'       => 'in this course',
1.576     raeburn  8829:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 8830:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  8831:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 8832:                     'exact'     => 'is',
                   8833:                     'contains'  => 'contains',
1.569     raeburn  8834:                     'begins'    => 'begins with',
1.571     raeburn  8835:                     'youm'      => "You must include some text to search for.",
                   8836:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   8837:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   8838:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   8839:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   8840:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   8841:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   8842:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  8843:                                        );
1.563     raeburn  8844:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   8845:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  8846: 
                   8847:     my @srchins = ('crs','dom','alc','instd');
                   8848: 
                   8849:     foreach my $option (@srchins) {
                   8850:         # FIXME 'alc' option unavailable until 
                   8851:         #       loncreateuser::print_user_query_page()
                   8852:         #       has been completed.
                   8853:         next if ($option eq 'alc');
1.880     raeburn  8854:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  8855:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  8856:         if ($curr_selected{'srchin'} eq $option) {
                   8857:             $srchinsel .= ' 
                   8858:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8859:         } else {
                   8860:             $srchinsel .= '
                   8861:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8862:         }
1.555     raeburn  8863:     }
1.563     raeburn  8864:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  8865: 
                   8866:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  8867:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  8868:         if ($curr_selected{'srchby'} eq $option) {
                   8869:             $srchbysel .= '
                   8870:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8871:         } else {
                   8872:             $srchbysel .= '
                   8873:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8874:          }
                   8875:     }
                   8876:     $srchbysel .= "\n  </select>\n";
                   8877: 
                   8878:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  8879:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  8880:         if ($curr_selected{'srchtype'} eq $option) {
                   8881:             $srchtypesel .= '
                   8882:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8883:         } else {
                   8884:             $srchtypesel .= '
                   8885:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8886:         }
                   8887:     }
                   8888:     $srchtypesel .= "\n  </select>\n";
                   8889: 
1.558     albertel 8890:     my ($newuserscript,$new_user_create);
1.994     raeburn  8891:     my $context_dom = $env{'request.role.domain'};
                   8892:     if ($context eq 'requestcrs') {
                   8893:         if ($env{'form.coursedom'} ne '') { 
                   8894:             $context_dom = $env{'form.coursedom'};
                   8895:         }
                   8896:     }
1.556     raeburn  8897:     if ($forcenewuser) {
1.576     raeburn  8898:         if (ref($srch) eq 'HASH') {
1.994     raeburn  8899:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  8900:                 if ($cancreate) {
                   8901:                     $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>';
                   8902:                 } else {
1.799     bisitz   8903:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  8904:                     my %usertypetext = (
                   8905:                         official   => 'institutional',
                   8906:                         unofficial => 'non-institutional',
                   8907:                     );
1.799     bisitz   8908:                     $new_user_create = '<p class="LC_warning">'
                   8909:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   8910:                                       .' '
                   8911:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   8912:                                           ,'<a href="'.$helplink.'">','</a>')
                   8913:                                       .'</p><br />';
1.627     raeburn  8914:                 }
1.576     raeburn  8915:             }
                   8916:         }
                   8917: 
1.556     raeburn  8918:         $newuserscript = <<"ENDSCRIPT";
                   8919: 
1.570     raeburn  8920: function setSearch(createnew,callingForm) {
1.556     raeburn  8921:     if (createnew == 1) {
1.570     raeburn  8922:         for (var i=0; i<callingForm.srchby.length; i++) {
                   8923:             if (callingForm.srchby.options[i].value == 'uname') {
                   8924:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  8925:             }
                   8926:         }
1.570     raeburn  8927:         for (var i=0; i<callingForm.srchin.length; i++) {
                   8928:             if ( callingForm.srchin.options[i].value == 'dom') {
                   8929: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  8930:             }
                   8931:         }
1.570     raeburn  8932:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   8933:             if (callingForm.srchtype.options[i].value == 'exact') {
                   8934:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  8935:             }
                   8936:         }
1.570     raeburn  8937:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  8938:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  8939:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  8940:             }
                   8941:         }
                   8942:     }
                   8943: }
                   8944: ENDSCRIPT
1.558     albertel 8945: 
1.556     raeburn  8946:     }
                   8947: 
1.555     raeburn  8948:     my $output = <<"END_BLOCK";
1.556     raeburn  8949: <script type="text/javascript">
1.824     bisitz   8950: // <![CDATA[
1.570     raeburn  8951: function validateEntry(callingForm) {
1.558     albertel 8952: 
1.556     raeburn  8953:     var checkok = 1;
1.558     albertel 8954:     var srchin;
1.570     raeburn  8955:     for (var i=0; i<callingForm.srchin.length; i++) {
                   8956: 	if ( callingForm.srchin[i].checked ) {
                   8957: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 8958: 	}
                   8959:     }
                   8960: 
1.570     raeburn  8961:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   8962:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   8963:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   8964:     var srchterm =  callingForm.srchterm.value;
                   8965:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  8966:     var msg = "";
                   8967: 
                   8968:     if (srchterm == "") {
                   8969:         checkok = 0;
1.571     raeburn  8970:         msg += "$lt{'youm'}\\n";
1.556     raeburn  8971:     }
                   8972: 
1.569     raeburn  8973:     if (srchtype== 'begins') {
                   8974:         if (srchterm.length < 2) {
                   8975:             checkok = 0;
1.571     raeburn  8976:             msg += "$lt{'thte'}\\n";
1.569     raeburn  8977:         }
                   8978:     }
                   8979: 
1.556     raeburn  8980:     if (srchtype== 'contains') {
                   8981:         if (srchterm.length < 3) {
                   8982:             checkok = 0;
1.571     raeburn  8983:             msg += "$lt{'thet'}\\n";
1.556     raeburn  8984:         }
                   8985:     }
                   8986:     if (srchin == 'instd') {
                   8987:         if (srchdomain == '') {
                   8988:             checkok = 0;
1.571     raeburn  8989:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  8990:         }
                   8991:     }
                   8992:     if (srchin == 'dom') {
                   8993:         if (srchdomain == '') {
                   8994:             checkok = 0;
1.571     raeburn  8995:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  8996:         }
                   8997:     }
                   8998:     if (srchby == 'lastfirst') {
                   8999:         if (srchterm.indexOf(",") == -1) {
                   9000:             checkok = 0;
1.571     raeburn  9001:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9002:         }
                   9003:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9004:             checkok = 0;
1.571     raeburn  9005:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9006:         }
                   9007:     }
                   9008:     if (checkok == 0) {
1.571     raeburn  9009:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9010:         return;
                   9011:     }
                   9012:     if (checkok == 1) {
1.570     raeburn  9013:         callingForm.submit();
1.556     raeburn  9014:     }
                   9015: }
                   9016: 
                   9017: $newuserscript
                   9018: 
1.824     bisitz   9019: // ]]>
1.556     raeburn  9020: </script>
1.558     albertel 9021: 
                   9022: $new_user_create
                   9023: 
1.555     raeburn  9024: END_BLOCK
1.558     albertel 9025: 
1.876     raeburn  9026:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9027:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9028:                $domform.
                   9029:                &Apache::lonhtmlcommon::row_closure().
                   9030:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9031:                $srchbysel.
                   9032:                $srchtypesel. 
                   9033:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9034:                $srchinsel.
                   9035:                &Apache::lonhtmlcommon::row_closure(1). 
                   9036:                &Apache::lonhtmlcommon::end_pick_box().
                   9037:                '<br />';
1.555     raeburn  9038:     return $output;
                   9039: }
                   9040: 
1.612     raeburn  9041: sub user_rule_check {
1.615     raeburn  9042:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9043:     my $response;
                   9044:     if (ref($usershash) eq 'HASH') {
                   9045:         foreach my $user (keys(%{$usershash})) {
                   9046:             my ($uname,$udom) = split(/:/,$user);
                   9047:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9048:             my ($id,$newuser);
1.612     raeburn  9049:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9050:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9051:                 $id = $usershash->{$user}->{'id'};
                   9052:             }
                   9053:             my $inst_response;
                   9054:             if (ref($checks) eq 'HASH') {
                   9055:                 if (defined($checks->{'username'})) {
1.615     raeburn  9056:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9057:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9058:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9059:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9060:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9061:                 }
1.615     raeburn  9062:             } else {
                   9063:                 ($inst_response,%{$inst_results->{$user}}) =
                   9064:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9065:                 return;
1.612     raeburn  9066:             }
1.615     raeburn  9067:             if (!$got_rules->{$udom}) {
1.612     raeburn  9068:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9069:                                                   ['usercreation'],$udom);
                   9070:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9071:                     foreach my $item ('username','id') {
1.612     raeburn  9072:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9073:                             $$curr_rules{$udom}{$item} = 
                   9074:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9075:                         }
                   9076:                     }
                   9077:                 }
1.615     raeburn  9078:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9079:             }
1.612     raeburn  9080:             foreach my $item (keys(%{$checks})) {
                   9081:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9082:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9083:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9084:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9085:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9086:                                 if ($rule_check{$rule}) {
                   9087:                                     $$rulematch{$user}{$item} = $rule;
                   9088:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9089:                                         if (ref($inst_results) eq 'HASH') {
                   9090:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9091:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9092:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9093:                                                 }
1.612     raeburn  9094:                                             }
                   9095:                                         }
1.615     raeburn  9096:                                     }
                   9097:                                     last;
1.585     raeburn  9098:                                 }
                   9099:                             }
                   9100:                         }
                   9101:                     }
                   9102:                 }
                   9103:             }
                   9104:         }
                   9105:     }
1.612     raeburn  9106:     return;
                   9107: }
                   9108: 
                   9109: sub user_rule_formats {
                   9110:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9111:     my %text = ( 
                   9112:                  'username' => 'Usernames',
                   9113:                  'id'       => 'IDs',
                   9114:                );
                   9115:     my $output;
                   9116:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9117:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9118:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9119:             $output = '<br />'.
                   9120:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9121:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9122:                       ' <ul>';
1.612     raeburn  9123:             foreach my $rule (@{$ruleorder}) {
                   9124:                 if (ref($curr_rules) eq 'ARRAY') {
                   9125:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9126:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9127:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9128:                                         $rules->{$rule}{'desc'}.'</li>';
                   9129:                         }
                   9130:                     }
                   9131:                 }
                   9132:             }
                   9133:             $output .= '</ul>';
                   9134:         }
                   9135:     }
                   9136:     return $output;
                   9137: }
                   9138: 
                   9139: sub instrule_disallow_msg {
1.615     raeburn  9140:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9141:     my $response;
                   9142:     my %text = (
                   9143:                   item   => 'username',
                   9144:                   items  => 'usernames',
                   9145:                   match  => 'matches',
                   9146:                   do     => 'does',
                   9147:                   action => 'a username',
                   9148:                   one    => 'one',
                   9149:                );
                   9150:     if ($count > 1) {
                   9151:         $text{'item'} = 'usernames';
                   9152:         $text{'match'} ='match';
                   9153:         $text{'do'} = 'do';
                   9154:         $text{'action'} = 'usernames',
                   9155:         $text{'one'} = 'ones';
                   9156:     }
                   9157:     if ($checkitem eq 'id') {
                   9158:         $text{'items'} = 'IDs';
                   9159:         $text{'item'} = 'ID';
                   9160:         $text{'action'} = 'an ID';
1.615     raeburn  9161:         if ($count > 1) {
                   9162:             $text{'item'} = 'IDs';
                   9163:             $text{'action'} = 'IDs';
                   9164:         }
1.612     raeburn  9165:     }
1.674     bisitz   9166:     $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  9167:     if ($mode eq 'upload') {
                   9168:         if ($checkitem eq 'username') {
                   9169:             $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'}.");
                   9170:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9171:             $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  9172:         }
1.669     raeburn  9173:     } elsif ($mode eq 'selfcreate') {
                   9174:         if ($checkitem eq 'id') {
                   9175:             $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.");
                   9176:         }
1.615     raeburn  9177:     } else {
                   9178:         if ($checkitem eq 'username') {
                   9179:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9180:         } elsif ($checkitem eq 'id') {
                   9181:             $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.");
                   9182:         }
1.612     raeburn  9183:     }
                   9184:     return $response;
1.585     raeburn  9185: }
                   9186: 
1.624     raeburn  9187: sub personal_data_fieldtitles {
                   9188:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9189:                         id => 'Student/Employee ID',
                   9190:                         permanentemail => 'E-mail address',
                   9191:                         lastname => 'Last Name',
                   9192:                         firstname => 'First Name',
                   9193:                         middlename => 'Middle Name',
                   9194:                         generation => 'Generation',
                   9195:                         gen => 'Generation',
1.765     raeburn  9196:                         inststatus => 'Affiliation',
1.624     raeburn  9197:                    );
                   9198:     return %fieldtitles;
                   9199: }
                   9200: 
1.642     raeburn  9201: sub sorted_inst_types {
                   9202:     my ($dom) = @_;
                   9203:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9204:     my $othertitle = &mt('All users');
                   9205:     if ($env{'request.course.id'}) {
1.668     raeburn  9206:         $othertitle  = &mt('Any users');
1.642     raeburn  9207:     }
                   9208:     my @types;
                   9209:     if (ref($order) eq 'ARRAY') {
                   9210:         @types = @{$order};
                   9211:     }
                   9212:     if (@types == 0) {
                   9213:         if (ref($usertypes) eq 'HASH') {
                   9214:             @types = sort(keys(%{$usertypes}));
                   9215:         }
                   9216:     }
                   9217:     if (keys(%{$usertypes}) > 0) {
                   9218:         $othertitle = &mt('Other users');
                   9219:     }
                   9220:     return ($othertitle,$usertypes,\@types);
                   9221: }
                   9222: 
1.645     raeburn  9223: sub get_institutional_codes {
                   9224:     my ($settings,$allcourses,$LC_code) = @_;
                   9225: # Get complete list of course sections to update
                   9226:     my @currsections = ();
                   9227:     my @currxlists = ();
                   9228:     my $coursecode = $$settings{'internal.coursecode'};
                   9229: 
                   9230:     if ($$settings{'internal.sectionnums'} ne '') {
                   9231:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9232:     }
                   9233: 
                   9234:     if ($$settings{'internal.crosslistings'} ne '') {
                   9235:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9236:     }
                   9237: 
                   9238:     if (@currxlists > 0) {
                   9239:         foreach (@currxlists) {
                   9240:             if (m/^([^:]+):(\w*)$/) {
                   9241:                 unless (grep/^$1$/,@{$allcourses}) {
                   9242:                     push @{$allcourses},$1;
                   9243:                     $$LC_code{$1} = $2;
                   9244:                 }
                   9245:             }
                   9246:         }
                   9247:     }
                   9248:  
                   9249:     if (@currsections > 0) {
                   9250:         foreach (@currsections) {
                   9251:             if (m/^(\w+):(\w*)$/) {
                   9252:                 my $sec = $coursecode.$1;
                   9253:                 my $lc_sec = $2;
                   9254:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9255:                     push @{$allcourses},$sec;
                   9256:                     $$LC_code{$sec} = $lc_sec;
                   9257:                 }
                   9258:             }
                   9259:         }
                   9260:     }
                   9261:     return;
                   9262: }
                   9263: 
1.971     raeburn  9264: sub get_standard_codeitems {
                   9265:     return ('Year','Semester','Department','Number','Section');
                   9266: }
                   9267: 
1.112     bowersj2 9268: =pod
                   9269: 
1.780     raeburn  9270: =head1 Slot Helpers
                   9271: 
                   9272: =over 4
                   9273: 
                   9274: =item * sorted_slots()
                   9275: 
1.1040    raeburn  9276: Sorts an array of slot names in order of an optional sort key,
                   9277: default sort is by slot start time (earliest first). 
1.780     raeburn  9278: 
                   9279: Inputs:
                   9280: 
                   9281: =over 4
                   9282: 
                   9283: slotsarr  - Reference to array of unsorted slot names.
                   9284: 
                   9285: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9286: 
1.1040    raeburn  9287: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9288: 
1.549     albertel 9289: =back
                   9290: 
1.780     raeburn  9291: Returns:
                   9292: 
                   9293: =over 4
                   9294: 
1.1040    raeburn  9295: sorted   - An array of slot names sorted by a specified sort key 
                   9296:            (default sort key is start time of the slot).
1.780     raeburn  9297: 
                   9298: =back
                   9299: 
                   9300: =cut
                   9301: 
                   9302: 
                   9303: sub sorted_slots {
1.1040    raeburn  9304:     my ($slotsarr,$slots,$sortkey) = @_;
                   9305:     if ($sortkey eq '') {
                   9306:         $sortkey = 'starttime';
                   9307:     }
1.780     raeburn  9308:     my @sorted;
                   9309:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9310:         @sorted =
                   9311:             sort {
                   9312:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9313:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9314:                      }
                   9315:                      if (ref($slots->{$a})) { return -1;}
                   9316:                      if (ref($slots->{$b})) { return 1;}
                   9317:                      return 0;
                   9318:                  } @{$slotsarr};
                   9319:     }
                   9320:     return @sorted;
                   9321: }
                   9322: 
1.1040    raeburn  9323: =pod
                   9324: 
                   9325: =item * get_future_slots()
                   9326: 
                   9327: Inputs:
                   9328: 
                   9329: =over 4
                   9330: 
                   9331: cnum - course number
                   9332: 
                   9333: cdom - course domain
                   9334: 
                   9335: now - current UNIX time
                   9336: 
                   9337: symb - optional symb
                   9338: 
                   9339: =back
                   9340: 
                   9341: Returns:
                   9342: 
                   9343: =over 4
                   9344: 
                   9345: sorted_reservable - ref to array of student_schedulable slots currently 
                   9346:                     reservable, ordered by end date of reservation period.
                   9347: 
                   9348: reservable_now - ref to hash of student_schedulable slots currently
                   9349:                  reservable.
                   9350: 
                   9351:     Keys in inner hash are:
                   9352:     (a) symb: either blank or symb to which slot use is restricted.
                   9353:     (b) endreserve: end date of reservation period. 
                   9354: 
                   9355: sorted_future - ref to array of student_schedulable slots reservable in
                   9356:                 the future, ordered by start date of reservation period.
                   9357: 
                   9358: future_reservable - ref to hash of student_schedulable slots reservable
                   9359:                     in the future.
                   9360: 
                   9361:     Keys in inner hash are:
                   9362:     (a) symb: either blank or symb to which slot use is restricted.
                   9363:     (b) startreserve:  start date of reservation period.
                   9364: 
                   9365: =back
                   9366: 
                   9367: =cut
                   9368: 
                   9369: sub get_future_slots {
                   9370:     my ($cnum,$cdom,$now,$symb) = @_;
                   9371:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9372:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9373:     foreach my $slot (keys(%slots)) {
                   9374:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9375:         if ($symb) {
                   9376:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9377:                      ($slots{$slot}->{'symb'} ne $symb));
                   9378:         }
                   9379:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9380:             ($slots{$slot}->{'endtime'} > $now)) {
                   9381:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9382:                 my $userallowed = 0;
                   9383:                 if ($slots{$slot}->{'allowedsections'}) {
                   9384:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9385:                     if (!defined($env{'request.role.sec'})
                   9386:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9387:                         $userallowed=1;
                   9388:                     } else {
                   9389:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9390:                             $userallowed=1;
                   9391:                         }
                   9392:                     }
                   9393:                     unless ($userallowed) {
                   9394:                         if (defined($env{'request.course.groups'})) {
                   9395:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9396:                             foreach my $group (@groups) {
                   9397:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9398:                                     $userallowed=1;
                   9399:                                     last;
                   9400:                                 }
                   9401:                             }
                   9402:                         }
                   9403:                     }
                   9404:                 }
                   9405:                 if ($slots{$slot}->{'allowedusers'}) {
                   9406:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9407:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9408:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9409:                         $userallowed = 1;
                   9410:                     }
                   9411:                 }
                   9412:                 next unless($userallowed);
                   9413:             }
                   9414:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9415:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9416:             my $symb = $slots{$slot}->{'symb'};
                   9417:             if (($startreserve < $now) &&
                   9418:                 (!$endreserve || $endreserve > $now)) {
                   9419:                 my $lastres = $endreserve;
                   9420:                 if (!$lastres) {
                   9421:                     $lastres = $slots{$slot}->{'starttime'};
                   9422:                 }
                   9423:                 $reservable_now{$slot} = {
                   9424:                                            symb       => $symb,
                   9425:                                            endreserve => $lastres
                   9426:                                          };
                   9427:             } elsif (($startreserve > $now) &&
                   9428:                      (!$endreserve || $endreserve > $startreserve)) {
                   9429:                 $future_reservable{$slot} = {
                   9430:                                               symb         => $symb,
                   9431:                                               startreserve => $startreserve
                   9432:                                             };
                   9433:             }
                   9434:         }
                   9435:     }
                   9436:     my @unsorted_reservable = keys(%reservable_now);
                   9437:     if (@unsorted_reservable > 0) {
                   9438:         @sorted_reservable = 
                   9439:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9440:     }
                   9441:     my @unsorted_future = keys(%future_reservable);
                   9442:     if (@unsorted_future > 0) {
                   9443:         @sorted_future =
                   9444:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9445:     }
                   9446:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9447: }
1.780     raeburn  9448: 
                   9449: =pod
                   9450: 
1.1057    foxr     9451: =back
                   9452: 
1.549     albertel 9453: =head1 HTTP Helpers
                   9454: 
                   9455: =over 4
                   9456: 
1.648     raeburn  9457: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9458: 
1.258     albertel 9459: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9460: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9461: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9462: 
                   9463: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9464: $possible_names is an ref to an array of form element names.  As an example:
                   9465: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9466: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9467: 
                   9468: =cut
1.1       albertel 9469: 
1.6       albertel 9470: sub get_unprocessed_cgi {
1.25      albertel 9471:   my ($query,$possible_names)= @_;
1.26      matthew  9472:   # $Apache::lonxml::debug=1;
1.356     albertel 9473:   foreach my $pair (split(/&/,$query)) {
                   9474:     my ($name, $value) = split(/=/,$pair);
1.369     www      9475:     $name = &unescape($name);
1.25      albertel 9476:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9477:       $value =~ tr/+/ /;
                   9478:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9479:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9480:     }
1.16      harris41 9481:   }
1.6       albertel 9482: }
                   9483: 
1.112     bowersj2 9484: =pod
                   9485: 
1.648     raeburn  9486: =item * &cacheheader() 
1.112     bowersj2 9487: 
                   9488: returns cache-controlling header code
                   9489: 
                   9490: =cut
                   9491: 
1.7       albertel 9492: sub cacheheader {
1.258     albertel 9493:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9494:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9495:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9496:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9497:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9498:     return $output;
1.7       albertel 9499: }
                   9500: 
1.112     bowersj2 9501: =pod
                   9502: 
1.648     raeburn  9503: =item * &no_cache($r) 
1.112     bowersj2 9504: 
                   9505: specifies header code to not have cache
                   9506: 
                   9507: =cut
                   9508: 
1.9       albertel 9509: sub no_cache {
1.216     albertel 9510:     my ($r) = @_;
                   9511:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9512: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9513:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9514:     $r->no_cache(1);
                   9515:     $r->header_out("Expires" => $date);
                   9516:     $r->header_out("Pragma" => "no-cache");
1.123     www      9517: }
                   9518: 
                   9519: sub content_type {
1.181     albertel 9520:     my ($r,$type,$charset) = @_;
1.299     foxr     9521:     if ($r) {
                   9522: 	#  Note that printout.pl calls this with undef for $r.
                   9523: 	&no_cache($r);
                   9524:     }
1.258     albertel 9525:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9526:     unless ($charset) {
                   9527: 	$charset=&Apache::lonlocal::current_encoding;
                   9528:     }
                   9529:     if ($charset) { $type.='; charset='.$charset; }
                   9530:     if ($r) {
                   9531: 	$r->content_type($type);
                   9532:     } else {
                   9533: 	print("Content-type: $type\n\n");
                   9534:     }
1.9       albertel 9535: }
1.25      albertel 9536: 
1.112     bowersj2 9537: =pod
                   9538: 
1.648     raeburn  9539: =item * &add_to_env($name,$value) 
1.112     bowersj2 9540: 
1.258     albertel 9541: adds $name to the %env hash with value
1.112     bowersj2 9542: $value, if $name already exists, the entry is converted to an array
                   9543: reference and $value is added to the array.
                   9544: 
                   9545: =cut
                   9546: 
1.25      albertel 9547: sub add_to_env {
                   9548:   my ($name,$value)=@_;
1.258     albertel 9549:   if (defined($env{$name})) {
                   9550:     if (ref($env{$name})) {
1.25      albertel 9551:       #already have multiple values
1.258     albertel 9552:       push(@{ $env{$name} },$value);
1.25      albertel 9553:     } else {
                   9554:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9555:       my $first=$env{$name};
                   9556:       undef($env{$name});
                   9557:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9558:     }
                   9559:   } else {
1.258     albertel 9560:     $env{$name}=$value;
1.25      albertel 9561:   }
1.31      albertel 9562: }
1.149     albertel 9563: 
                   9564: =pod
                   9565: 
1.648     raeburn  9566: =item * &get_env_multiple($name) 
1.149     albertel 9567: 
1.258     albertel 9568: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9569: values may be defined and end up as an array ref.
                   9570: 
                   9571: returns an array of values
                   9572: 
                   9573: =cut
                   9574: 
                   9575: sub get_env_multiple {
                   9576:     my ($name) = @_;
                   9577:     my @values;
1.258     albertel 9578:     if (defined($env{$name})) {
1.149     albertel 9579:         # exists is it an array
1.258     albertel 9580:         if (ref($env{$name})) {
                   9581:             @values=@{ $env{$name} };
1.149     albertel 9582:         } else {
1.258     albertel 9583:             $values[0]=$env{$name};
1.149     albertel 9584:         }
                   9585:     }
                   9586:     return(@values);
                   9587: }
                   9588: 
1.660     raeburn  9589: sub ask_for_embedded_content {
                   9590:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9591:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  9592:         %currsubfile,%unused,$rem);
1.1071    raeburn  9593:     my $counter = 0;
                   9594:     my $numnew = 0;
1.987     raeburn  9595:     my $numremref = 0;
                   9596:     my $numinvalid = 0;
                   9597:     my $numpathchg = 0;
                   9598:     my $numexisting = 0;
1.1071    raeburn  9599:     my $numunused = 0;
                   9600:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
                   9601:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
                   9602:     my $heading = &mt('Upload embedded files');
                   9603:     my $buttontext = &mt('Upload');
                   9604: 
1.1123    raeburn  9605:     my ($navmap,$cdom,$cnum);
1.1085    raeburn  9606:     if ($env{'request.course.id'}) {
1.1123    raeburn  9607:         if ($actionurl eq '/adm/dependencies') {
                   9608:             $navmap = Apache::lonnavmaps::navmap->new();
                   9609:         }
                   9610:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9611:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  9612:     }
1.1123    raeburn  9613:     if (($actionurl eq '/adm/portfolio') || 
                   9614:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  9615:         my $current_path='/';
                   9616:         if ($env{'form.currentpath'}) {
                   9617:             $current_path = $env{'form.currentpath'};
                   9618:         }
                   9619:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  9620:             $udom = $cdom;
                   9621:             $uname = $cnum;
1.984     raeburn  9622:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9623:         } else {
                   9624:             $udom = $env{'user.domain'};
                   9625:             $uname = $env{'user.name'};
                   9626:             $url = '/userfiles/portfolio';
                   9627:         }
1.987     raeburn  9628:         $toplevel = $url.'/';
1.984     raeburn  9629:         $url .= $current_path;
                   9630:         $getpropath = 1;
1.987     raeburn  9631:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9632:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9633:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9634:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9635:         $toplevel = $url;
1.984     raeburn  9636:         if ($rest ne '') {
1.987     raeburn  9637:             $url .= $rest;
                   9638:         }
                   9639:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9640:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9641:             $url = $args->{'docs_url'};
                   9642:             $toplevel = $url;
1.1084    raeburn  9643:             if ($args->{'context'} eq 'paste') {
                   9644:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9645:                 ($path) = 
                   9646:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9647:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9648:                 $fileloc =~ s{^/}{};
                   9649:             }
1.1071    raeburn  9650:         }
1.1084    raeburn  9651:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  9652:         if ($env{'request.course.id'} ne '') {
                   9653:             if (ref($args) eq 'HASH') {
                   9654:                 $url = $args->{'docs_url'};
                   9655:                 $title = $args->{'docs_title'};
1.1126    raeburn  9656:                 $toplevel = $url; 
                   9657:                 unless ($toplevel =~ m{^/}) {
                   9658:                     $toplevel = "/$url";
                   9659:                 }
1.1085    raeburn  9660:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  9661:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   9662:                     $path = $1;
                   9663:                 } else {
                   9664:                     ($path) =
                   9665:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9666:                 }
1.1071    raeburn  9667:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9668:                 $fileloc =~ s{^/}{};
                   9669:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9670:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9671:             }
1.987     raeburn  9672:         }
1.1123    raeburn  9673:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9674:         $udom = $cdom;
                   9675:         $uname = $cnum;
                   9676:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   9677:         $toplevel = $url;
                   9678:         $path = $url;
                   9679:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   9680:         $fileloc =~ s{^/}{};
1.987     raeburn  9681:     }
1.1126    raeburn  9682:     foreach my $file (keys(%{$allfiles})) {
                   9683:         my $embed_file;
                   9684:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   9685:             $embed_file = $1;
                   9686:         } else {
                   9687:             $embed_file = $file;
                   9688:         }
1.987     raeburn  9689:         my $absolutepath;
                   9690:         if ($embed_file =~ m{^\w+://}) {
                   9691:             $newfiles{$embed_file} = 1;
                   9692:             $mapping{$embed_file} = $embed_file;
                   9693:         } else {
                   9694:             if ($embed_file =~ m{^/}) {
                   9695:                 $absolutepath = $embed_file;
                   9696:                 $embed_file =~ s{^(/+)}{};
                   9697:             }
                   9698:             if ($embed_file =~ m{/}) {
                   9699:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
                   9700:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9701:                 my $item = $fname;
                   9702:                 if ($path ne '') {
                   9703:                     $item = $path.'/'.$fname;
                   9704:                     $subdependencies{$path}{$fname} = 1;
                   9705:                 } else {
                   9706:                     $dependencies{$item} = 1;
                   9707:                 }
                   9708:                 if ($absolutepath) {
                   9709:                     $mapping{$item} = $absolutepath;
                   9710:                 } else {
                   9711:                     $mapping{$item} = $embed_file;
                   9712:                 }
                   9713:             } else {
                   9714:                 $dependencies{$embed_file} = 1;
                   9715:                 if ($absolutepath) {
                   9716:                     $mapping{$embed_file} = $absolutepath;
                   9717:                 } else {
                   9718:                     $mapping{$embed_file} = $embed_file;
                   9719:                 }
                   9720:             }
1.984     raeburn  9721:         }
                   9722:     }
1.1071    raeburn  9723:     my $dirptr = 16384;
1.984     raeburn  9724:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9725:         $currsubfile{$path} = {};
1.1123    raeburn  9726:         if (($actionurl eq '/adm/portfolio') || 
                   9727:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9728:             my ($sublistref,$listerror) =
                   9729:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9730:             if (ref($sublistref) eq 'ARRAY') {
                   9731:                 foreach my $line (@{$sublistref}) {
                   9732:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9733:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9734:                 }
1.984     raeburn  9735:             }
1.987     raeburn  9736:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9737:             if (opendir(my $dir,$url.'/'.$path)) {
                   9738:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9739:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9740:             }
1.1084    raeburn  9741:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9742:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  9743:                   ($args->{'context'} eq 'paste')) ||
                   9744:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9745:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  9746:                 my $dir;
                   9747:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9748:                     $dir = $fileloc;
                   9749:                 } else {
                   9750:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9751:                 }
1.1071    raeburn  9752:                 if ($dir ne '') {
                   9753:                     my ($sublistref,$listerror) =
                   9754:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9755:                     if (ref($sublistref) eq 'ARRAY') {
                   9756:                         foreach my $line (@{$sublistref}) {
                   9757:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9758:                                 undef,$mtime)=split(/\&/,$line,12);
                   9759:                             unless (($testdir&$dirptr) ||
                   9760:                                     ($file_name =~ /^\.\.?$/)) {
                   9761:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9762:                             }
                   9763:                         }
                   9764:                     }
                   9765:                 }
1.984     raeburn  9766:             }
                   9767:         }
                   9768:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9769:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9770:                 my $item = $path.'/'.$file;
                   9771:                 unless ($mapping{$item} eq $item) {
                   9772:                     $pathchanges{$item} = 1;
                   9773:                 }
                   9774:                 $existing{$item} = 1;
                   9775:                 $numexisting ++;
                   9776:             } else {
                   9777:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9778:             }
                   9779:         }
1.1071    raeburn  9780:         if ($actionurl eq '/adm/dependencies') {
                   9781:             foreach my $path (keys(%currsubfile)) {
                   9782:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9783:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9784:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  9785:                              next if (($rem ne '') &&
                   9786:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9787:                                        (ref($navmap) &&
                   9788:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9789:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9790:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9791:                              $unused{$path.'/'.$file} = 1; 
                   9792:                          }
                   9793:                     }
                   9794:                 }
                   9795:             }
                   9796:         }
1.984     raeburn  9797:     }
1.987     raeburn  9798:     my %currfile;
1.1123    raeburn  9799:     if (($actionurl eq '/adm/portfolio') ||
                   9800:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9801:         my ($dirlistref,$listerror) =
                   9802:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9803:         if (ref($dirlistref) eq 'ARRAY') {
                   9804:             foreach my $line (@{$dirlistref}) {
                   9805:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   9806:                 $currfile{$file_name} = 1;
                   9807:             }
1.984     raeburn  9808:         }
1.987     raeburn  9809:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9810:         if (opendir(my $dir,$url)) {
1.987     raeburn  9811:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  9812:             map {$currfile{$_} = 1;} @dir_list;
                   9813:         }
1.1084    raeburn  9814:     } elsif (($actionurl eq '/adm/dependencies') ||
                   9815:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  9816:               ($args->{'context'} eq 'paste')) ||
                   9817:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9818:         if ($env{'request.course.id'} ne '') {
                   9819:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9820:             if ($dir ne '') {
                   9821:                 my ($dirlistref,$listerror) =
                   9822:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   9823:                 if (ref($dirlistref) eq 'ARRAY') {
                   9824:                     foreach my $line (@{$dirlistref}) {
                   9825:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   9826:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   9827:                         unless (($testdir&$dirptr) ||
                   9828:                                 ($file_name =~ /^\.\.?$/)) {
                   9829:                             $currfile{$file_name} = [$size,$mtime];
                   9830:                         }
                   9831:                     }
                   9832:                 }
                   9833:             }
                   9834:         }
1.984     raeburn  9835:     }
                   9836:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  9837:         if (exists($currfile{$file})) {
1.987     raeburn  9838:             unless ($mapping{$file} eq $file) {
                   9839:                 $pathchanges{$file} = 1;
                   9840:             }
                   9841:             $existing{$file} = 1;
                   9842:             $numexisting ++;
                   9843:         } else {
1.984     raeburn  9844:             $newfiles{$file} = 1;
                   9845:         }
                   9846:     }
1.1071    raeburn  9847:     foreach my $file (keys(%currfile)) {
                   9848:         unless (($file eq $filename) ||
                   9849:                 ($file eq $filename.'.bak') ||
                   9850:                 ($dependencies{$file})) {
1.1085    raeburn  9851:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  9852:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   9853:                     next if (($rem ne '') &&
                   9854:                              (($env{"httpref.$rem".$file} ne '') ||
                   9855:                               (ref($navmap) &&
                   9856:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   9857:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9858:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   9859:                 }
1.1085    raeburn  9860:             }
1.1071    raeburn  9861:             $unused{$file} = 1;
                   9862:         }
                   9863:     }
1.1084    raeburn  9864:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9865:         ($args->{'context'} eq 'paste')) {
                   9866:         $counter = scalar(keys(%existing));
                   9867:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  9868:         return ($output,$counter,$numpathchg,\%existing);
                   9869:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   9870:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   9871:         $counter = scalar(keys(%existing));
                   9872:         $numpathchg = scalar(keys(%pathchanges));
                   9873:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  9874:     }
1.984     raeburn  9875:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  9876:         if ($actionurl eq '/adm/dependencies') {
                   9877:             next if ($embed_file =~ m{^\w+://});
                   9878:         }
1.660     raeburn  9879:         $upload_output .= &start_data_table_row().
1.1123    raeburn  9880:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  9881:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  9882:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  9883:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   9884:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  9885:         }
1.1123    raeburn  9886:         $upload_output .= '</td>';
1.1071    raeburn  9887:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  9888:             $upload_output.='<td align="right">'.
                   9889:                             '<span class="LC_info LC_fontsize_medium">'.
                   9890:                             &mt("URL points to web address").'</span>';
1.987     raeburn  9891:             $numremref++;
1.660     raeburn  9892:         } elsif ($args->{'error_on_invalid_names'}
                   9893:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  9894:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   9895:                             &mt('Invalid characters').'</span>';
1.987     raeburn  9896:             $numinvalid++;
1.660     raeburn  9897:         } else {
1.1123    raeburn  9898:             $upload_output .= '<td>'.
                   9899:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  9900:                                                      $embed_file,\%mapping,
1.1071    raeburn  9901:                                                      $allfiles,$codebase,'upload');
                   9902:             $counter ++;
                   9903:             $numnew ++;
1.987     raeburn  9904:         }
                   9905:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   9906:     }
                   9907:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  9908:         if ($actionurl eq '/adm/dependencies') {
                   9909:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   9910:             $modify_output .= &start_data_table_row().
                   9911:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   9912:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   9913:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   9914:                               '<td>'.$size.'</td>'.
                   9915:                               '<td>'.$mtime.'</td>'.
                   9916:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   9917:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   9918:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   9919:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   9920:                               &embedded_file_element('upload_embedded',$counter,
                   9921:                                                      $embed_file,\%mapping,
                   9922:                                                      $allfiles,$codebase,'modify').
                   9923:                               '</div></td>'.
                   9924:                               &end_data_table_row()."\n";
                   9925:             $counter ++;
                   9926:         } else {
                   9927:             $upload_output .= &start_data_table_row().
1.1123    raeburn  9928:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   9929:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   9930:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  9931:                               &Apache::loncommon::end_data_table_row()."\n";
                   9932:         }
                   9933:     }
                   9934:     my $delidx = $counter;
                   9935:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   9936:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   9937:         $delete_output .= &start_data_table_row().
                   9938:                           '<td><img src="'.&icon($oldfile).'" />'.
                   9939:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   9940:                           '<td>'.$size.'</td>'.
                   9941:                           '<td>'.$mtime.'</td>'.
                   9942:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   9943:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   9944:                           &embedded_file_element('upload_embedded',$delidx,
                   9945:                                                  $oldfile,\%mapping,$allfiles,
                   9946:                                                  $codebase,'delete').'</td>'.
                   9947:                           &end_data_table_row()."\n"; 
                   9948:         $numunused ++;
                   9949:         $delidx ++;
1.987     raeburn  9950:     }
                   9951:     if ($upload_output) {
                   9952:         $upload_output = &start_data_table().
                   9953:                          $upload_output.
                   9954:                          &end_data_table()."\n";
                   9955:     }
1.1071    raeburn  9956:     if ($modify_output) {
                   9957:         $modify_output = &start_data_table().
                   9958:                          &start_data_table_header_row().
                   9959:                          '<th>'.&mt('File').'</th>'.
                   9960:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9961:                          '<th>'.&mt('Modified').'</th>'.
                   9962:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   9963:                          &end_data_table_header_row().
                   9964:                          $modify_output.
                   9965:                          &end_data_table()."\n";
                   9966:     }
                   9967:     if ($delete_output) {
                   9968:         $delete_output = &start_data_table().
                   9969:                          &start_data_table_header_row().
                   9970:                          '<th>'.&mt('File').'</th>'.
                   9971:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9972:                          '<th>'.&mt('Modified').'</th>'.
                   9973:                          '<th>'.&mt('Delete?').'</th>'.
                   9974:                          &end_data_table_header_row().
                   9975:                          $delete_output.
                   9976:                          &end_data_table()."\n";
                   9977:     }
1.987     raeburn  9978:     my $applies = 0;
                   9979:     if ($numremref) {
                   9980:         $applies ++;
                   9981:     }
                   9982:     if ($numinvalid) {
                   9983:         $applies ++;
                   9984:     }
                   9985:     if ($numexisting) {
                   9986:         $applies ++;
                   9987:     }
1.1071    raeburn  9988:     if ($counter || $numunused) {
1.987     raeburn  9989:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   9990:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  9991:                   $state.'<h3>'.$heading.'</h3>'; 
                   9992:         if ($actionurl eq '/adm/dependencies') {
                   9993:             if ($numnew) {
                   9994:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   9995:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   9996:                            $upload_output.'<br />'."\n";
                   9997:             }
                   9998:             if ($numexisting) {
                   9999:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10000:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10001:                            $modify_output.'<br />'."\n";
                   10002:                            $buttontext = &mt('Save changes');
                   10003:             }
                   10004:             if ($numunused) {
                   10005:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10006:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10007:                            $delete_output.'<br />'."\n";
                   10008:                            $buttontext = &mt('Save changes');
                   10009:             }
                   10010:         } else {
                   10011:             $output .= $upload_output.'<br />'."\n";
                   10012:         }
                   10013:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10014:                    $counter.'" />'."\n";
                   10015:         if ($actionurl eq '/adm/dependencies') { 
                   10016:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10017:                        $numnew.'" />'."\n";
                   10018:         } elsif ($actionurl eq '') {
1.987     raeburn  10019:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10020:         }
                   10021:     } elsif ($applies) {
                   10022:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10023:         if ($applies > 1) {
                   10024:             $output .=  
1.1123    raeburn  10025:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10026:             if ($numremref) {
                   10027:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10028:             }
                   10029:             if ($numinvalid) {
                   10030:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10031:             }
                   10032:             if ($numexisting) {
                   10033:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10034:             }
                   10035:             $output .= '</ul><br />';
                   10036:         } elsif ($numremref) {
                   10037:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10038:         } elsif ($numinvalid) {
                   10039:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10040:         } elsif ($numexisting) {
                   10041:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10042:         }
                   10043:         $output .= $upload_output.'<br />';
                   10044:     }
                   10045:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10046:     $chgcount = $counter;
1.987     raeburn  10047:     if (keys(%pathchanges) > 0) {
                   10048:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10049:             if ($counter) {
1.987     raeburn  10050:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10051:                                                   $embed_file,\%mapping,
1.1071    raeburn  10052:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10053:             } else {
                   10054:                 $pathchange_output .= 
                   10055:                     &start_data_table_row().
                   10056:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10057:                     $chgcount.'" checked="checked" /></td>'.
                   10058:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10059:                     '<td>'.$embed_file.
                   10060:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10061:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10062:                     '</td>'.&end_data_table_row();
1.660     raeburn  10063:             }
1.987     raeburn  10064:             $numpathchg ++;
                   10065:             $chgcount ++;
1.660     raeburn  10066:         }
                   10067:     }
1.1127    raeburn  10068:     if (($counter) || ($numunused)) {
1.987     raeburn  10069:         if ($numpathchg) {
                   10070:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10071:                        $numpathchg.'" />'."\n";
                   10072:         }
                   10073:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10074:             ($actionurl eq '/adm/imsimport')) {
                   10075:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10076:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10077:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10078:         } elsif ($actionurl eq '/adm/dependencies') {
                   10079:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10080:         }
1.1123    raeburn  10081:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10082:     } elsif ($numpathchg) {
                   10083:         my %pathchange = ();
                   10084:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10085:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10086:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  10087:         }
1.987     raeburn  10088:     }
1.1071    raeburn  10089:     return ($output,$counter,$numpathchg);
1.987     raeburn  10090: }
                   10091: 
                   10092: sub embedded_file_element {
1.1071    raeburn  10093:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10094:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10095:                    (ref($codebase) eq 'HASH'));
                   10096:     my $output;
1.1071    raeburn  10097:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10098:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10099:     }
                   10100:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10101:                &escape($embed_file).'" />';
                   10102:     unless (($context eq 'upload_embedded') && 
                   10103:             ($mapping->{$embed_file} eq $embed_file)) {
                   10104:         $output .='
                   10105:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10106:     }
                   10107:     my $attrib;
                   10108:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10109:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10110:     }
                   10111:     $output .=
                   10112:         "\n\t\t".
                   10113:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10114:         $attrib.'" />';
                   10115:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10116:         $output .=
                   10117:             "\n\t\t".
                   10118:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10119:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10120:     }
1.987     raeburn  10121:     return $output;
1.660     raeburn  10122: }
                   10123: 
1.1071    raeburn  10124: sub get_dependency_details {
                   10125:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10126:     my ($size,$mtime,$showsize,$showmtime);
                   10127:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10128:         if ($embed_file =~ m{/}) {
                   10129:             my ($path,$fname) = split(/\//,$embed_file);
                   10130:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10131:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10132:             }
                   10133:         } else {
                   10134:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10135:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10136:             }
                   10137:         }
                   10138:         $showsize = $size/1024.0;
                   10139:         $showsize = sprintf("%.1f",$showsize);
                   10140:         if ($mtime > 0) {
                   10141:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10142:         }
                   10143:     }
                   10144:     return ($showsize,$showmtime);
                   10145: }
                   10146: 
                   10147: sub ask_embedded_js {
                   10148:     return <<"END";
                   10149: <script type="text/javascript"">
                   10150: // <![CDATA[
                   10151: function toggleBrowse(counter) {
                   10152:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10153:     var fileid = document.getElementById('embedded_item_'+counter);
                   10154:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10155:     if (chkboxid.checked == true) {
                   10156:         uploaddivid.style.display='block';
                   10157:     } else {
                   10158:         uploaddivid.style.display='none';
                   10159:         fileid.value = '';
                   10160:     }
                   10161: }
                   10162: // ]]>
                   10163: </script>
                   10164: 
                   10165: END
                   10166: }
                   10167: 
1.661     raeburn  10168: sub upload_embedded {
                   10169:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10170:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10171:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10172:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10173:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10174:         my $orig_uploaded_filename =
                   10175:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10176:         foreach my $type ('orig','ref','attrib','codebase') {
                   10177:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10178:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10179:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10180:             }
                   10181:         }
1.661     raeburn  10182:         my ($path,$fname) =
                   10183:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10184:         # no path, whole string is fname
                   10185:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10186:         $fname = &Apache::lonnet::clean_filename($fname);
                   10187:         # See if there is anything left
                   10188:         next if ($fname eq '');
                   10189: 
                   10190:         # Check if file already exists as a file or directory.
                   10191:         my ($state,$msg);
                   10192:         if ($context eq 'portfolio') {
                   10193:             my $port_path = $dirpath;
                   10194:             if ($group ne '') {
                   10195:                 $port_path = "groups/$group/$port_path";
                   10196:             }
1.987     raeburn  10197:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10198:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10199:                                               $dir_root,$port_path,$disk_quota,
                   10200:                                               $current_disk_usage,$uname,$udom);
                   10201:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10202:                 || $state eq 'file_locked') {
1.661     raeburn  10203:                 $output .= $msg;
                   10204:                 next;
                   10205:             }
                   10206:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10207:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10208:             if ($state eq 'exists') {
                   10209:                 $output .= $msg;
                   10210:                 next;
                   10211:             }
                   10212:         }
                   10213:         # Check if extension is valid
                   10214:         if (($fname =~ /\.(\w+)$/) &&
                   10215:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.987     raeburn  10216:             $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  10217:             next;
                   10218:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10219:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10220:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10221:             next;
                   10222:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10223:             $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  10224:             next;
                   10225:         }
                   10226:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  10227:         my $subdir = $path;
                   10228:         $subdir =~ s{/+$}{};
1.661     raeburn  10229:         if ($context eq 'portfolio') {
1.984     raeburn  10230:             my $result;
                   10231:             if ($state eq 'existingfile') {
                   10232:                 $result=
                   10233:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  10234:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10235:             } else {
1.984     raeburn  10236:                 $result=
                   10237:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10238:                                                     $dirpath.
1.1123    raeburn  10239:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10240:                 if ($result !~ m|^/uploaded/|) {
                   10241:                     $output .= '<span class="LC_error">'
                   10242:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10243:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10244:                                .'</span><br />';
                   10245:                     next;
                   10246:                 } else {
1.987     raeburn  10247:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10248:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10249:                 }
1.661     raeburn  10250:             }
1.1123    raeburn  10251:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  10252:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10253:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10254:             my $result =
1.1126    raeburn  10255:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10256:             if ($result !~ m|^/uploaded/|) {
                   10257:                 $output .= '<span class="LC_error">'
                   10258:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10259:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10260:                            .'</span><br />';
                   10261:                     next;
                   10262:             } else {
                   10263:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10264:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  10265:                 if ($context eq 'syllabus') {
                   10266:                     &Apache::lonnet::make_public_indefinitely($result);
                   10267:                 }
1.987     raeburn  10268:             }
1.661     raeburn  10269:         } else {
                   10270: # Save the file
                   10271:             my $target = $env{'form.embedded_item_'.$i};
                   10272:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10273:             my $dest = $fullpath.$fname;
                   10274:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10275:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10276:             my $count;
                   10277:             my $filepath = $dir_root;
1.1027    raeburn  10278:             foreach my $subdir (@parts) {
                   10279:                 $filepath .= "/$subdir";
                   10280:                 if (!-e $filepath) {
1.661     raeburn  10281:                     mkdir($filepath,0770);
                   10282:                 }
                   10283:             }
                   10284:             my $fh;
                   10285:             if (!open($fh,'>'.$dest)) {
                   10286:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10287:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10288:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10289:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10290:                            '</span><br />';
                   10291:             } else {
                   10292:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10293:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10294:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10295:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10296:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10297:                               '</span><br />';
                   10298:                 } else {
1.987     raeburn  10299:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10300:                                $url.'</span>').'<br />';
                   10301:                     unless ($context eq 'testbank') {
                   10302:                         $footer .= &mt('View embedded file: [_1]',
                   10303:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10304:                     }
                   10305:                 }
                   10306:                 close($fh);
                   10307:             }
                   10308:         }
                   10309:         if ($env{'form.embedded_ref_'.$i}) {
                   10310:             $pathchange{$i} = 1;
                   10311:         }
                   10312:     }
                   10313:     if ($output) {
                   10314:         $output = '<p>'.$output.'</p>';
                   10315:     }
                   10316:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10317:     $returnflag = 'ok';
1.1071    raeburn  10318:     my $numpathchgs = scalar(keys(%pathchange));
                   10319:     if ($numpathchgs > 0) {
1.987     raeburn  10320:         if ($context eq 'portfolio') {
                   10321:             $output .= '<p>'.&mt('or').'</p>';
                   10322:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10323:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10324:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10325:             $returnflag = 'modify_orightml';
                   10326:         }
                   10327:     }
1.1071    raeburn  10328:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10329: }
                   10330: 
                   10331: sub modify_html_form {
                   10332:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10333:     my $end = 0;
                   10334:     my $modifyform;
                   10335:     if ($context eq 'upload_embedded') {
                   10336:         return unless (ref($pathchange) eq 'HASH');
                   10337:         if ($env{'form.number_embedded_items'}) {
                   10338:             $end += $env{'form.number_embedded_items'};
                   10339:         }
                   10340:         if ($env{'form.number_pathchange_items'}) {
                   10341:             $end += $env{'form.number_pathchange_items'};
                   10342:         }
                   10343:         if ($end) {
                   10344:             for (my $i=0; $i<$end; $i++) {
                   10345:                 if ($i < $env{'form.number_embedded_items'}) {
                   10346:                     next unless($pathchange->{$i});
                   10347:                 }
                   10348:                 $modifyform .=
                   10349:                     &start_data_table_row().
                   10350:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10351:                     'checked="checked" /></td>'.
                   10352:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10353:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10354:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10355:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10356:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10357:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10358:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10359:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10360:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10361:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10362:                     &end_data_table_row();
1.1071    raeburn  10363:             }
1.987     raeburn  10364:         }
                   10365:     } else {
                   10366:         $modifyform = $pathchgtable;
                   10367:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10368:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10369:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10370:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10371:         }
                   10372:     }
                   10373:     if ($modifyform) {
1.1071    raeburn  10374:         if ($actionurl eq '/adm/dependencies') {
                   10375:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10376:         }
1.987     raeburn  10377:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10378:                '<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".
                   10379:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10380:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10381:                '</ol></p>'."\n".'<p>'.
                   10382:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10383:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10384:                &start_data_table()."\n".
                   10385:                &start_data_table_header_row().
                   10386:                '<th>'.&mt('Change?').'</th>'.
                   10387:                '<th>'.&mt('Current reference').'</th>'.
                   10388:                '<th>'.&mt('Required reference').'</th>'.
                   10389:                &end_data_table_header_row()."\n".
                   10390:                $modifyform.
                   10391:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10392:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10393:                '</form>'."\n";
                   10394:     }
                   10395:     return;
                   10396: }
                   10397: 
                   10398: sub modify_html_refs {
1.1123    raeburn  10399:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10400:     my $container;
                   10401:     if ($context eq 'portfolio') {
                   10402:         $container = $env{'form.container'};
                   10403:     } elsif ($context eq 'coursedoc') {
                   10404:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10405:     } elsif ($context eq 'manage_dependencies') {
                   10406:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10407:         $container = "/$container";
1.1123    raeburn  10408:     } elsif ($context eq 'syllabus') {
                   10409:         $container = $url;
1.987     raeburn  10410:     } else {
1.1027    raeburn  10411:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10412:     }
                   10413:     my (%allfiles,%codebase,$output,$content);
                   10414:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  10415:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  10416:         if (wantarray) {
                   10417:             return ('',0,0); 
                   10418:         } else {
                   10419:             return;
                   10420:         }
                   10421:     }
                   10422:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  10423:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10424:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10425:             if (wantarray) {
                   10426:                 return ('',0,0);
                   10427:             } else {
                   10428:                 return;
                   10429:             }
                   10430:         } 
1.987     raeburn  10431:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10432:         if ($content eq '-1') {
                   10433:             if (wantarray) {
                   10434:                 return ('',0,0);
                   10435:             } else {
                   10436:                 return;
                   10437:             }
                   10438:         }
1.987     raeburn  10439:     } else {
1.1071    raeburn  10440:         unless ($container =~ /^\Q$dir_root\E/) {
                   10441:             if (wantarray) {
                   10442:                 return ('',0,0);
                   10443:             } else {
                   10444:                 return;
                   10445:             }
                   10446:         } 
1.987     raeburn  10447:         if (open(my $fh,"<$container")) {
                   10448:             $content = join('', <$fh>);
                   10449:             close($fh);
                   10450:         } else {
1.1071    raeburn  10451:             if (wantarray) {
                   10452:                 return ('',0,0);
                   10453:             } else {
                   10454:                 return;
                   10455:             }
1.987     raeburn  10456:         }
                   10457:     }
                   10458:     my ($count,$codebasecount) = (0,0);
                   10459:     my $mm = new File::MMagic;
                   10460:     my $mime_type = $mm->checktype_contents($content);
                   10461:     if ($mime_type eq 'text/html') {
                   10462:         my $parse_result = 
                   10463:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10464:                                                     \%codebase,\$content);
                   10465:         if ($parse_result eq 'ok') {
                   10466:             foreach my $i (@changes) {
                   10467:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10468:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10469:                 if ($allfiles{$ref}) {
                   10470:                     my $newname =  $orig;
                   10471:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10472:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10473:                     if ($attrib_regexp =~ /:/) {
                   10474:                         $attrib_regexp =~ s/\:/|/g;
                   10475:                     }
                   10476:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10477:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10478:                         $count += $numchg;
1.1123    raeburn  10479:                         $allfiles{$newname} = $allfiles{$ref};
1.987     raeburn  10480:                     }
                   10481:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10482:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10483:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10484:                         $codebasecount ++;
                   10485:                     }
                   10486:                 }
                   10487:             }
1.1123    raeburn  10488:             my $skiprewrites;
1.987     raeburn  10489:             if ($count || $codebasecount) {
                   10490:                 my $saveresult;
1.1071    raeburn  10491:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  10492:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10493:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10494:                     if ($url eq $container) {
                   10495:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10496:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10497:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10498:                                             $fname.'</span>').'</p>';
1.987     raeburn  10499:                     } else {
                   10500:                          $output = '<p class="LC_error">'.
                   10501:                                    &mt('Error: update failed for: [_1].',
                   10502:                                    '<span class="LC_filename">'.
                   10503:                                    $container.'</span>').'</p>';
                   10504:                     }
1.1123    raeburn  10505:                     if ($context eq 'syllabus') {
                   10506:                         unless ($saveresult eq 'ok') {
                   10507:                             $skiprewrites = 1;
                   10508:                         }
                   10509:                     }
1.987     raeburn  10510:                 } else {
                   10511:                     if (open(my $fh,">$container")) {
                   10512:                         print $fh $content;
                   10513:                         close($fh);
                   10514:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10515:                                   $count,'<span class="LC_filename">'.
                   10516:                                   $container.'</span>').'</p>';
1.661     raeburn  10517:                     } else {
1.987     raeburn  10518:                          $output = '<p class="LC_error">'.
                   10519:                                    &mt('Error: could not update [_1].',
                   10520:                                    '<span class="LC_filename">'.
                   10521:                                    $container.'</span>').'</p>';
1.661     raeburn  10522:                     }
                   10523:                 }
                   10524:             }
1.1123    raeburn  10525:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10526:                 my ($actionurl,$state);
                   10527:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10528:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10529:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10530:                                               \%codebase,
                   10531:                                               {'context' => 'rewrites',
                   10532:                                                'ignore_remote_references' => 1,});
                   10533:                 if (ref($mapping) eq 'HASH') {
                   10534:                     my $rewrites = 0;
                   10535:                     foreach my $key (keys(%{$mapping})) {
                   10536:                         next if ($key =~ m{^https?://});
                   10537:                         my $ref = $mapping->{$key};
                   10538:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10539:                         my $attrib;
                   10540:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   10541:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   10542:                         }
                   10543:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10544:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10545:                             $rewrites += $numchg;
                   10546:                         }
                   10547:                     }
                   10548:                     if ($rewrites) {
                   10549:                         my $saveresult; 
                   10550:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10551:                         if ($url eq $container) {
                   10552:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   10553:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   10554:                                             $count,'<span class="LC_filename">'.
                   10555:                                             $fname.'</span>').'</p>';
                   10556:                         } else {
                   10557:                             $output .= '<p class="LC_error">'.
                   10558:                                        &mt('Error: could not update links in [_1].',
                   10559:                                        '<span class="LC_filename">'.
                   10560:                                        $container.'</span>').'</p>';
                   10561: 
                   10562:                         }
                   10563:                     }
                   10564:                 }
                   10565:             }
1.987     raeburn  10566:         } else {
                   10567:             &logthis('Failed to parse '.$container.
                   10568:                      ' to modify references: '.$parse_result);
1.661     raeburn  10569:         }
                   10570:     }
1.1071    raeburn  10571:     if (wantarray) {
                   10572:         return ($output,$count,$codebasecount);
                   10573:     } else {
                   10574:         return $output;
                   10575:     }
1.661     raeburn  10576: }
                   10577: 
                   10578: sub check_for_existing {
                   10579:     my ($path,$fname,$element) = @_;
                   10580:     my ($state,$msg);
                   10581:     if (-d $path.'/'.$fname) {
                   10582:         $state = 'exists';
                   10583:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10584:     } elsif (-e $path.'/'.$fname) {
                   10585:         $state = 'exists';
                   10586:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10587:     }
                   10588:     if ($state eq 'exists') {
                   10589:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10590:     }
                   10591:     return ($state,$msg);
                   10592: }
                   10593: 
                   10594: sub check_for_upload {
                   10595:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10596:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10597:     my $filesize = length($env{'form.'.$element});
                   10598:     if (!$filesize) {
                   10599:         my $msg = '<span class="LC_error">'.
                   10600:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10601:                       '<span class="LC_filename">'.$fname.'</span>',
                   10602:                       $filesize).'<br />'.
1.1007    raeburn  10603:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10604:                   '</span>';
                   10605:         return ('zero_bytes',$msg);
                   10606:     }
                   10607:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10608:     my $getpropath = 1;
1.1021    raeburn  10609:     my ($dirlistref,$listerror) =
                   10610:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10611:     my $found_file = 0;
                   10612:     my $locked_file = 0;
1.991     raeburn  10613:     my @lockers;
                   10614:     my $navmap;
                   10615:     if ($env{'request.course.id'}) {
                   10616:         $navmap = Apache::lonnavmaps::navmap->new();
                   10617:     }
1.1021    raeburn  10618:     if (ref($dirlistref) eq 'ARRAY') {
                   10619:         foreach my $line (@{$dirlistref}) {
                   10620:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10621:             if ($file_name eq $fname){
                   10622:                 $file_name = $path.$file_name;
                   10623:                 if ($group ne '') {
                   10624:                     $file_name = $group.$file_name;
                   10625:                 }
                   10626:                 $found_file = 1;
                   10627:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10628:                     foreach my $lock (@lockers) {
                   10629:                         if (ref($lock) eq 'ARRAY') {
                   10630:                             my ($symb,$crsid) = @{$lock};
                   10631:                             if ($crsid eq $env{'request.course.id'}) {
                   10632:                                 if (ref($navmap)) {
                   10633:                                     my $res = $navmap->getBySymb($symb);
                   10634:                                     foreach my $part (@{$res->parts()}) { 
                   10635:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10636:                                         unless (($slot_status == $res->RESERVED) ||
                   10637:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10638:                                             $locked_file = 1;
                   10639:                                         }
1.991     raeburn  10640:                                     }
1.1021    raeburn  10641:                                 } else {
                   10642:                                     $locked_file = 1;
1.991     raeburn  10643:                                 }
                   10644:                             } else {
                   10645:                                 $locked_file = 1;
                   10646:                             }
                   10647:                         }
1.1021    raeburn  10648:                    }
                   10649:                 } else {
                   10650:                     my @info = split(/\&/,$rest);
                   10651:                     my $currsize = $info[6]/1000;
                   10652:                     if ($currsize < $filesize) {
                   10653:                         my $extra = $filesize - $currsize;
                   10654:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10655:                             my $msg = '<span class="LC_error">'.
                   10656:                                       &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.',
                   10657:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10658:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10659:                                                    $disk_quota,$current_disk_usage);
                   10660:                             return ('will_exceed_quota',$msg);
                   10661:                         }
1.984     raeburn  10662:                     }
                   10663:                 }
1.661     raeburn  10664:             }
                   10665:         }
                   10666:     }
                   10667:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10668:         my $msg = '<span class="LC_error">'.
                   10669:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10670:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10671:         return ('will_exceed_quota',$msg);
                   10672:     } elsif ($found_file) {
                   10673:         if ($locked_file) {
                   10674:             my $msg = '<span class="LC_error">';
                   10675:             $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>');
                   10676:             $msg .= '</span><br />';
                   10677:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10678:             return ('file_locked',$msg);
                   10679:         } else {
                   10680:             my $msg = '<span class="LC_error">';
1.984     raeburn  10681:             $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  10682:             $msg .= '</span>';
1.984     raeburn  10683:             return ('existingfile',$msg);
1.661     raeburn  10684:         }
                   10685:     }
                   10686: }
                   10687: 
1.987     raeburn  10688: sub check_for_traversal {
                   10689:     my ($path,$url,$toplevel) = @_;
                   10690:     my @parts=split(/\//,$path);
                   10691:     my $cleanpath;
                   10692:     my $fullpath = $url;
                   10693:     for (my $i=0;$i<@parts;$i++) {
                   10694:         next if ($parts[$i] eq '.');
                   10695:         if ($parts[$i] eq '..') {
                   10696:             $fullpath =~ s{([^/]+/)$}{};
                   10697:         } else {
                   10698:             $fullpath .= $parts[$i].'/';
                   10699:         }
                   10700:     }
                   10701:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10702:         $cleanpath = $1;
                   10703:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10704:         my $curr_toprel = $1;
                   10705:         my @parts = split(/\//,$curr_toprel);
                   10706:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10707:         my @urlparts = split(/\//,$url_toprel);
                   10708:         my $doubledots;
                   10709:         my $startdiff = -1;
                   10710:         for (my $i=0; $i<@urlparts; $i++) {
                   10711:             if ($startdiff == -1) {
                   10712:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10713:                     $startdiff = $i;
                   10714:                     $doubledots .= '../';
                   10715:                 }
                   10716:             } else {
                   10717:                 $doubledots .= '../';
                   10718:             }
                   10719:         }
                   10720:         if ($startdiff > -1) {
                   10721:             $cleanpath = $doubledots;
                   10722:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10723:                 $cleanpath .= $parts[$i].'/';
                   10724:             }
                   10725:         }
                   10726:     }
                   10727:     $cleanpath =~ s{(/)$}{};
                   10728:     return $cleanpath;
                   10729: }
1.31      albertel 10730: 
1.1053    raeburn  10731: sub is_archive_file {
                   10732:     my ($mimetype) = @_;
                   10733:     if (($mimetype eq 'application/octet-stream') ||
                   10734:         ($mimetype eq 'application/x-stuffit') ||
                   10735:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10736:         return 1;
                   10737:     }
                   10738:     return;
                   10739: }
                   10740: 
                   10741: sub decompress_form {
1.1065    raeburn  10742:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10743:     my %lt = &Apache::lonlocal::texthash (
                   10744:         this => 'This file is an archive file.',
1.1067    raeburn  10745:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10746:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10747:         youm => 'You may wish to extract its contents.',
                   10748:         extr => 'Extract contents',
1.1067    raeburn  10749:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10750:         proa => 'Process automatically?',
1.1053    raeburn  10751:         yes  => 'Yes',
                   10752:         no   => 'No',
1.1067    raeburn  10753:         fold => 'Title for folder containing movie',
                   10754:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10755:     );
1.1065    raeburn  10756:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10757:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10758:     my $info = &list_archive_contents($fileloc,\@paths);
                   10759:     if (@paths) {
                   10760:         foreach my $path (@paths) {
                   10761:             $path =~ s{^/}{};
1.1067    raeburn  10762:             if ($path =~ m{^([^/]+)/$}) {
                   10763:                 $topdir = $1;
                   10764:             }
1.1065    raeburn  10765:             if ($path =~ m{^([^/]+)/}) {
                   10766:                 $toplevel{$1} = $path;
                   10767:             } else {
                   10768:                 $toplevel{$path} = $path;
                   10769:             }
                   10770:         }
                   10771:     }
1.1067    raeburn  10772:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
                   10773:         my @camtasia = ("$topdir/","$topdir/index.html",
                   10774:                         "$topdir/media/",
                   10775:                         "$topdir/media/$topdir.mp4",
                   10776:                         "$topdir/media/FirstFrame.png",
                   10777:                         "$topdir/media/player.swf",
                   10778:                         "$topdir/media/swfobject.js",
                   10779:                         "$topdir/media/expressInstall.swf");
                   10780:         my @diffs = &compare_arrays(\@paths,\@camtasia);
                   10781:         if (@diffs == 0) {
                   10782:             $is_camtasia = 1;
                   10783:         }
                   10784:     }
                   10785:     my $output;
                   10786:     if ($is_camtasia) {
                   10787:         $output = <<"ENDCAM";
                   10788: <script type="text/javascript" language="Javascript">
                   10789: // <![CDATA[
                   10790: 
                   10791: function camtasiaToggle() {
                   10792:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   10793:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
                   10794:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
                   10795: 
                   10796:                 document.getElementById('camtasia_titles').style.display='block';
                   10797:             } else {
                   10798:                 document.getElementById('camtasia_titles').style.display='none';
                   10799:             }
                   10800:         }
                   10801:     }
                   10802:     return;
                   10803: }
                   10804: 
                   10805: // ]]>
                   10806: </script>
                   10807: <p>$lt{'camt'}</p>
                   10808: ENDCAM
1.1065    raeburn  10809:     } else {
1.1067    raeburn  10810:         $output = '<p>'.$lt{'this'};
                   10811:         if ($info eq '') {
                   10812:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   10813:         } else {
                   10814:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   10815:                        '<div><pre>'.$info.'</pre></div>';
                   10816:         }
1.1065    raeburn  10817:     }
1.1067    raeburn  10818:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  10819:     my $duplicates;
                   10820:     my $num = 0;
                   10821:     if (ref($dirlist) eq 'ARRAY') {
                   10822:         foreach my $item (@{$dirlist}) {
                   10823:             if (ref($item) eq 'ARRAY') {
                   10824:                 if (exists($toplevel{$item->[0]})) {
                   10825:                     $duplicates .= 
                   10826:                         &start_data_table_row().
                   10827:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10828:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   10829:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10830:                         'value="1" />'.&mt('Yes').'</label>'.
                   10831:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   10832:                         '<td>'.$item->[0].'</td>';
                   10833:                     if ($item->[2]) {
                   10834:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   10835:                     } else {
                   10836:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   10837:                     }
                   10838:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   10839:                                    '<td>'.
                   10840:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   10841:                                    '</td>'.
                   10842:                                    &end_data_table_row();
                   10843:                     $num ++;
                   10844:                 }
                   10845:             }
                   10846:         }
                   10847:     }
                   10848:     my $itemcount;
                   10849:     if (@paths > 0) {
                   10850:         $itemcount = scalar(@paths);
                   10851:     } else {
                   10852:         $itemcount = 1;
                   10853:     }
1.1067    raeburn  10854:     if ($is_camtasia) {
                   10855:         $output .= $lt{'auto'}.'<br />'.
                   10856:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
                   10857:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
                   10858:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   10859:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   10860:                    $lt{'no'}.'</label></span><br />'.
                   10861:                    '<div id="camtasia_titles" style="display:block">'.
                   10862:                    &Apache::lonhtmlcommon::start_pick_box().
                   10863:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   10864:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   10865:                    &Apache::lonhtmlcommon::row_closure().
                   10866:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   10867:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   10868:                    &Apache::lonhtmlcommon::row_closure(1).
                   10869:                    &Apache::lonhtmlcommon::end_pick_box().
                   10870:                    '</div>';
                   10871:     }
1.1065    raeburn  10872:     $output .= 
                   10873:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  10874:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   10875:         "\n";
1.1065    raeburn  10876:     if ($duplicates ne '') {
                   10877:         $output .= '<p><span class="LC_warning">'.
                   10878:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   10879:                    &start_data_table().
                   10880:                    &start_data_table_header_row().
                   10881:                    '<th>'.&mt('Overwrite?').'</th>'.
                   10882:                    '<th>'.&mt('Name').'</th>'.
                   10883:                    '<th>'.&mt('Type').'</th>'.
                   10884:                    '<th>'.&mt('Size').'</th>'.
                   10885:                    '<th>'.&mt('Last modified').'</th>'.
                   10886:                    &end_data_table_header_row().
                   10887:                    $duplicates.
                   10888:                    &end_data_table().
                   10889:                    '</p>';
                   10890:     }
1.1067    raeburn  10891:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  10892:     if (ref($hiddenelements) eq 'HASH') {
                   10893:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   10894:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   10895:         }
                   10896:     }
                   10897:     $output .= <<"END";
1.1067    raeburn  10898: <br />
1.1053    raeburn  10899: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   10900: </form>
                   10901: $noextract
                   10902: END
                   10903:     return $output;
                   10904: }
                   10905: 
1.1065    raeburn  10906: sub decompression_utility {
                   10907:     my ($program) = @_;
                   10908:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   10909:     my $location;
                   10910:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   10911:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   10912:                          '/usr/sbin/') {
                   10913:             if (-x $dir.$program) {
                   10914:                 $location = $dir.$program;
                   10915:                 last;
                   10916:             }
                   10917:         }
                   10918:     }
                   10919:     return $location;
                   10920: }
                   10921: 
                   10922: sub list_archive_contents {
                   10923:     my ($file,$pathsref) = @_;
                   10924:     my (@cmd,$output);
                   10925:     my $needsregexp;
                   10926:     if ($file =~ /\.zip$/) {
                   10927:         @cmd = (&decompression_utility('unzip'),"-l");
                   10928:         $needsregexp = 1;
                   10929:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   10930:              ($file =~ /\.tgz$/)) {
                   10931:         @cmd = (&decompression_utility('tar'),"-ztf");
                   10932:     } elsif ($file =~ /\.tar\.bz2$/) {
                   10933:         @cmd = (&decompression_utility('tar'),"-jtf");
                   10934:     } elsif ($file =~ m|\.tar$|) {
                   10935:         @cmd = (&decompression_utility('tar'),"-tf");
                   10936:     }
                   10937:     if (@cmd) {
                   10938:         undef($!);
                   10939:         undef($@);
                   10940:         if (open(my $fh,"-|", @cmd, $file)) {
                   10941:             while (my $line = <$fh>) {
                   10942:                 $output .= $line;
                   10943:                 chomp($line);
                   10944:                 my $item;
                   10945:                 if ($needsregexp) {
                   10946:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   10947:                 } else {
                   10948:                     $item = $line;
                   10949:                 }
                   10950:                 if ($item ne '') {
                   10951:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   10952:                         push(@{$pathsref},$item);
                   10953:                     } 
                   10954:                 }
                   10955:             }
                   10956:             close($fh);
                   10957:         }
                   10958:     }
                   10959:     return $output;
                   10960: }
                   10961: 
1.1053    raeburn  10962: sub decompress_uploaded_file {
                   10963:     my ($file,$dir) = @_;
                   10964:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   10965:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   10966:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   10967:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   10968:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   10969:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   10970:     my $decompressed = $env{'cgi.decompressed'};
                   10971:     &Apache::lonnet::delenv('cgi.file');
                   10972:     &Apache::lonnet::delenv('cgi.dir');
                   10973:     &Apache::lonnet::delenv('cgi.decompressed');
                   10974:     return ($decompressed,$result);
                   10975: }
                   10976: 
1.1055    raeburn  10977: sub process_decompression {
                   10978:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   10979:     my ($dir,$error,$warning,$output);
                   10980:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
1.1120    bisitz   10981:         $error = &mt('Filename not a supported archive file type.').
                   10982:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  10983:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   10984:     } else {
                   10985:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   10986:         if ($docuhome eq 'no_host') {
                   10987:             $error = &mt('Could not determine home server for course.');
                   10988:         } else {
                   10989:             my @ids=&Apache::lonnet::current_machine_ids();
                   10990:             my $currdir = "$dir_root/$destination";
                   10991:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   10992:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   10993:                        "$dir_root/$destination";
                   10994:             } else {
                   10995:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   10996:                        "$dir_root/$docudom/$docuname/$destination";
                   10997:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   10998:                     $error = &mt('Archive file not found.');
                   10999:                 }
                   11000:             }
1.1065    raeburn  11001:             my (@to_overwrite,@to_skip);
                   11002:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11003:                 my $total = $env{'form.archive_overwrite_total'};
                   11004:                 for (my $i=0; $i<$total; $i++) {
                   11005:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11006:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11007:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11008:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11009:                     }
                   11010:                 }
                   11011:             }
                   11012:             my $numskip = scalar(@to_skip);
                   11013:             if (($numskip > 0) && 
                   11014:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11015:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11016:             } elsif ($dir eq '') {
1.1055    raeburn  11017:                 $error = &mt('Directory containing archive file unavailable.');
                   11018:             } elsif (!$error) {
1.1065    raeburn  11019:                 my ($decompressed,$display);
                   11020:                 if ($numskip > 0) {
                   11021:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11022:                     mkdir("$dir/$tempdir",0755);
                   11023:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11024:                     ($decompressed,$display) = 
                   11025:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11026:                     foreach my $item (@to_skip) {
                   11027:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11028:                             if (-f "$dir/$tempdir/$item") { 
                   11029:                                 unlink("$dir/$tempdir/$item");
                   11030:                             } elsif (-d "$dir/$tempdir/$item") {
                   11031:                                 system("rm -rf $dir/$tempdir/$item");
                   11032:                             }
                   11033:                         }
                   11034:                     }
                   11035:                     system("mv $dir/$tempdir/* $dir");
                   11036:                     rmdir("$dir/$tempdir");   
                   11037:                 } else {
                   11038:                     ($decompressed,$display) = 
                   11039:                         &decompress_uploaded_file($file,$dir);
                   11040:                 }
1.1055    raeburn  11041:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11042:                     $output = '<p class="LC_info">'.
                   11043:                               &mt('Files extracted successfully from archive.').
                   11044:                               '</p>'."\n";
1.1055    raeburn  11045:                     my ($warning,$result,@contents);
                   11046:                     my ($newdirlistref,$newlisterror) =
                   11047:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11048:                                                  $docuname,1);
                   11049:                     my (%is_dir,%changes,@newitems);
                   11050:                     my $dirptr = 16384;
1.1065    raeburn  11051:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11052:                         foreach my $dir_line (@{$newdirlistref}) {
                   11053:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11054:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11055:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11056:                                 push(@newitems,$item);
                   11057:                                 if ($dirptr&$testdir) {
                   11058:                                     $is_dir{$item} = 1;
                   11059:                                 }
                   11060:                                 $changes{$item} = 1;
                   11061:                             }
                   11062:                         }
                   11063:                     }
                   11064:                     if (keys(%changes) > 0) {
                   11065:                         foreach my $item (sort(@newitems)) {
                   11066:                             if ($changes{$item}) {
                   11067:                                 push(@contents,$item);
                   11068:                             }
                   11069:                         }
                   11070:                     }
                   11071:                     if (@contents > 0) {
1.1067    raeburn  11072:                         my $wantform;
                   11073:                         unless ($env{'form.autoextract_camtasia'}) {
                   11074:                             $wantform = 1;
                   11075:                         }
1.1056    raeburn  11076:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11077:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11078:                                                                 $currdir,\%is_dir,
                   11079:                                                                 \%children,\%parent,
1.1056    raeburn  11080:                                                                 \@contents,\%dirorder,
                   11081:                                                                 \%titles,$wantform);
1.1055    raeburn  11082:                         if ($datatable ne '') {
                   11083:                             $output .= &archive_options_form('decompressed',$datatable,
                   11084:                                                              $count,$hiddenelem);
1.1065    raeburn  11085:                             my $startcount = 6;
1.1055    raeburn  11086:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11087:                                                            \%titles,\%children);
1.1055    raeburn  11088:                         }
1.1067    raeburn  11089:                         if ($env{'form.autoextract_camtasia'}) {
                   11090:                             my %displayed;
                   11091:                             my $total = 1;
                   11092:                             $env{'form.archive_directory'} = [];
                   11093:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11094:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11095:                                 $path =~ s{/$}{};
                   11096:                                 my $item;
                   11097:                                 if ($path ne '') {
                   11098:                                     $item = "$path/$titles{$i}";
                   11099:                                 } else {
                   11100:                                     $item = $titles{$i};
                   11101:                                 }
                   11102:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11103:                                 if ($item eq $contents[0]) {
                   11104:                                     push(@{$env{'form.archive_directory'}},$i);
                   11105:                                     $env{'form.archive_'.$i} = 'display';
                   11106:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11107:                                     $displayed{'folder'} = $i;
                   11108:                                 } elsif ($item eq "$contents[0]/index.html") {
                   11109:                                     $env{'form.archive_'.$i} = 'display';
                   11110:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11111:                                     $displayed{'web'} = $i;
                   11112:                                 } else {
                   11113:                                     if ($item eq "$contents[0]/media") {
                   11114:                                         push(@{$env{'form.archive_directory'}},$i);
                   11115:                                     }
                   11116:                                     $env{'form.archive_'.$i} = 'dependency';
                   11117:                                 }
                   11118:                                 $total ++;
                   11119:                             }
                   11120:                             for (my $i=1; $i<$total; $i++) {
                   11121:                                 next if ($i == $displayed{'web'});
                   11122:                                 next if ($i == $displayed{'folder'});
                   11123:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11124:                             }
                   11125:                             $env{'form.phase'} = 'decompress_cleanup';
                   11126:                             $env{'form.archivedelete'} = 1;
                   11127:                             $env{'form.archive_count'} = $total-1;
                   11128:                             $output .=
                   11129:                                 &process_extracted_files('coursedocs',$docudom,
                   11130:                                                          $docuname,$destination,
                   11131:                                                          $dir_root,$hiddenelem);
                   11132:                         }
1.1055    raeburn  11133:                     } else {
                   11134:                         $warning = &mt('No new items extracted from archive file.');
                   11135:                     }
                   11136:                 } else {
                   11137:                     $output = $display;
                   11138:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11139:                 }
                   11140:             }
                   11141:         }
                   11142:     }
                   11143:     if ($error) {
                   11144:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11145:                    $error.'</p>'."\n";
                   11146:     }
                   11147:     if ($warning) {
                   11148:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11149:     }
                   11150:     return $output;
                   11151: }
                   11152: 
                   11153: sub get_extracted {
1.1056    raeburn  11154:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11155:         $titles,$wantform) = @_;
1.1055    raeburn  11156:     my $count = 0;
                   11157:     my $depth = 0;
                   11158:     my $datatable;
1.1056    raeburn  11159:     my @hierarchy;
1.1055    raeburn  11160:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11161:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11162:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11163:     foreach my $item (@{$contents}) {
                   11164:         $count ++;
1.1056    raeburn  11165:         @{$dirorder->{$count}} = @hierarchy;
                   11166:         $titles->{$count} = $item;
1.1055    raeburn  11167:         &archive_hierarchy($depth,$count,$parent,$children);
                   11168:         if ($wantform) {
                   11169:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11170:                                        $currdir,$depth,$count);
                   11171:         }
                   11172:         if ($is_dir->{$item}) {
                   11173:             $depth ++;
1.1056    raeburn  11174:             push(@hierarchy,$count);
                   11175:             $parent->{$depth} = $count;
1.1055    raeburn  11176:             $datatable .=
                   11177:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11178:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11179:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11180:             $depth --;
1.1056    raeburn  11181:             pop(@hierarchy);
1.1055    raeburn  11182:         }
                   11183:     }
                   11184:     return ($count,$datatable);
                   11185: }
                   11186: 
                   11187: sub recurse_extracted_archive {
1.1056    raeburn  11188:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11189:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11190:     my $result='';
1.1056    raeburn  11191:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11192:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11193:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11194:         return $result;
                   11195:     }
                   11196:     my $dirptr = 16384;
                   11197:     my ($newdirlistref,$newlisterror) =
                   11198:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11199:     if (ref($newdirlistref) eq 'ARRAY') {
                   11200:         foreach my $dir_line (@{$newdirlistref}) {
                   11201:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11202:             unless ($item =~ /^\.+$/) {
                   11203:                 $$count ++;
1.1056    raeburn  11204:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11205:                 $titles->{$$count} = $item;
1.1055    raeburn  11206:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11207: 
1.1055    raeburn  11208:                 my $is_dir;
                   11209:                 if ($dirptr&$testdir) {
                   11210:                     $is_dir = 1;
                   11211:                 }
                   11212:                 if ($wantform) {
                   11213:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11214:                 }
                   11215:                 if ($is_dir) {
                   11216:                     $$depth ++;
1.1056    raeburn  11217:                     push(@{$hierarchy},$$count);
                   11218:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11219:                     $result .=
                   11220:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11221:                                                    $docuname,$depth,$count,
1.1056    raeburn  11222:                                                    $hierarchy,$dirorder,$children,
                   11223:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11224:                     $$depth --;
1.1056    raeburn  11225:                     pop(@{$hierarchy});
1.1055    raeburn  11226:                 }
                   11227:             }
                   11228:         }
                   11229:     }
                   11230:     return $result;
                   11231: }
                   11232: 
                   11233: sub archive_hierarchy {
                   11234:     my ($depth,$count,$parent,$children) =@_;
                   11235:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11236:         if (exists($parent->{$depth})) {
                   11237:              $children->{$parent->{$depth}} .= $count.':';
                   11238:         }
                   11239:     }
                   11240:     return;
                   11241: }
                   11242: 
                   11243: sub archive_row {
                   11244:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11245:     my ($name) = ($item =~ m{([^/]+)$});
                   11246:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11247:                                        'display'    => 'Add as file',
1.1055    raeburn  11248:                                        'dependency' => 'Include as dependency',
                   11249:                                        'discard'    => 'Discard',
                   11250:                                       );
                   11251:     if ($is_dir) {
1.1059    raeburn  11252:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11253:     }
1.1056    raeburn  11254:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11255:     my $offset = 0;
1.1055    raeburn  11256:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11257:         $offset ++;
1.1065    raeburn  11258:         if ($action ne 'display') {
                   11259:             $offset ++;
                   11260:         }  
1.1055    raeburn  11261:         $output .= '<td><span class="LC_nobreak">'.
                   11262:                    '<label><input type="radio" name="archive_'.$count.
                   11263:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11264:         my $text = $choices{$action};
                   11265:         if ($is_dir) {
                   11266:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11267:             if ($action eq 'display') {
1.1059    raeburn  11268:                 $text = &mt('Add as folder');
1.1055    raeburn  11269:             }
1.1056    raeburn  11270:         } else {
                   11271:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11272: 
                   11273:         }
                   11274:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11275:         if ($action eq 'dependency') {
                   11276:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11277:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11278:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11279:                        '<option value=""></option>'."\n".
                   11280:                        '</select>'."\n".
                   11281:                        '</div>';
1.1059    raeburn  11282:         } elsif ($action eq 'display') {
                   11283:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11284:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11285:                        '</div>';
1.1055    raeburn  11286:         }
1.1056    raeburn  11287:         $output .= '</td>';
1.1055    raeburn  11288:     }
                   11289:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11290:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11291:     for (my $i=0; $i<$depth; $i++) {
                   11292:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11293:     }
                   11294:     if ($is_dir) {
                   11295:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11296:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11297:     } else {
                   11298:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11299:     }
                   11300:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11301:                &end_data_table_row();
                   11302:     return $output;
                   11303: }
                   11304: 
                   11305: sub archive_options_form {
1.1065    raeburn  11306:     my ($form,$display,$count,$hiddenelem) = @_;
                   11307:     my %lt = &Apache::lonlocal::texthash(
                   11308:                perm => 'Permanently remove archive file?',
                   11309:                hows => 'How should each extracted item be incorporated in the course?',
                   11310:                cont => 'Content actions for all',
                   11311:                addf => 'Add as folder/file',
                   11312:                incd => 'Include as dependency for a displayed file',
                   11313:                disc => 'Discard',
                   11314:                no   => 'No',
                   11315:                yes  => 'Yes',
                   11316:                save => 'Save',
                   11317:     );
                   11318:     my $output = <<"END";
                   11319: <form name="$form" method="post" action="">
                   11320: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11321: <label>
                   11322:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11323: </label>
                   11324: &nbsp;
                   11325: <label>
                   11326:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11327: </span>
                   11328: </p>
                   11329: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11330: <br />$lt{'hows'}
                   11331: <div class="LC_columnSection">
                   11332:   <fieldset>
                   11333:     <legend>$lt{'cont'}</legend>
                   11334:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11335:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11336:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11337:   </fieldset>
                   11338: </div>
                   11339: END
                   11340:     return $output.
1.1055    raeburn  11341:            &start_data_table()."\n".
1.1065    raeburn  11342:            $display."\n".
1.1055    raeburn  11343:            &end_data_table()."\n".
                   11344:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11345:            $hiddenelem.
1.1065    raeburn  11346:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11347:            '</form>';
                   11348: }
                   11349: 
                   11350: sub archive_javascript {
1.1056    raeburn  11351:     my ($startcount,$numitems,$titles,$children) = @_;
                   11352:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11353:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11354:     my $scripttag = <<START;
                   11355: <script type="text/javascript">
                   11356: // <![CDATA[
                   11357: 
                   11358: function checkAll(form,prefix) {
                   11359:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11360:     for (var i=0; i < form.elements.length; i++) {
                   11361:         var id = form.elements[i].id;
                   11362:         if ((id != '') && (id != undefined)) {
                   11363:             if (idstr.test(id)) {
                   11364:                 if (form.elements[i].type == 'radio') {
                   11365:                     form.elements[i].checked = true;
1.1056    raeburn  11366:                     var nostart = i-$startcount;
1.1059    raeburn  11367:                     var offset = nostart%7;
                   11368:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11369:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11370:                 }
                   11371:             }
                   11372:         }
                   11373:     }
                   11374: }
                   11375: 
                   11376: function propagateCheck(form,count) {
                   11377:     if (count > 0) {
1.1059    raeburn  11378:         var startelement = $startcount + ((count-1) * 7);
                   11379:         for (var j=1; j<6; j++) {
                   11380:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11381:                 var item = startelement + j; 
                   11382:                 if (form.elements[item].type == 'radio') {
                   11383:                     if (form.elements[item].checked) {
                   11384:                         containerCheck(form,count,j);
                   11385:                         break;
                   11386:                     }
1.1055    raeburn  11387:                 }
                   11388:             }
                   11389:         }
                   11390:     }
                   11391: }
                   11392: 
                   11393: numitems = $numitems
1.1056    raeburn  11394: var titles = new Array(numitems);
                   11395: var parents = new Array(numitems);
1.1055    raeburn  11396: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11397:     parents[i] = new Array;
1.1055    raeburn  11398: }
1.1059    raeburn  11399: var maintitle = '$maintitle';
1.1055    raeburn  11400: 
                   11401: START
                   11402: 
1.1056    raeburn  11403:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11404:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11405:         for (my $i=0; $i<@contents; $i ++) {
                   11406:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11407:         }
                   11408:     }
                   11409: 
1.1056    raeburn  11410:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11411:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11412:     }
                   11413: 
1.1055    raeburn  11414:     $scripttag .= <<END;
                   11415: 
                   11416: function containerCheck(form,count,offset) {
                   11417:     if (count > 0) {
1.1056    raeburn  11418:         dependencyCheck(form,count,offset);
1.1059    raeburn  11419:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11420:         form.elements[item].checked = true;
                   11421:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11422:             if (parents[count].length > 0) {
                   11423:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11424:                     containerCheck(form,parents[count][j],offset);
                   11425:                 }
                   11426:             }
                   11427:         }
                   11428:     }
                   11429: }
                   11430: 
                   11431: function dependencyCheck(form,count,offset) {
                   11432:     if (count > 0) {
1.1059    raeburn  11433:         var chosen = (offset+$startcount)+7*(count-1);
                   11434:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11435:         var currtype = form.elements[depitem].type;
                   11436:         if (form.elements[chosen].value == 'dependency') {
                   11437:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11438:             form.elements[depitem].options.length = 0;
                   11439:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  11440:             for (var i=1; i<=numitems; i++) {
                   11441:                 if (i == count) {
                   11442:                     continue;
                   11443:                 }
1.1059    raeburn  11444:                 var startelement = $startcount + (i-1) * 7;
                   11445:                 for (var j=1; j<6; j++) {
                   11446:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11447:                         var item = startelement + j;
                   11448:                         if (form.elements[item].type == 'radio') {
                   11449:                             if (form.elements[item].checked) {
                   11450:                                 if (form.elements[item].value == 'display') {
                   11451:                                     var n = form.elements[depitem].options.length;
                   11452:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11453:                                 }
                   11454:                             }
                   11455:                         }
                   11456:                     }
                   11457:                 }
                   11458:             }
                   11459:         } else {
                   11460:             document.getElementById('arc_depon_'+count).style.display='none';
                   11461:             form.elements[depitem].options.length = 0;
                   11462:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11463:         }
1.1059    raeburn  11464:         titleCheck(form,count,offset);
1.1056    raeburn  11465:     }
                   11466: }
                   11467: 
                   11468: function propagateSelect(form,count,offset) {
                   11469:     if (count > 0) {
1.1065    raeburn  11470:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11471:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11472:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11473:             if (parents[count].length > 0) {
                   11474:                 for (var j=0; j<parents[count].length; j++) {
                   11475:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11476:                 }
                   11477:             }
                   11478:         }
                   11479:     }
                   11480: }
1.1056    raeburn  11481: 
                   11482: function containerSelect(form,count,offset,picked) {
                   11483:     if (count > 0) {
1.1065    raeburn  11484:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11485:         if (form.elements[item].type == 'radio') {
                   11486:             if (form.elements[item].value == 'dependency') {
                   11487:                 if (form.elements[item+1].type == 'select-one') {
                   11488:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11489:                         if (form.elements[item+1].options[i].value == picked) {
                   11490:                             form.elements[item+1].selectedIndex = i;
                   11491:                             break;
                   11492:                         }
                   11493:                     }
                   11494:                 }
                   11495:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11496:                     if (parents[count].length > 0) {
                   11497:                         for (var j=0; j<parents[count].length; j++) {
                   11498:                             containerSelect(form,parents[count][j],offset,picked);
                   11499:                         }
                   11500:                     }
                   11501:                 }
                   11502:             }
                   11503:         }
                   11504:     }
                   11505: }
                   11506: 
1.1059    raeburn  11507: function titleCheck(form,count,offset) {
                   11508:     if (count > 0) {
                   11509:         var chosen = (offset+$startcount)+7*(count-1);
                   11510:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11511:         var currtype = form.elements[depitem].type;
                   11512:         if (form.elements[chosen].value == 'display') {
                   11513:             document.getElementById('arc_title_'+count).style.display='block';
                   11514:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11515:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11516:             }
                   11517:         } else {
                   11518:             document.getElementById('arc_title_'+count).style.display='none';
                   11519:             if (currtype == 'text') { 
                   11520:                 document.getElementById('archive_title_'+count).value='';
                   11521:             }
                   11522:         }
                   11523:     }
                   11524:     return;
                   11525: }
                   11526: 
1.1055    raeburn  11527: // ]]>
                   11528: </script>
                   11529: END
                   11530:     return $scripttag;
                   11531: }
                   11532: 
                   11533: sub process_extracted_files {
1.1067    raeburn  11534:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11535:     my $numitems = $env{'form.archive_count'};
                   11536:     return unless ($numitems);
                   11537:     my @ids=&Apache::lonnet::current_machine_ids();
                   11538:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11539:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11540:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11541:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11542:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11543:         $pathtocheck = "$dir_root/$destination";
                   11544:         $dir = $dir_root;
                   11545:         $ishome = 1;
                   11546:     } else {
                   11547:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11548:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11549:         $dir = "$dir_root/$docudom/$docuname";    
                   11550:     }
                   11551:     my $currdir = "$dir_root/$destination";
                   11552:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11553:     if ($env{'form.folderpath'}) {
                   11554:         my @items = split('&',$env{'form.folderpath'});
                   11555:         $folders{'0'} = $items[-2];
1.1099    raeburn  11556:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11557:             $containers{'0'}='page';
                   11558:         } else {  
                   11559:             $containers{'0'}='sequence';
                   11560:         }
1.1055    raeburn  11561:     }
                   11562:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11563:     if ($numitems) {
                   11564:         for (my $i=1; $i<=$numitems; $i++) {
                   11565:             my $path = $env{'form.archive_content_'.$i};
                   11566:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11567:                 my $item = $1;
                   11568:                 $toplevelitems{$item} = $i;
                   11569:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11570:                     $is_dir{$item} = 1;
                   11571:                 }
                   11572:             }
                   11573:         }
                   11574:     }
1.1067    raeburn  11575:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11576:     if (keys(%toplevelitems) > 0) {
                   11577:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11578:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11579:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11580:     }
1.1066    raeburn  11581:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11582:     if ($numitems) {
                   11583:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  11584:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11585:             my $path = $env{'form.archive_content_'.$i};
                   11586:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11587:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11588:                     if ($prefix ne '' && $path ne '') {
                   11589:                         if (-e $prefix.$path) {
1.1066    raeburn  11590:                             if ((@archdirs > 0) && 
                   11591:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11592:                                 $todeletedir{$prefix.$path} = 1;
                   11593:                             } else {
                   11594:                                 $todelete{$prefix.$path} = 1;
                   11595:                             }
1.1055    raeburn  11596:                         }
                   11597:                     }
                   11598:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11599:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11600:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11601:                     $docstitle = $env{'form.archive_title_'.$i};
                   11602:                     if ($docstitle eq '') {
                   11603:                         $docstitle = $title;
                   11604:                     }
1.1055    raeburn  11605:                     $outer = 0;
1.1056    raeburn  11606:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11607:                         if (@{$dirorder{$i}} > 0) {
                   11608:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11609:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11610:                                     $outer = $item;
                   11611:                                     last;
                   11612:                                 }
                   11613:                             }
                   11614:                         }
                   11615:                     }
                   11616:                     my ($errtext,$fatal) = 
                   11617:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11618:                                                '/'.$folders{$outer}.'.'.
                   11619:                                                $containers{$outer});
                   11620:                     next if ($fatal);
                   11621:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11622:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11623:                             $mapinner{$i} = time;
1.1055    raeburn  11624:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11625:                             $containers{$i} = 'sequence';
                   11626:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11627:                                       $folders{$i}.'.'.$containers{$i};
                   11628:                             my $newidx = &LONCAPA::map::getresidx();
                   11629:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11630:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11631:                             push(@LONCAPA::map::order,$newidx);
                   11632:                             my ($outtext,$errtext) =
                   11633:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11634:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11635:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11636:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11637:                             unless ($errtext) {
                   11638:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11639:                             }
1.1055    raeburn  11640:                         }
                   11641:                     } else {
                   11642:                         if ($context eq 'coursedocs') {
                   11643:                             my $newidx=&LONCAPA::map::getresidx();
                   11644:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11645:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11646:                                       $title;
                   11647:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11648:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11649:                             }
                   11650:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11651:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11652:                             }
                   11653:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11654:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11655:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11656:                                 unless ($ishome) {
                   11657:                                     my $fetch = "$newdest{$i}/$title";
                   11658:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11659:                                     $prompttofetch{$fetch} = 1;
                   11660:                                 }
1.1055    raeburn  11661:                             }
                   11662:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11663:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11664:                             push(@LONCAPA::map::order, $newidx);
                   11665:                             my ($outtext,$errtext)=
                   11666:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11667:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11668:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11669:                             unless ($errtext) {
                   11670:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11671:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11672:                                 }
                   11673:                             }
1.1055    raeburn  11674:                         }
                   11675:                     }
1.1086    raeburn  11676:                 }
                   11677:             } else {
                   11678:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11679:             }
                   11680:         }
                   11681:         for (my $i=1; $i<=$numitems; $i++) {
                   11682:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11683:             my $path = $env{'form.archive_content_'.$i};
                   11684:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11685:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11686:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11687:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11688:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11689:                         my ($itemidx,$fullpath,$relpath);
                   11690:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11691:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11692:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  11693:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11694:                                     $itemidx = $j;
1.1056    raeburn  11695:                                 }
                   11696:                             }
1.1086    raeburn  11697:                         }
                   11698:                         if ($itemidx eq '') {
                   11699:                             $itemidx =  0;
                   11700:                         } 
                   11701:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11702:                             if ($mapinner{$referrer{$i}}) {
                   11703:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11704:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11705:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11706:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11707:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11708:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11709:                                             if (!-e $fullpath) {
                   11710:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11711:                                             }
                   11712:                                         }
1.1086    raeburn  11713:                                     } else {
                   11714:                                         last;
1.1056    raeburn  11715:                                     }
1.1086    raeburn  11716:                                 }
                   11717:                             }
                   11718:                         } elsif ($newdest{$referrer{$i}}) {
                   11719:                             $fullpath = $newdest{$referrer{$i}};
                   11720:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11721:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11722:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11723:                                     last;
                   11724:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11725:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11726:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11727:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11728:                                         if (!-e $fullpath) {
                   11729:                                             mkdir($fullpath,0755);
1.1056    raeburn  11730:                                         }
                   11731:                                     }
1.1086    raeburn  11732:                                 } else {
                   11733:                                     last;
1.1056    raeburn  11734:                                 }
1.1055    raeburn  11735:                             }
                   11736:                         }
1.1086    raeburn  11737:                         if ($fullpath ne '') {
                   11738:                             if (-e "$prefix$path") {
                   11739:                                 system("mv $prefix$path $fullpath/$title");
                   11740:                             }
                   11741:                             if (-e "$fullpath/$title") {
                   11742:                                 my $showpath;
                   11743:                                 if ($relpath ne '') {
                   11744:                                     $showpath = "$relpath/$title";
                   11745:                                 } else {
                   11746:                                     $showpath = "/$title";
                   11747:                                 } 
                   11748:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   11749:                             } 
                   11750:                             unless ($ishome) {
                   11751:                                 my $fetch = "$fullpath/$title";
                   11752:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   11753:                                 $prompttofetch{$fetch} = 1;
                   11754:                             }
                   11755:                         }
1.1055    raeburn  11756:                     }
1.1086    raeburn  11757:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   11758:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   11759:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  11760:                 }
                   11761:             } else {
                   11762:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11763:             }
                   11764:         }
                   11765:         if (keys(%todelete)) {
                   11766:             foreach my $key (keys(%todelete)) {
                   11767:                 unlink($key);
1.1066    raeburn  11768:             }
                   11769:         }
                   11770:         if (keys(%todeletedir)) {
                   11771:             foreach my $key (keys(%todeletedir)) {
                   11772:                 rmdir($key);
                   11773:             }
                   11774:         }
                   11775:         foreach my $dir (sort(keys(%is_dir))) {
                   11776:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   11777:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  11778:             }
                   11779:         }
1.1067    raeburn  11780:         if ($result ne '') {
                   11781:             $output .= '<ul>'."\n".
                   11782:                        $result."\n".
                   11783:                        '</ul>';
                   11784:         }
                   11785:         unless ($ishome) {
                   11786:             my $replicationfail;
                   11787:             foreach my $item (keys(%prompttofetch)) {
                   11788:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   11789:                 unless ($fetchresult eq 'ok') {
                   11790:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   11791:                 }
                   11792:             }
                   11793:             if ($replicationfail) {
                   11794:                 $output .= '<p class="LC_error">'.
                   11795:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   11796:                            $replicationfail.
                   11797:                            '</ul></p>';
                   11798:             }
                   11799:         }
1.1055    raeburn  11800:     } else {
                   11801:         $warning = &mt('No items found in archive.');
                   11802:     }
                   11803:     if ($error) {
                   11804:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11805:                    $error.'</p>'."\n";
                   11806:     }
                   11807:     if ($warning) {
                   11808:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11809:     }
                   11810:     return $output;
                   11811: }
                   11812: 
1.1066    raeburn  11813: sub cleanup_empty_dirs {
                   11814:     my ($path) = @_;
                   11815:     if (($path ne '') && (-d $path)) {
                   11816:         if (opendir(my $dirh,$path)) {
                   11817:             my @dircontents = grep(!/^\./,readdir($dirh));
                   11818:             my $numitems = 0;
                   11819:             foreach my $item (@dircontents) {
                   11820:                 if (-d "$path/$item") {
1.1111    raeburn  11821:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  11822:                     if (-e "$path/$item") {
                   11823:                         $numitems ++;
                   11824:                     }
                   11825:                 } else {
                   11826:                     $numitems ++;
                   11827:                 }
                   11828:             }
                   11829:             if ($numitems == 0) {
                   11830:                 rmdir($path);
                   11831:             }
                   11832:             closedir($dirh);
                   11833:         }
                   11834:     }
                   11835:     return;
                   11836: }
                   11837: 
1.41      ng       11838: =pod
1.45      matthew  11839: 
1.1068    raeburn  11840: =item &get_folder_hierarchy()
                   11841: 
                   11842: Provides hierarchy of names of folders/sub-folders containing the current
                   11843: item,
                   11844: 
                   11845: Inputs: 3
                   11846:      - $navmap - navmaps object
                   11847: 
                   11848:      - $map - url for map (either the trigger itself, or map containing
                   11849:                            the resource, which is the trigger).
                   11850: 
                   11851:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   11852: 
                   11853: Outputs: 1 @pathitems - array of folder/subfolder names.
                   11854: 
                   11855: =cut
                   11856: 
                   11857: sub get_folder_hierarchy {
                   11858:     my ($navmap,$map,$showitem) = @_;
                   11859:     my @pathitems;
                   11860:     if (ref($navmap)) {
                   11861:         my $mapres = $navmap->getResourceByUrl($map);
                   11862:         if (ref($mapres)) {
                   11863:             my $pcslist = $mapres->map_hierarchy();
                   11864:             if ($pcslist ne '') {
                   11865:                 my @pcs = split(/,/,$pcslist);
                   11866:                 foreach my $pc (@pcs) {
                   11867:                     if ($pc == 1) {
1.1129    raeburn  11868:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  11869:                     } else {
                   11870:                         my $res = $navmap->getByMapPc($pc);
                   11871:                         if (ref($res)) {
                   11872:                             my $title = $res->compTitle();
                   11873:                             $title =~ s/\W+/_/g;
                   11874:                             if ($title ne '') {
                   11875:                                 push(@pathitems,$title);
                   11876:                             }
                   11877:                         }
                   11878:                     }
                   11879:                 }
                   11880:             }
1.1071    raeburn  11881:             if ($showitem) {
                   11882:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  11883:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  11884:                 } else {
                   11885:                     my $maptitle = $mapres->compTitle();
                   11886:                     $maptitle =~ s/\W+/_/g;
                   11887:                     if ($maptitle ne '') {
                   11888:                         push(@pathitems,$maptitle);
                   11889:                     }
1.1068    raeburn  11890:                 }
                   11891:             }
                   11892:         }
                   11893:     }
                   11894:     return @pathitems;
                   11895: }
                   11896: 
                   11897: =pod
                   11898: 
1.1015    raeburn  11899: =item * &get_turnedin_filepath()
                   11900: 
                   11901: Determines path in a user's portfolio file for storage of files uploaded
                   11902: to a specific essayresponse or dropbox item.
                   11903: 
                   11904: Inputs: 3 required + 1 optional.
                   11905: $symb is symb for resource, $uname and $udom are for current user (required).
                   11906: $caller is optional (can be "submission", if routine is called when storing
                   11907: an upoaded file when "Submit Answer" button was pressed).
                   11908: 
                   11909: Returns array containing $path and $multiresp. 
                   11910: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   11911: than one file upload item.  Callers of routine should append partid as a 
                   11912: subdirectory to $path in cases where $multiresp is 1.
                   11913: 
                   11914: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   11915: 
                   11916: =cut
                   11917: 
                   11918: sub get_turnedin_filepath {
                   11919:     my ($symb,$uname,$udom,$caller) = @_;
                   11920:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   11921:     my $turnindir;
                   11922:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   11923:     $turnindir = $userhash{'turnindir'};
                   11924:     my ($path,$multiresp);
                   11925:     if ($turnindir eq '') {
                   11926:         if ($caller eq 'submission') {
                   11927:             $turnindir = &mt('turned in');
                   11928:             $turnindir =~ s/\W+/_/g;
                   11929:             my %newhash = (
                   11930:                             'turnindir' => $turnindir,
                   11931:                           );
                   11932:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   11933:         }
                   11934:     }
                   11935:     if ($turnindir ne '') {
                   11936:         $path = '/'.$turnindir.'/';
                   11937:         my ($multipart,$turnin,@pathitems);
                   11938:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11939:         if (defined($navmap)) {
                   11940:             my $mapres = $navmap->getResourceByUrl($map);
                   11941:             if (ref($mapres)) {
                   11942:                 my $pcslist = $mapres->map_hierarchy();
                   11943:                 if ($pcslist ne '') {
                   11944:                     foreach my $pc (split(/,/,$pcslist)) {
                   11945:                         my $res = $navmap->getByMapPc($pc);
                   11946:                         if (ref($res)) {
                   11947:                             my $title = $res->compTitle();
                   11948:                             $title =~ s/\W+/_/g;
                   11949:                             if ($title ne '') {
                   11950:                                 push(@pathitems,$title);
                   11951:                             }
                   11952:                         }
                   11953:                     }
                   11954:                 }
                   11955:                 my $maptitle = $mapres->compTitle();
                   11956:                 $maptitle =~ s/\W+/_/g;
                   11957:                 if ($maptitle ne '') {
                   11958:                     push(@pathitems,$maptitle);
                   11959:                 }
                   11960:                 unless ($env{'request.state'} eq 'construct') {
                   11961:                     my $res = $navmap->getBySymb($symb);
                   11962:                     if (ref($res)) {
                   11963:                         my $partlist = $res->parts();
                   11964:                         my $totaluploads = 0;
                   11965:                         if (ref($partlist) eq 'ARRAY') {
                   11966:                             foreach my $part (@{$partlist}) {
                   11967:                                 my @types = $res->responseType($part);
                   11968:                                 my @ids = $res->responseIds($part);
                   11969:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   11970:                                     if ($types[$i] eq 'essay') {
                   11971:                                         my $partid = $part.'_'.$ids[$i];
                   11972:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   11973:                                             $totaluploads ++;
                   11974:                                         }
                   11975:                                     }
                   11976:                                 }
                   11977:                             }
                   11978:                             if ($totaluploads > 1) {
                   11979:                                 $multiresp = 1;
                   11980:                             }
                   11981:                         }
                   11982:                     }
                   11983:                 }
                   11984:             } else {
                   11985:                 return;
                   11986:             }
                   11987:         } else {
                   11988:             return;
                   11989:         }
                   11990:         my $restitle=&Apache::lonnet::gettitle($symb);
                   11991:         $restitle =~ s/\W+/_/g;
                   11992:         if ($restitle eq '') {
                   11993:             $restitle = ($resurl =~ m{/[^/]+$});
                   11994:             if ($restitle eq '') {
                   11995:                 $restitle = time;
                   11996:             }
                   11997:         }
                   11998:         push(@pathitems,$restitle);
                   11999:         $path .= join('/',@pathitems);
                   12000:     }
                   12001:     return ($path,$multiresp);
                   12002: }
                   12003: 
                   12004: =pod
                   12005: 
1.464     albertel 12006: =back
1.41      ng       12007: 
1.112     bowersj2 12008: =head1 CSV Upload/Handling functions
1.38      albertel 12009: 
1.41      ng       12010: =over 4
                   12011: 
1.648     raeburn  12012: =item * &upfile_store($r)
1.41      ng       12013: 
                   12014: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12015: needs $env{'form.upfile'}
1.41      ng       12016: returns $datatoken to be put into hidden field
                   12017: 
                   12018: =cut
1.31      albertel 12019: 
                   12020: sub upfile_store {
                   12021:     my $r=shift;
1.258     albertel 12022:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12023:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12024:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12025:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12026: 
1.258     albertel 12027:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12028: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12029:     {
1.158     raeburn  12030:         my $datafile = $r->dir_config('lonDaemons').
                   12031:                            '/tmp/'.$datatoken.'.tmp';
                   12032:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12033:             print $fh $env{'form.upfile'};
1.158     raeburn  12034:             close($fh);
                   12035:         }
1.31      albertel 12036:     }
                   12037:     return $datatoken;
                   12038: }
                   12039: 
1.56      matthew  12040: =pod
                   12041: 
1.648     raeburn  12042: =item * &load_tmp_file($r)
1.41      ng       12043: 
                   12044: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12045: needs $env{'form.datatoken'},
                   12046: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12047: 
                   12048: =cut
1.31      albertel 12049: 
                   12050: sub load_tmp_file {
                   12051:     my $r=shift;
                   12052:     my @studentdata=();
                   12053:     {
1.158     raeburn  12054:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12055:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12056:         if ( open(my $fh,"<$studentfile") ) {
                   12057:             @studentdata=<$fh>;
                   12058:             close($fh);
                   12059:         }
1.31      albertel 12060:     }
1.258     albertel 12061:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12062: }
                   12063: 
1.56      matthew  12064: =pod
                   12065: 
1.648     raeburn  12066: =item * &upfile_record_sep()
1.41      ng       12067: 
                   12068: Separate uploaded file into records
                   12069: returns array of records,
1.258     albertel 12070: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12071: 
                   12072: =cut
1.31      albertel 12073: 
                   12074: sub upfile_record_sep {
1.258     albertel 12075:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12076:     } else {
1.248     albertel 12077: 	my @records;
1.258     albertel 12078: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12079: 	    if ($line=~/^\s*$/) { next; }
                   12080: 	    push(@records,$line);
                   12081: 	}
                   12082: 	return @records;
1.31      albertel 12083:     }
                   12084: }
                   12085: 
1.56      matthew  12086: =pod
                   12087: 
1.648     raeburn  12088: =item * &record_sep($record)
1.41      ng       12089: 
1.258     albertel 12090: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12091: 
                   12092: =cut
                   12093: 
1.263     www      12094: sub takeleft {
                   12095:     my $index=shift;
                   12096:     return substr('0000'.$index,-4,4);
                   12097: }
                   12098: 
1.31      albertel 12099: sub record_sep {
                   12100:     my $record=shift;
                   12101:     my %components=();
1.258     albertel 12102:     if ($env{'form.upfiletype'} eq 'xml') {
                   12103:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12104:         my $i=0;
1.356     albertel 12105:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12106:             $field=~s/^(\"|\')//;
                   12107:             $field=~s/(\"|\')$//;
1.263     www      12108:             $components{&takeleft($i)}=$field;
1.31      albertel 12109:             $i++;
                   12110:         }
1.258     albertel 12111:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12112:         my $i=0;
1.356     albertel 12113:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12114:             $field=~s/^(\"|\')//;
                   12115:             $field=~s/(\"|\')$//;
1.263     www      12116:             $components{&takeleft($i)}=$field;
1.31      albertel 12117:             $i++;
                   12118:         }
                   12119:     } else {
1.561     www      12120:         my $separator=',';
1.480     banghart 12121:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12122:             $separator=';';
1.480     banghart 12123:         }
1.31      albertel 12124:         my $i=0;
1.561     www      12125: # the character we are looking for to indicate the end of a quote or a record 
                   12126:         my $looking_for=$separator;
                   12127: # do not add the characters to the fields
                   12128:         my $ignore=0;
                   12129: # we just encountered a separator (or the beginning of the record)
                   12130:         my $just_found_separator=1;
                   12131: # store the field we are working on here
                   12132:         my $field='';
                   12133: # work our way through all characters in record
                   12134:         foreach my $character ($record=~/(.)/g) {
                   12135:             if ($character eq $looking_for) {
                   12136:                if ($character ne $separator) {
                   12137: # Found the end of a quote, again looking for separator
                   12138:                   $looking_for=$separator;
                   12139:                   $ignore=1;
                   12140:                } else {
                   12141: # Found a separator, store away what we got
                   12142:                   $components{&takeleft($i)}=$field;
                   12143: 	          $i++;
                   12144:                   $just_found_separator=1;
                   12145:                   $ignore=0;
                   12146:                   $field='';
                   12147:                }
                   12148:                next;
                   12149:             }
                   12150: # single or double quotation marks after a separator indicate beginning of a quote
                   12151: # we are now looking for the end of the quote and need to ignore separators
                   12152:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12153:                $looking_for=$character;
                   12154:                next;
                   12155:             }
                   12156: # ignore would be true after we reached the end of a quote
                   12157:             if ($ignore) { next; }
                   12158:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12159:             $field.=$character;
                   12160:             $just_found_separator=0; 
1.31      albertel 12161:         }
1.561     www      12162: # catch the very last entry, since we never encountered the separator
                   12163:         $components{&takeleft($i)}=$field;
1.31      albertel 12164:     }
                   12165:     return %components;
                   12166: }
                   12167: 
1.144     matthew  12168: ######################################################
                   12169: ######################################################
                   12170: 
1.56      matthew  12171: =pod
                   12172: 
1.648     raeburn  12173: =item * &upfile_select_html()
1.41      ng       12174: 
1.144     matthew  12175: Return HTML code to select a file from the users machine and specify 
                   12176: the file type.
1.41      ng       12177: 
                   12178: =cut
                   12179: 
1.144     matthew  12180: ######################################################
                   12181: ######################################################
1.31      albertel 12182: sub upfile_select_html {
1.144     matthew  12183:     my %Types = (
                   12184:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12185:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12186:                  space => &mt('Space separated'),
                   12187:                  tab   => &mt('Tabulator separated'),
                   12188: #                 xml   => &mt('HTML/XML'),
                   12189:                  );
                   12190:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12191:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12192:     foreach my $type (sort(keys(%Types))) {
                   12193:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12194:     }
                   12195:     $Str .= "</select>\n";
                   12196:     return $Str;
1.31      albertel 12197: }
                   12198: 
1.301     albertel 12199: sub get_samples {
                   12200:     my ($records,$toget) = @_;
                   12201:     my @samples=({});
                   12202:     my $got=0;
                   12203:     foreach my $rec (@$records) {
                   12204: 	my %temp = &record_sep($rec);
                   12205: 	if (! grep(/\S/, values(%temp))) { next; }
                   12206: 	if (%temp) {
                   12207: 	    $samples[$got]=\%temp;
                   12208: 	    $got++;
                   12209: 	    if ($got == $toget) { last; }
                   12210: 	}
                   12211:     }
                   12212:     return \@samples;
                   12213: }
                   12214: 
1.144     matthew  12215: ######################################################
                   12216: ######################################################
                   12217: 
1.56      matthew  12218: =pod
                   12219: 
1.648     raeburn  12220: =item * &csv_print_samples($r,$records)
1.41      ng       12221: 
                   12222: Prints a table of sample values from each column uploaded $r is an
                   12223: Apache Request ref, $records is an arrayref from
                   12224: &Apache::loncommon::upfile_record_sep
                   12225: 
                   12226: =cut
                   12227: 
1.144     matthew  12228: ######################################################
                   12229: ######################################################
1.31      albertel 12230: sub csv_print_samples {
                   12231:     my ($r,$records) = @_;
1.662     bisitz   12232:     my $samples = &get_samples($records,5);
1.301     albertel 12233: 
1.594     raeburn  12234:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12235:               &start_data_table_header_row());
1.356     albertel 12236:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12237:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12238:     $r->print(&end_data_table_header_row());
1.301     albertel 12239:     foreach my $hash (@$samples) {
1.594     raeburn  12240: 	$r->print(&start_data_table_row());
1.356     albertel 12241: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12242: 	    $r->print('<td>');
1.356     albertel 12243: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12244: 	    $r->print('</td>');
                   12245: 	}
1.594     raeburn  12246: 	$r->print(&end_data_table_row());
1.31      albertel 12247:     }
1.594     raeburn  12248:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12249: }
                   12250: 
1.144     matthew  12251: ######################################################
                   12252: ######################################################
                   12253: 
1.56      matthew  12254: =pod
                   12255: 
1.648     raeburn  12256: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12257: 
                   12258: Prints a table to create associations between values and table columns.
1.144     matthew  12259: 
1.41      ng       12260: $r is an Apache Request ref,
                   12261: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12262: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12263: 
                   12264: =cut
                   12265: 
1.144     matthew  12266: ######################################################
                   12267: ######################################################
1.31      albertel 12268: sub csv_print_select_table {
                   12269:     my ($r,$records,$d) = @_;
1.301     albertel 12270:     my $i=0;
                   12271:     my $samples = &get_samples($records,1);
1.144     matthew  12272:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12273: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12274:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12275:               '<th>'.&mt('Column').'</th>'.
                   12276:               &end_data_table_header_row()."\n");
1.356     albertel 12277:     foreach my $array_ref (@$d) {
                   12278: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12279: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12280: 
1.875     bisitz   12281: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12282: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12283: 	$r->print('<option value="none"></option>');
1.356     albertel 12284: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12285: 	    $r->print('<option value="'.$sample.'"'.
                   12286:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12287:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12288: 	}
1.594     raeburn  12289: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12290: 	$i++;
                   12291:     }
1.594     raeburn  12292:     $r->print(&end_data_table());
1.31      albertel 12293:     $i--;
                   12294:     return $i;
                   12295: }
1.56      matthew  12296: 
1.144     matthew  12297: ######################################################
                   12298: ######################################################
                   12299: 
1.56      matthew  12300: =pod
1.31      albertel 12301: 
1.648     raeburn  12302: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12303: 
                   12304: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12305: 
                   12306: $r is an Apache Request ref,
                   12307: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12308: $d is an array of 2 element arrays (internal name, displayed name)
                   12309: 
                   12310: =cut
                   12311: 
1.144     matthew  12312: ######################################################
                   12313: ######################################################
1.31      albertel 12314: sub csv_samples_select_table {
                   12315:     my ($r,$records,$d) = @_;
                   12316:     my $i=0;
1.144     matthew  12317:     #
1.662     bisitz   12318:     my $max_samples = 5;
                   12319:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12320:     $r->print(&start_data_table().
                   12321:               &start_data_table_header_row().'<th>'.
                   12322:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12323:               &end_data_table_header_row());
1.301     albertel 12324: 
                   12325:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12326: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12327: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12328: 	foreach my $option (@$d) {
                   12329: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12330: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12331:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12332:                       $display.'</option>');
1.31      albertel 12333: 	}
                   12334: 	$r->print('</select></td><td>');
1.662     bisitz   12335: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12336: 	    if (defined($samples->[$line]{$key})) { 
                   12337: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12338: 	    }
                   12339: 	}
1.594     raeburn  12340: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12341: 	$i++;
                   12342:     }
1.594     raeburn  12343:     $r->print(&end_data_table());
1.31      albertel 12344:     $i--;
                   12345:     return($i);
1.115     matthew  12346: }
                   12347: 
1.144     matthew  12348: ######################################################
                   12349: ######################################################
                   12350: 
1.115     matthew  12351: =pod
                   12352: 
1.648     raeburn  12353: =item * &clean_excel_name($name)
1.115     matthew  12354: 
                   12355: Returns a replacement for $name which does not contain any illegal characters.
                   12356: 
                   12357: =cut
                   12358: 
1.144     matthew  12359: ######################################################
                   12360: ######################################################
1.115     matthew  12361: sub clean_excel_name {
                   12362:     my ($name) = @_;
                   12363:     $name =~ s/[:\*\?\/\\]//g;
                   12364:     if (length($name) > 31) {
                   12365:         $name = substr($name,0,31);
                   12366:     }
                   12367:     return $name;
1.25      albertel 12368: }
1.84      albertel 12369: 
1.85      albertel 12370: =pod
                   12371: 
1.648     raeburn  12372: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12373: 
                   12374: Returns either 1 or undef
                   12375: 
                   12376: 1 if the part is to be hidden, undef if it is to be shown
                   12377: 
                   12378: Arguments are:
                   12379: 
                   12380: $id the id of the part to be checked
                   12381: $symb, optional the symb of the resource to check
                   12382: $udom, optional the domain of the user to check for
                   12383: $uname, optional the username of the user to check for
                   12384: 
                   12385: =cut
1.84      albertel 12386: 
                   12387: sub check_if_partid_hidden {
                   12388:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12389:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12390: 					 $symb,$udom,$uname);
1.141     albertel 12391:     my $truth=1;
                   12392:     #if the string starts with !, then the list is the list to show not hide
                   12393:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12394:     my @hiddenlist=split(/,/,$hiddenparts);
                   12395:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12396: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12397:     }
1.141     albertel 12398:     return !$truth;
1.84      albertel 12399: }
1.127     matthew  12400: 
1.138     matthew  12401: 
                   12402: ############################################################
                   12403: ############################################################
                   12404: 
                   12405: =pod
                   12406: 
1.157     matthew  12407: =back 
                   12408: 
1.138     matthew  12409: =head1 cgi-bin script and graphing routines
                   12410: 
1.157     matthew  12411: =over 4
                   12412: 
1.648     raeburn  12413: =item * &get_cgi_id()
1.138     matthew  12414: 
                   12415: Inputs: none
                   12416: 
                   12417: Returns an id which can be used to pass environment variables
                   12418: to various cgi-bin scripts.  These environment variables will
                   12419: be removed from the users environment after a given time by
                   12420: the routine &Apache::lonnet::transfer_profile_to_env.
                   12421: 
                   12422: =cut
                   12423: 
                   12424: ############################################################
                   12425: ############################################################
1.152     albertel 12426: my $uniq=0;
1.136     matthew  12427: sub get_cgi_id {
1.154     albertel 12428:     $uniq=($uniq+1)%100000;
1.280     albertel 12429:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12430: }
                   12431: 
1.127     matthew  12432: ############################################################
                   12433: ############################################################
                   12434: 
                   12435: =pod
                   12436: 
1.648     raeburn  12437: =item * &DrawBarGraph()
1.127     matthew  12438: 
1.138     matthew  12439: Facilitates the plotting of data in a (stacked) bar graph.
                   12440: Puts plot definition data into the users environment in order for 
                   12441: graph.png to plot it.  Returns an <img> tag for the plot.
                   12442: The bars on the plot are labeled '1','2',...,'n'.
                   12443: 
                   12444: Inputs:
                   12445: 
                   12446: =over 4
                   12447: 
                   12448: =item $Title: string, the title of the plot
                   12449: 
                   12450: =item $xlabel: string, text describing the X-axis of the plot
                   12451: 
                   12452: =item $ylabel: string, text describing the Y-axis of the plot
                   12453: 
                   12454: =item $Max: scalar, the maximum Y value to use in the plot
                   12455: If $Max is < any data point, the graph will not be rendered.
                   12456: 
1.140     matthew  12457: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12458: they are plotted.  If undefined, default values will be used.
                   12459: 
1.178     matthew  12460: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12461: 
1.138     matthew  12462: =item @Values: An array of array references.  Each array reference holds data
                   12463: to be plotted in a stacked bar chart.
                   12464: 
1.239     matthew  12465: =item If the final element of @Values is a hash reference the key/value
                   12466: pairs will be added to the graph definition.
                   12467: 
1.138     matthew  12468: =back
                   12469: 
                   12470: Returns:
                   12471: 
                   12472: An <img> tag which references graph.png and the appropriate identifying
                   12473: information for the plot.
                   12474: 
1.127     matthew  12475: =cut
                   12476: 
                   12477: ############################################################
                   12478: ############################################################
1.134     matthew  12479: sub DrawBarGraph {
1.178     matthew  12480:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12481:     #
                   12482:     if (! defined($colors)) {
                   12483:         $colors = ['#33ff00', 
                   12484:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12485:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12486:                   ]; 
                   12487:     }
1.228     matthew  12488:     my $extra_settings = {};
                   12489:     if (ref($Values[-1]) eq 'HASH') {
                   12490:         $extra_settings = pop(@Values);
                   12491:     }
1.127     matthew  12492:     #
1.136     matthew  12493:     my $identifier = &get_cgi_id();
                   12494:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12495:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12496:         return '';
                   12497:     }
1.225     matthew  12498:     #
                   12499:     my @Labels;
                   12500:     if (defined($labels)) {
                   12501:         @Labels = @$labels;
                   12502:     } else {
                   12503:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12504:             push (@Labels,$i+1);
                   12505:         }
                   12506:     }
                   12507:     #
1.129     matthew  12508:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12509:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12510:     my %ValuesHash;
                   12511:     my $NumSets=1;
                   12512:     foreach my $array (@Values) {
                   12513:         next if (! ref($array));
1.136     matthew  12514:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12515:             join(',',@$array);
1.129     matthew  12516:     }
1.127     matthew  12517:     #
1.136     matthew  12518:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12519:     if ($NumBars < 3) {
                   12520:         $width = 120+$NumBars*32;
1.220     matthew  12521:         $xskip = 1;
1.225     matthew  12522:         $bar_width = 30;
                   12523:     } elsif ($NumBars < 5) {
                   12524:         $width = 120+$NumBars*20;
                   12525:         $xskip = 1;
                   12526:         $bar_width = 20;
1.220     matthew  12527:     } elsif ($NumBars < 10) {
1.136     matthew  12528:         $width = 120+$NumBars*15;
                   12529:         $xskip = 1;
                   12530:         $bar_width = 15;
                   12531:     } elsif ($NumBars <= 25) {
                   12532:         $width = 120+$NumBars*11;
                   12533:         $xskip = 5;
                   12534:         $bar_width = 8;
                   12535:     } elsif ($NumBars <= 50) {
                   12536:         $width = 120+$NumBars*8;
                   12537:         $xskip = 5;
                   12538:         $bar_width = 4;
                   12539:     } else {
                   12540:         $width = 120+$NumBars*8;
                   12541:         $xskip = 5;
                   12542:         $bar_width = 4;
                   12543:     }
                   12544:     #
1.137     matthew  12545:     $Max = 1 if ($Max < 1);
                   12546:     if ( int($Max) < $Max ) {
                   12547:         $Max++;
                   12548:         $Max = int($Max);
                   12549:     }
1.127     matthew  12550:     $Title  = '' if (! defined($Title));
                   12551:     $xlabel = '' if (! defined($xlabel));
                   12552:     $ylabel = '' if (! defined($ylabel));
1.369     www      12553:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12554:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12555:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12556:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12557:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12558:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12559:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12560:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12561:     $ValuesHash{$id.'.height'}   = $height;
                   12562:     $ValuesHash{$id.'.width'}    = $width;
                   12563:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12564:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12565:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12566:     #
1.228     matthew  12567:     # Deal with other parameters
                   12568:     while (my ($key,$value) = each(%$extra_settings)) {
                   12569:         $ValuesHash{$id.'.'.$key} = $value;
                   12570:     }
                   12571:     #
1.646     raeburn  12572:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12573:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12574: }
                   12575: 
                   12576: ############################################################
                   12577: ############################################################
                   12578: 
                   12579: =pod
                   12580: 
1.648     raeburn  12581: =item * &DrawXYGraph()
1.137     matthew  12582: 
1.138     matthew  12583: Facilitates the plotting of data in an XY graph.
                   12584: Puts plot definition data into the users environment in order for 
                   12585: graph.png to plot it.  Returns an <img> tag for the plot.
                   12586: 
                   12587: Inputs:
                   12588: 
                   12589: =over 4
                   12590: 
                   12591: =item $Title: string, the title of the plot
                   12592: 
                   12593: =item $xlabel: string, text describing the X-axis of the plot
                   12594: 
                   12595: =item $ylabel: string, text describing the Y-axis of the plot
                   12596: 
                   12597: =item $Max: scalar, the maximum Y value to use in the plot
                   12598: If $Max is < any data point, the graph will not be rendered.
                   12599: 
                   12600: =item $colors: Array ref containing the hex color codes for the data to be 
                   12601: plotted in.  If undefined, default values will be used.
                   12602: 
                   12603: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12604: 
                   12605: =item $Ydata: Array ref containing Array refs.  
1.185     www      12606: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12607: 
                   12608: =item %Values: hash indicating or overriding any default values which are 
                   12609: passed to graph.png.  
                   12610: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12611: 
                   12612: =back
                   12613: 
                   12614: Returns:
                   12615: 
                   12616: An <img> tag which references graph.png and the appropriate identifying
                   12617: information for the plot.
                   12618: 
1.137     matthew  12619: =cut
                   12620: 
                   12621: ############################################################
                   12622: ############################################################
                   12623: sub DrawXYGraph {
                   12624:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12625:     #
                   12626:     # Create the identifier for the graph
                   12627:     my $identifier = &get_cgi_id();
                   12628:     my $id = 'cgi.'.$identifier;
                   12629:     #
                   12630:     $Title  = '' if (! defined($Title));
                   12631:     $xlabel = '' if (! defined($xlabel));
                   12632:     $ylabel = '' if (! defined($ylabel));
                   12633:     my %ValuesHash = 
                   12634:         (
1.369     www      12635:          $id.'.title'  => &escape($Title),
                   12636:          $id.'.xlabel' => &escape($xlabel),
                   12637:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12638:          $id.'.y_max_value'=> $Max,
                   12639:          $id.'.labels'     => join(',',@$Xlabels),
                   12640:          $id.'.PlotType'   => 'XY',
                   12641:          );
                   12642:     #
                   12643:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12644:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12645:     }
                   12646:     #
                   12647:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12648:         return '';
                   12649:     }
                   12650:     my $NumSets=1;
1.138     matthew  12651:     foreach my $array (@{$Ydata}){
1.137     matthew  12652:         next if (! ref($array));
                   12653:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12654:     }
1.138     matthew  12655:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12656:     #
                   12657:     # Deal with other parameters
                   12658:     while (my ($key,$value) = each(%Values)) {
                   12659:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12660:     }
                   12661:     #
1.646     raeburn  12662:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12663:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12664: }
                   12665: 
                   12666: ############################################################
                   12667: ############################################################
                   12668: 
                   12669: =pod
                   12670: 
1.648     raeburn  12671: =item * &DrawXYYGraph()
1.138     matthew  12672: 
                   12673: Facilitates the plotting of data in an XY graph with two Y axes.
                   12674: Puts plot definition data into the users environment in order for 
                   12675: graph.png to plot it.  Returns an <img> tag for the plot.
                   12676: 
                   12677: Inputs:
                   12678: 
                   12679: =over 4
                   12680: 
                   12681: =item $Title: string, the title of the plot
                   12682: 
                   12683: =item $xlabel: string, text describing the X-axis of the plot
                   12684: 
                   12685: =item $ylabel: string, text describing the Y-axis of the plot
                   12686: 
                   12687: =item $colors: Array ref containing the hex color codes for the data to be 
                   12688: plotted in.  If undefined, default values will be used.
                   12689: 
                   12690: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12691: 
                   12692: =item $Ydata1: The first data set
                   12693: 
                   12694: =item $Min1: The minimum value of the left Y-axis
                   12695: 
                   12696: =item $Max1: The maximum value of the left Y-axis
                   12697: 
                   12698: =item $Ydata2: The second data set
                   12699: 
                   12700: =item $Min2: The minimum value of the right Y-axis
                   12701: 
                   12702: =item $Max2: The maximum value of the left Y-axis
                   12703: 
                   12704: =item %Values: hash indicating or overriding any default values which are 
                   12705: passed to graph.png.  
                   12706: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12707: 
                   12708: =back
                   12709: 
                   12710: Returns:
                   12711: 
                   12712: An <img> tag which references graph.png and the appropriate identifying
                   12713: information for the plot.
1.136     matthew  12714: 
                   12715: =cut
                   12716: 
                   12717: ############################################################
                   12718: ############################################################
1.137     matthew  12719: sub DrawXYYGraph {
                   12720:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12721:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12722:     #
                   12723:     # Create the identifier for the graph
                   12724:     my $identifier = &get_cgi_id();
                   12725:     my $id = 'cgi.'.$identifier;
                   12726:     #
                   12727:     $Title  = '' if (! defined($Title));
                   12728:     $xlabel = '' if (! defined($xlabel));
                   12729:     $ylabel = '' if (! defined($ylabel));
                   12730:     my %ValuesHash = 
                   12731:         (
1.369     www      12732:          $id.'.title'  => &escape($Title),
                   12733:          $id.'.xlabel' => &escape($xlabel),
                   12734:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  12735:          $id.'.labels' => join(',',@$Xlabels),
                   12736:          $id.'.PlotType' => 'XY',
                   12737:          $id.'.NumSets' => 2,
1.137     matthew  12738:          $id.'.two_axes' => 1,
                   12739:          $id.'.y1_max_value' => $Max1,
                   12740:          $id.'.y1_min_value' => $Min1,
                   12741:          $id.'.y2_max_value' => $Max2,
                   12742:          $id.'.y2_min_value' => $Min2,
1.136     matthew  12743:          );
                   12744:     #
1.137     matthew  12745:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12746:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12747:     }
                   12748:     #
                   12749:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   12750:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  12751:         return '';
                   12752:     }
                   12753:     my $NumSets=1;
1.137     matthew  12754:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  12755:         next if (! ref($array));
                   12756:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  12757:     }
                   12758:     #
                   12759:     # Deal with other parameters
                   12760:     while (my ($key,$value) = each(%Values)) {
                   12761:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  12762:     }
                   12763:     #
1.646     raeburn  12764:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 12765:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  12766: }
                   12767: 
                   12768: ############################################################
                   12769: ############################################################
                   12770: 
                   12771: =pod
                   12772: 
1.157     matthew  12773: =back 
                   12774: 
1.139     matthew  12775: =head1 Statistics helper routines?  
                   12776: 
                   12777: Bad place for them but what the hell.
                   12778: 
1.157     matthew  12779: =over 4
                   12780: 
1.648     raeburn  12781: =item * &chartlink()
1.139     matthew  12782: 
                   12783: Returns a link to the chart for a specific student.  
                   12784: 
                   12785: Inputs:
                   12786: 
                   12787: =over 4
                   12788: 
                   12789: =item $linktext: The text of the link
                   12790: 
                   12791: =item $sname: The students username
                   12792: 
                   12793: =item $sdomain: The students domain
                   12794: 
                   12795: =back
                   12796: 
1.157     matthew  12797: =back
                   12798: 
1.139     matthew  12799: =cut
                   12800: 
                   12801: ############################################################
                   12802: ############################################################
                   12803: sub chartlink {
                   12804:     my ($linktext, $sname, $sdomain) = @_;
                   12805:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      12806:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 12807:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  12808:        '">'.$linktext.'</a>';
1.153     matthew  12809: }
                   12810: 
                   12811: #######################################################
                   12812: #######################################################
                   12813: 
                   12814: =pod
                   12815: 
                   12816: =head1 Course Environment Routines
1.157     matthew  12817: 
                   12818: =over 4
1.153     matthew  12819: 
1.648     raeburn  12820: =item * &restore_course_settings()
1.153     matthew  12821: 
1.648     raeburn  12822: =item * &store_course_settings()
1.153     matthew  12823: 
                   12824: Restores/Store indicated form parameters from the course environment.
                   12825: Will not overwrite existing values of the form parameters.
                   12826: 
                   12827: Inputs: 
                   12828: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   12829: 
                   12830: a hash ref describing the data to be stored.  For example:
                   12831:    
                   12832: %Save_Parameters = ('Status' => 'scalar',
                   12833:     'chartoutputmode' => 'scalar',
                   12834:     'chartoutputdata' => 'scalar',
                   12835:     'Section' => 'array',
1.373     raeburn  12836:     'Group' => 'array',
1.153     matthew  12837:     'StudentData' => 'array',
                   12838:     'Maps' => 'array');
                   12839: 
                   12840: Returns: both routines return nothing
                   12841: 
1.631     raeburn  12842: =back
                   12843: 
1.153     matthew  12844: =cut
                   12845: 
                   12846: #######################################################
                   12847: #######################################################
                   12848: sub store_course_settings {
1.496     albertel 12849:     return &store_settings($env{'request.course.id'},@_);
                   12850: }
                   12851: 
                   12852: sub store_settings {
1.153     matthew  12853:     # save to the environment
                   12854:     # appenv the same items, just to be safe
1.300     albertel 12855:     my $udom  = $env{'user.domain'};
                   12856:     my $uname = $env{'user.name'};
1.496     albertel 12857:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12858:     my %SaveHash;
                   12859:     my %AppHash;
                   12860:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 12861:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 12862:         my $envname = 'environment.'.$basename;
1.258     albertel 12863:         if (exists($env{'form.'.$setting})) {
1.153     matthew  12864:             # Save this value away
                   12865:             if ($type eq 'scalar' &&
1.258     albertel 12866:                 (! exists($env{$envname}) || 
                   12867:                  $env{$envname} ne $env{'form.'.$setting})) {
                   12868:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   12869:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  12870:             } elsif ($type eq 'array') {
                   12871:                 my $stored_form;
1.258     albertel 12872:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  12873:                     $stored_form = join(',',
                   12874:                                         map {
1.369     www      12875:                                             &escape($_);
1.258     albertel 12876:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  12877:                 } else {
                   12878:                     $stored_form = 
1.369     www      12879:                         &escape($env{'form.'.$setting});
1.153     matthew  12880:                 }
                   12881:                 # Determine if the array contents are the same.
1.258     albertel 12882:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  12883:                     $SaveHash{$basename} = $stored_form;
                   12884:                     $AppHash{$envname}   = $stored_form;
                   12885:                 }
                   12886:             }
                   12887:         }
                   12888:     }
                   12889:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 12890:                                           $udom,$uname);
1.153     matthew  12891:     if ($put_result !~ /^(ok|delayed)/) {
                   12892:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   12893:                                  'got error:'.$put_result);
                   12894:     }
                   12895:     # Make sure these settings stick around in this session, too
1.646     raeburn  12896:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  12897:     return;
                   12898: }
                   12899: 
                   12900: sub restore_course_settings {
1.499     albertel 12901:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 12902: }
                   12903: 
                   12904: sub restore_settings {
                   12905:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12906:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 12907:         next if (exists($env{'form.'.$setting}));
1.496     albertel 12908:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  12909:             '.'.$setting;
1.258     albertel 12910:         if (exists($env{$envname})) {
1.153     matthew  12911:             if ($type eq 'scalar') {
1.258     albertel 12912:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  12913:             } elsif ($type eq 'array') {
1.258     albertel 12914:                 $env{'form.'.$setting} = [ 
1.153     matthew  12915:                                            map { 
1.369     www      12916:                                                &unescape($_); 
1.258     albertel 12917:                                            } split(',',$env{$envname})
1.153     matthew  12918:                                            ];
                   12919:             }
                   12920:         }
                   12921:     }
1.127     matthew  12922: }
                   12923: 
1.618     raeburn  12924: #######################################################
                   12925: #######################################################
                   12926: 
                   12927: =pod
                   12928: 
                   12929: =head1 Domain E-mail Routines  
                   12930: 
                   12931: =over 4
                   12932: 
1.648     raeburn  12933: =item * &build_recipient_list()
1.618     raeburn  12934: 
1.884     raeburn  12935: Build recipient lists for five types of e-mail:
1.766     raeburn  12936: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.884     raeburn  12937: (d) Help requests, (e) Course requests needing approval,  generated by
                   12938: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
                   12939: loncoursequeueadmin.pm respectively.
1.618     raeburn  12940: 
                   12941: Inputs:
1.619     raeburn  12942: defmail (scalar - email address of default recipient), 
1.618     raeburn  12943: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  12944: defdom (domain for which to retrieve configuration settings),
                   12945: origmail (scalar - email address of recipient from loncapa.conf, 
                   12946: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  12947: 
1.655     raeburn  12948: Returns: comma separated list of addresses to which to send e-mail.
                   12949: 
                   12950: =back
1.618     raeburn  12951: 
                   12952: =cut
                   12953: 
                   12954: ############################################################
                   12955: ############################################################
                   12956: sub build_recipient_list {
1.619     raeburn  12957:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  12958:     my @recipients;
                   12959:     my $otheremails;
                   12960:     my %domconfig =
                   12961:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   12962:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  12963:         if (exists($domconfig{'contacts'}{$mailing})) {
                   12964:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   12965:                 my @contacts = ('adminemail','supportemail');
                   12966:                 foreach my $item (@contacts) {
                   12967:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   12968:                         my $addr = $domconfig{'contacts'}{$item}; 
                   12969:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12970:                             push(@recipients,$addr);
                   12971:                         }
1.619     raeburn  12972:                     }
1.766     raeburn  12973:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  12974:                 }
                   12975:             }
1.766     raeburn  12976:         } elsif ($origmail ne '') {
                   12977:             push(@recipients,$origmail);
1.618     raeburn  12978:         }
1.619     raeburn  12979:     } elsif ($origmail ne '') {
                   12980:         push(@recipients,$origmail);
1.618     raeburn  12981:     }
1.688     raeburn  12982:     if (defined($defmail)) {
                   12983:         if ($defmail ne '') {
                   12984:             push(@recipients,$defmail);
                   12985:         }
1.618     raeburn  12986:     }
                   12987:     if ($otheremails) {
1.619     raeburn  12988:         my @others;
                   12989:         if ($otheremails =~ /,/) {
                   12990:             @others = split(/,/,$otheremails);
1.618     raeburn  12991:         } else {
1.619     raeburn  12992:             push(@others,$otheremails);
                   12993:         }
                   12994:         foreach my $addr (@others) {
                   12995:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12996:                 push(@recipients,$addr);
                   12997:             }
1.618     raeburn  12998:         }
                   12999:     }
1.619     raeburn  13000:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13001:     return $recipientlist;
                   13002: }
                   13003: 
1.127     matthew  13004: ############################################################
                   13005: ############################################################
1.154     albertel 13006: 
1.655     raeburn  13007: =pod
                   13008: 
                   13009: =head1 Course Catalog Routines
                   13010: 
                   13011: =over 4
                   13012: 
                   13013: =item * &gather_categories()
                   13014: 
                   13015: Converts category definitions - keys of categories hash stored in  
                   13016: coursecategories in configuration.db on the primary library server in a 
                   13017: domain - to an array.  Also generates javascript and idx hash used to 
                   13018: generate Domain Coordinator interface for editing Course Categories.
                   13019: 
                   13020: Inputs:
1.663     raeburn  13021: 
1.655     raeburn  13022: categories (reference to hash of category definitions).
1.663     raeburn  13023: 
1.655     raeburn  13024: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13025:       categories and subcategories).
1.663     raeburn  13026: 
1.655     raeburn  13027: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13028:       editing Course Categories).
1.663     raeburn  13029: 
1.655     raeburn  13030: jsarray (reference to array of categories used to create Javascript arrays for
                   13031:          Domain Coordinator interface for editing Course Categories).
                   13032: 
                   13033: Returns: nothing
                   13034: 
                   13035: Side effects: populates cats, idx and jsarray. 
                   13036: 
                   13037: =cut
                   13038: 
                   13039: sub gather_categories {
                   13040:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13041:     my %counters;
                   13042:     my $num = 0;
                   13043:     foreach my $item (keys(%{$categories})) {
                   13044:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13045:         if ($container eq '' && $depth == 0) {
                   13046:             $cats->[$depth][$categories->{$item}] = $cat;
                   13047:         } else {
                   13048:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13049:         }
                   13050:         my ($escitem,$tail) = split(/:/,$item,2);
                   13051:         if ($counters{$tail} eq '') {
                   13052:             $counters{$tail} = $num;
                   13053:             $num ++;
                   13054:         }
                   13055:         if (ref($idx) eq 'HASH') {
                   13056:             $idx->{$item} = $counters{$tail};
                   13057:         }
                   13058:         if (ref($jsarray) eq 'ARRAY') {
                   13059:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13060:         }
                   13061:     }
                   13062:     return;
                   13063: }
                   13064: 
                   13065: =pod
                   13066: 
                   13067: =item * &extract_categories()
                   13068: 
                   13069: Used to generate breadcrumb trails for course categories.
                   13070: 
                   13071: Inputs:
1.663     raeburn  13072: 
1.655     raeburn  13073: categories (reference to hash of category definitions).
1.663     raeburn  13074: 
1.655     raeburn  13075: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13076:       categories and subcategories).
1.663     raeburn  13077: 
1.655     raeburn  13078: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13079: 
1.655     raeburn  13080: allitems (reference to hash - key is category key 
                   13081:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13082: 
1.655     raeburn  13083: idx (reference to hash of counters used in Domain Coordinator interface for
                   13084:       editing Course Categories).
1.663     raeburn  13085: 
1.655     raeburn  13086: jsarray (reference to array of categories used to create Javascript arrays for
                   13087:          Domain Coordinator interface for editing Course Categories).
                   13088: 
1.665     raeburn  13089: subcats (reference to hash of arrays containing all subcategories within each 
                   13090:          category, -recursive)
                   13091: 
1.655     raeburn  13092: Returns: nothing
                   13093: 
                   13094: Side effects: populates trails and allitems hash references.
                   13095: 
                   13096: =cut
                   13097: 
                   13098: sub extract_categories {
1.665     raeburn  13099:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13100:     if (ref($categories) eq 'HASH') {
                   13101:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13102:         if (ref($cats->[0]) eq 'ARRAY') {
                   13103:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13104:                 my $name = $cats->[0][$i];
                   13105:                 my $item = &escape($name).'::0';
                   13106:                 my $trailstr;
                   13107:                 if ($name eq 'instcode') {
                   13108:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13109:                 } elsif ($name eq 'communities') {
                   13110:                     $trailstr = &mt('Communities');
1.655     raeburn  13111:                 } else {
                   13112:                     $trailstr = $name;
                   13113:                 }
                   13114:                 if ($allitems->{$item} eq '') {
                   13115:                     push(@{$trails},$trailstr);
                   13116:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13117:                 }
                   13118:                 my @parents = ($name);
                   13119:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13120:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13121:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13122:                         if (ref($subcats) eq 'HASH') {
                   13123:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13124:                         }
                   13125:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13126:                     }
                   13127:                 } else {
                   13128:                     if (ref($subcats) eq 'HASH') {
                   13129:                         $subcats->{$item} = [];
1.655     raeburn  13130:                     }
                   13131:                 }
                   13132:             }
                   13133:         }
                   13134:     }
                   13135:     return;
                   13136: }
                   13137: 
                   13138: =pod
                   13139: 
                   13140: =item *&recurse_categories()
                   13141: 
                   13142: Recursively used to generate breadcrumb trails for course categories.
                   13143: 
                   13144: Inputs:
1.663     raeburn  13145: 
1.655     raeburn  13146: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13147:       categories and subcategories).
1.663     raeburn  13148: 
1.655     raeburn  13149: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13150: 
                   13151: category (current course category, for which breadcrumb trail is being generated).
                   13152: 
                   13153: trails (reference to array of breadcrumb trails for each category).
                   13154: 
1.655     raeburn  13155: allitems (reference to hash - key is category key
                   13156:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13157: 
1.655     raeburn  13158: parents (array containing containers directories for current category, 
                   13159:          back to top level). 
                   13160: 
                   13161: Returns: nothing
                   13162: 
                   13163: Side effects: populates trails and allitems hash references
                   13164: 
                   13165: =cut
                   13166: 
                   13167: sub recurse_categories {
1.665     raeburn  13168:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13169:     my $shallower = $depth - 1;
                   13170:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13171:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13172:             my $name = $cats->[$depth]{$category}[$k];
                   13173:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13174:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13175:             if ($allitems->{$item} eq '') {
                   13176:                 push(@{$trails},$trailstr);
                   13177:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13178:             }
                   13179:             my $deeper = $depth+1;
                   13180:             push(@{$parents},$category);
1.665     raeburn  13181:             if (ref($subcats) eq 'HASH') {
                   13182:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13183:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13184:                     my $higher;
                   13185:                     if ($j > 0) {
                   13186:                         $higher = &escape($parents->[$j]).':'.
                   13187:                                   &escape($parents->[$j-1]).':'.$j;
                   13188:                     } else {
                   13189:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13190:                     }
                   13191:                     push(@{$subcats->{$higher}},$subcat);
                   13192:                 }
                   13193:             }
                   13194:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13195:                                 $subcats);
1.655     raeburn  13196:             pop(@{$parents});
                   13197:         }
                   13198:     } else {
                   13199:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13200:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13201:         if ($allitems->{$item} eq '') {
                   13202:             push(@{$trails},$trailstr);
                   13203:             $allitems->{$item} = scalar(@{$trails})-1;
                   13204:         }
                   13205:     }
                   13206:     return;
                   13207: }
                   13208: 
1.663     raeburn  13209: =pod
                   13210: 
                   13211: =item *&assign_categories_table()
                   13212: 
                   13213: Create a datatable for display of hierarchical categories in a domain,
                   13214: with checkboxes to allow a course to be categorized. 
                   13215: 
                   13216: Inputs:
                   13217: 
                   13218: cathash - reference to hash of categories defined for the domain (from
                   13219:           configuration.db)
                   13220: 
                   13221: currcat - scalar with an & separated list of categories assigned to a course. 
                   13222: 
1.919     raeburn  13223: type    - scalar contains course type (Course or Community).
                   13224: 
1.663     raeburn  13225: Returns: $output (markup to be displayed) 
                   13226: 
                   13227: =cut
                   13228: 
                   13229: sub assign_categories_table {
1.919     raeburn  13230:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13231:     my $output;
                   13232:     if (ref($cathash) eq 'HASH') {
                   13233:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13234:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13235:         $maxdepth = scalar(@cats);
                   13236:         if (@cats > 0) {
                   13237:             my $itemcount = 0;
                   13238:             if (ref($cats[0]) eq 'ARRAY') {
                   13239:                 my @currcategories;
                   13240:                 if ($currcat ne '') {
                   13241:                     @currcategories = split('&',$currcat);
                   13242:                 }
1.919     raeburn  13243:                 my $table;
1.663     raeburn  13244:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13245:                     my $parent = $cats[0][$i];
1.919     raeburn  13246:                     next if ($parent eq 'instcode');
                   13247:                     if ($type eq 'Community') {
                   13248:                         next unless ($parent eq 'communities');
                   13249:                     } else {
                   13250:                         next if ($parent eq 'communities');
                   13251:                     }
1.663     raeburn  13252:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13253:                     my $item = &escape($parent).'::0';
                   13254:                     my $checked = '';
                   13255:                     if (@currcategories > 0) {
                   13256:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13257:                             $checked = ' checked="checked"';
1.663     raeburn  13258:                         }
                   13259:                     }
1.919     raeburn  13260:                     my $parent_title = $parent;
                   13261:                     if ($parent eq 'communities') {
                   13262:                         $parent_title = &mt('Communities');
                   13263:                     }
                   13264:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13265:                               '<input type="checkbox" name="usecategory" value="'.
                   13266:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13267:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13268:                     my $depth = 1;
                   13269:                     push(@path,$parent);
1.919     raeburn  13270:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13271:                     pop(@path);
1.919     raeburn  13272:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13273:                     $itemcount ++;
                   13274:                 }
1.919     raeburn  13275:                 if ($itemcount) {
                   13276:                     $output = &Apache::loncommon::start_data_table().
                   13277:                               $table.
                   13278:                               &Apache::loncommon::end_data_table();
                   13279:                 }
1.663     raeburn  13280:             }
                   13281:         }
                   13282:     }
                   13283:     return $output;
                   13284: }
                   13285: 
                   13286: =pod
                   13287: 
                   13288: =item *&assign_category_rows()
                   13289: 
                   13290: Create a datatable row for display of nested categories in a domain,
                   13291: with checkboxes to allow a course to be categorized,called recursively.
                   13292: 
                   13293: Inputs:
                   13294: 
                   13295: itemcount - track row number for alternating colors
                   13296: 
                   13297: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13298:       categories and subcategories.
                   13299: 
                   13300: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13301: 
                   13302: parent - parent of current category item
                   13303: 
                   13304: path - Array containing all categories back up through the hierarchy from the
                   13305:        current category to the top level.
                   13306: 
                   13307: currcategories - reference to array of current categories assigned to the course
                   13308: 
                   13309: Returns: $output (markup to be displayed).
                   13310: 
                   13311: =cut
                   13312: 
                   13313: sub assign_category_rows {
                   13314:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13315:     my ($text,$name,$item,$chgstr);
                   13316:     if (ref($cats) eq 'ARRAY') {
                   13317:         my $maxdepth = scalar(@{$cats});
                   13318:         if (ref($cats->[$depth]) eq 'HASH') {
                   13319:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13320:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13321:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13322:                 $text .= '<td><table class="LC_datatable">';
                   13323:                 for (my $j=0; $j<$numchildren; $j++) {
                   13324:                     $name = $cats->[$depth]{$parent}[$j];
                   13325:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13326:                     my $deeper = $depth+1;
                   13327:                     my $checked = '';
                   13328:                     if (ref($currcategories) eq 'ARRAY') {
                   13329:                         if (@{$currcategories} > 0) {
                   13330:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13331:                                 $checked = ' checked="checked"';
1.663     raeburn  13332:                             }
                   13333:                         }
                   13334:                     }
1.664     raeburn  13335:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13336:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13337:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13338:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13339:                              '</td><td>';
1.663     raeburn  13340:                     if (ref($path) eq 'ARRAY') {
                   13341:                         push(@{$path},$name);
                   13342:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13343:                         pop(@{$path});
                   13344:                     }
                   13345:                     $text .= '</td></tr>';
                   13346:                 }
                   13347:                 $text .= '</table></td>';
                   13348:             }
                   13349:         }
                   13350:     }
                   13351:     return $text;
                   13352: }
                   13353: 
1.655     raeburn  13354: ############################################################
                   13355: ############################################################
                   13356: 
                   13357: 
1.443     albertel 13358: sub commit_customrole {
1.664     raeburn  13359:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13360:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13361:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13362:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13363:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13364:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13365:                  '</b><br />';
                   13366:     return $output;
                   13367: }
                   13368: 
                   13369: sub commit_standardrole {
1.1116    raeburn  13370:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13371:     my ($output,$logmsg,$linefeed);
                   13372:     if ($context eq 'auto') {
                   13373:         $linefeed = "\n";
                   13374:     } else {
                   13375:         $linefeed = "<br />\n";
                   13376:     }  
1.443     albertel 13377:     if ($three eq 'st') {
1.541     raeburn  13378:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  13379:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13380:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13381:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13382:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13383:         } else {
1.541     raeburn  13384:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13385:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13386:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13387:             if ($context eq 'auto') {
                   13388:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13389:             } else {
                   13390:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13391:                &mt('Add to classlist').': <b>ok</b>';
                   13392:             }
                   13393:             $output .= $linefeed;
1.443     albertel 13394:         }
                   13395:     } else {
                   13396:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13397:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13398:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13399:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13400:         if ($context eq 'auto') {
                   13401:             $output .= $result.$linefeed;
                   13402:         } else {
                   13403:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13404:         }
1.443     albertel 13405:     }
                   13406:     return $output;
                   13407: }
                   13408: 
                   13409: sub commit_studentrole {
1.1116    raeburn  13410:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13411:         $credits) = @_;
1.626     raeburn  13412:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13413:     if ($context eq 'auto') {
                   13414:         $linefeed = "\n";
                   13415:     } else {
                   13416:         $linefeed = '<br />'."\n";
                   13417:     }
1.443     albertel 13418:     if (defined($one) && defined($two)) {
                   13419:         my $cid=$one.'_'.$two;
                   13420:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13421:         my $secchange = 0;
                   13422:         my $expire_role_result;
                   13423:         my $modify_section_result;
1.628     raeburn  13424:         if ($oldsec ne '-1') { 
                   13425:             if ($oldsec ne $sec) {
1.443     albertel 13426:                 $secchange = 1;
1.628     raeburn  13427:                 my $now = time;
1.443     albertel 13428:                 my $uurl='/'.$cid;
                   13429:                 $uurl=~s/\_/\//g;
                   13430:                 if ($oldsec) {
                   13431:                     $uurl.='/'.$oldsec;
                   13432:                 }
1.626     raeburn  13433:                 $oldsecurl = $uurl;
1.628     raeburn  13434:                 $expire_role_result = 
1.652     raeburn  13435:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13436:                 if ($env{'request.course.sec'} ne '') { 
                   13437:                     if ($expire_role_result eq 'refused') {
                   13438:                         my @roles = ('st');
                   13439:                         my @statuses = ('previous');
                   13440:                         my @roledoms = ($one);
                   13441:                         my $withsec = 1;
                   13442:                         my %roleshash = 
                   13443:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13444:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13445:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13446:                             my ($oldstart,$oldend) = 
                   13447:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13448:                             if ($oldend > 0 && $oldend <= $now) {
                   13449:                                 $expire_role_result = 'ok';
                   13450:                             }
                   13451:                         }
                   13452:                     }
                   13453:                 }
1.443     albertel 13454:                 $result = $expire_role_result;
                   13455:             }
                   13456:         }
                   13457:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  13458:             $modify_section_result = 
                   13459:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13460:                                                            undef,undef,undef,$sec,
                   13461:                                                            $end,$start,'','',$cid,
                   13462:                                                            '',$context,$credits);
1.443     albertel 13463:             if ($modify_section_result =~ /^ok/) {
                   13464:                 if ($secchange == 1) {
1.628     raeburn  13465:                     if ($sec eq '') {
                   13466:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13467:                     } else {
                   13468:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13469:                     }
1.443     albertel 13470:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13471:                     if ($sec eq '') {
                   13472:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13473:                     } else {
                   13474:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13475:                     }
1.443     albertel 13476:                 } else {
1.628     raeburn  13477:                     if ($sec eq '') {
                   13478:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13479:                     } else {
                   13480:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13481:                     }
1.443     albertel 13482:                 }
                   13483:             } else {
1.1115    raeburn  13484:                 if ($secchange) { 
1.628     raeburn  13485:                     $$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;
                   13486:                 } else {
                   13487:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13488:                 }
1.443     albertel 13489:             }
                   13490:             $result = $modify_section_result;
                   13491:         } elsif ($secchange == 1) {
1.628     raeburn  13492:             if ($oldsec eq '') {
1.1103    raeburn  13493:                 $$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  13494:             } else {
                   13495:                 $$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;
                   13496:             }
1.626     raeburn  13497:             if ($expire_role_result eq 'refused') {
                   13498:                 my $newsecurl = '/'.$cid;
                   13499:                 $newsecurl =~ s/\_/\//g;
                   13500:                 if ($sec ne '') {
                   13501:                     $newsecurl.='/'.$sec;
                   13502:                 }
                   13503:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13504:                     if ($sec eq '') {
                   13505:                         $$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;
                   13506:                     } else {
                   13507:                         $$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;
                   13508:                     }
                   13509:                 }
                   13510:             }
1.443     albertel 13511:         }
                   13512:     } else {
1.626     raeburn  13513:         $$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 13514:         $result = "error: incomplete course id\n";
                   13515:     }
                   13516:     return $result;
                   13517: }
                   13518: 
1.1108    raeburn  13519: sub show_role_extent {
                   13520:     my ($scope,$context,$role) = @_;
                   13521:     $scope =~ s{^/}{};
                   13522:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   13523:     push(@courseroles,'co');
                   13524:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   13525:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   13526:         $scope =~ s{/}{_};
                   13527:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   13528:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   13529:         my ($audom,$auname) = split(/\//,$scope);
                   13530:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   13531:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   13532:     } else {
                   13533:         $scope =~ s{/$}{};
                   13534:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   13535:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   13536:     }
                   13537: }
                   13538: 
1.443     albertel 13539: ############################################################
                   13540: ############################################################
                   13541: 
1.566     albertel 13542: sub check_clone {
1.578     raeburn  13543:     my ($args,$linefeed) = @_;
1.566     albertel 13544:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13545:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13546:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13547:     my $clonemsg;
                   13548:     my $can_clone = 0;
1.944     raeburn  13549:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13550:     if ($lctype ne 'community') {
                   13551:         $lctype = 'course';
                   13552:     }
1.566     albertel 13553:     if ($clonehome eq 'no_host') {
1.944     raeburn  13554:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13555:             $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'});
                   13556:         } else {
                   13557:             $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'});
                   13558:         }     
1.566     albertel 13559:     } else {
                   13560: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13561:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13562:             if ($clonedesc{'type'} ne 'Community') {
                   13563:                  $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'});
                   13564:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13565:             }
                   13566:         }
1.882     raeburn  13567: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13568:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13569: 	    $can_clone = 1;
                   13570: 	} else {
                   13571: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13572: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13573: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13574:             if (grep(/^\*$/,@cloners)) {
                   13575:                 $can_clone = 1;
                   13576:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13577:                 $can_clone = 1;
                   13578:             } else {
1.908     raeburn  13579:                 my $ccrole = 'cc';
1.944     raeburn  13580:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13581:                     $ccrole = 'co';
                   13582:                 }
1.578     raeburn  13583: 	        my %roleshash =
                   13584: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13585: 					 $args->{'ccdomain'},
1.908     raeburn  13586:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13587: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13588: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13589:                     $can_clone = 1;
                   13590:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13591:                     $can_clone = 1;
                   13592:                 } else {
1.944     raeburn  13593:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13594:                         $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'});
                   13595:                     } else {
                   13596:                         $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'});
                   13597:                     }
1.578     raeburn  13598: 	        }
1.566     albertel 13599: 	    }
1.578     raeburn  13600:         }
1.566     albertel 13601:     }
                   13602:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13603: }
                   13604: 
1.444     albertel 13605: sub construct_course {
1.885     raeburn  13606:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 13607:     my $outcome;
1.541     raeburn  13608:     my $linefeed =  '<br />'."\n";
                   13609:     if ($context eq 'auto') {
                   13610:         $linefeed = "\n";
                   13611:     }
1.566     albertel 13612: 
                   13613: #
                   13614: # Are we cloning?
                   13615: #
                   13616:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13617:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13618: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13619: 	if ($context ne 'auto') {
1.578     raeburn  13620:             if ($clonemsg ne '') {
                   13621: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13622:             }
1.566     albertel 13623: 	}
                   13624: 	$outcome .= $clonemsg.$linefeed;
                   13625: 
                   13626:         if (!$can_clone) {
                   13627: 	    return (0,$outcome);
                   13628: 	}
                   13629:     }
                   13630: 
1.444     albertel 13631: #
                   13632: # Open course
                   13633: #
                   13634:     my $crstype = lc($args->{'crstype'});
                   13635:     my %cenv=();
                   13636:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13637:                                              $args->{'cdescr'},
                   13638:                                              $args->{'curl'},
                   13639:                                              $args->{'course_home'},
                   13640:                                              $args->{'nonstandard'},
                   13641:                                              $args->{'crscode'},
                   13642:                                              $args->{'ccuname'}.':'.
                   13643:                                              $args->{'ccdomain'},
1.882     raeburn  13644:                                              $args->{'crstype'},
1.885     raeburn  13645:                                              $cnum,$context,$category);
1.444     albertel 13646: 
                   13647:     # Note: The testing routines depend on this being output; see 
                   13648:     # Utils::Course. This needs to at least be output as a comment
                   13649:     # if anyone ever decides to not show this, and Utils::Course::new
                   13650:     # will need to be suitably modified.
1.541     raeburn  13651:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13652:     if ($$courseid =~ /^error:/) {
                   13653:         return (0,$outcome);
                   13654:     }
                   13655: 
1.444     albertel 13656: #
                   13657: # Check if created correctly
                   13658: #
1.479     albertel 13659:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13660:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13661:     if ($crsuhome eq 'no_host') {
                   13662:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13663:         return (0,$outcome);
                   13664:     }
1.541     raeburn  13665:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13666: 
1.444     albertel 13667: #
1.566     albertel 13668: # Do the cloning
                   13669: #   
                   13670:     if ($can_clone && $cloneid) {
                   13671: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13672: 	if ($context ne 'auto') {
                   13673: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13674: 	}
                   13675: 	$outcome .= $clonemsg.$linefeed;
                   13676: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13677: # Copy all files
1.637     www      13678: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13679: # Restore URL
1.566     albertel 13680: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13681: # Restore title
1.566     albertel 13682: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13683: # Restore creation date, creator and creation context.
                   13684:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13685:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13686:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13687: # Mark as cloned
1.566     albertel 13688: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13689: # Need to clone grading mode
                   13690:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13691:         $cenv{'grading'}=$newenv{'grading'};
                   13692: # Do not clone these environment entries
                   13693:         &Apache::lonnet::del('environment',
                   13694:                   ['default_enrollment_start_date',
                   13695:                    'default_enrollment_end_date',
                   13696:                    'question.email',
                   13697:                    'policy.email',
                   13698:                    'comment.email',
                   13699:                    'pch.users.denied',
1.725     raeburn  13700:                    'plc.users.denied',
                   13701:                    'hidefromcat',
1.1121    raeburn  13702:                    'checkforpriv',
1.725     raeburn  13703:                    'categories'],
1.638     www      13704:                    $$crsudom,$$crsunum);
1.444     albertel 13705:     }
1.566     albertel 13706: 
1.444     albertel 13707: #
                   13708: # Set environment (will override cloned, if existing)
                   13709: #
                   13710:     my @sections = ();
                   13711:     my @xlists = ();
                   13712:     if ($args->{'crstype'}) {
                   13713:         $cenv{'type'}=$args->{'crstype'};
                   13714:     }
                   13715:     if ($args->{'crsid'}) {
                   13716:         $cenv{'courseid'}=$args->{'crsid'};
                   13717:     }
                   13718:     if ($args->{'crscode'}) {
                   13719:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   13720:     }
                   13721:     if ($args->{'crsquota'} ne '') {
                   13722:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   13723:     } else {
                   13724:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   13725:     }
                   13726:     if ($args->{'ccuname'}) {
                   13727:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   13728:                                         ':'.$args->{'ccdomain'};
                   13729:     } else {
                   13730:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   13731:     }
1.1116    raeburn  13732:     if ($args->{'defaultcredits'}) {
                   13733:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   13734:     }
1.444     albertel 13735:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   13736:     if ($args->{'crssections'}) {
                   13737:         $cenv{'internal.sectionnums'} = '';
                   13738:         if ($args->{'crssections'} =~ m/,/) {
                   13739:             @sections = split/,/,$args->{'crssections'};
                   13740:         } else {
                   13741:             $sections[0] = $args->{'crssections'};
                   13742:         }
                   13743:         if (@sections > 0) {
                   13744:             foreach my $item (@sections) {
                   13745:                 my ($sec,$gp) = split/:/,$item;
                   13746:                 my $class = $args->{'crscode'}.$sec;
                   13747:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   13748:                 $cenv{'internal.sectionnums'} .= $item.',';
                   13749:                 unless ($addcheck eq 'ok') {
                   13750:                     push @badclasses, $class;
                   13751:                 }
                   13752:             }
                   13753:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   13754:         }
                   13755:     }
                   13756: # do not hide course coordinator from staff listing, 
                   13757: # even if privileged
                   13758:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  13759: # add course coordinator's domain to domains to check for privileged users
                   13760: # if different to course domain
                   13761:     if ($$crsudom ne $args->{'ccdomain'}) {
                   13762:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   13763:     }
1.444     albertel 13764: # add crosslistings
                   13765:     if ($args->{'crsxlist'}) {
                   13766:         $cenv{'internal.crosslistings'}='';
                   13767:         if ($args->{'crsxlist'} =~ m/,/) {
                   13768:             @xlists = split/,/,$args->{'crsxlist'};
                   13769:         } else {
                   13770:             $xlists[0] = $args->{'crsxlist'};
                   13771:         }
                   13772:         if (@xlists > 0) {
                   13773:             foreach my $item (@xlists) {
                   13774:                 my ($xl,$gp) = split/:/,$item;
                   13775:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   13776:                 $cenv{'internal.crosslistings'} .= $item.',';
                   13777:                 unless ($addcheck eq 'ok') {
                   13778:                     push @badclasses, $xl;
                   13779:                 }
                   13780:             }
                   13781:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   13782:         }
                   13783:     }
                   13784:     if ($args->{'autoadds'}) {
                   13785:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   13786:     }
                   13787:     if ($args->{'autodrops'}) {
                   13788:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   13789:     }
                   13790: # check for notification of enrollment changes
                   13791:     my @notified = ();
                   13792:     if ($args->{'notify_owner'}) {
                   13793:         if ($args->{'ccuname'} ne '') {
                   13794:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   13795:         }
                   13796:     }
                   13797:     if ($args->{'notify_dc'}) {
                   13798:         if ($uname ne '') { 
1.630     raeburn  13799:             push(@notified,$uname.':'.$udom);
1.444     albertel 13800:         }
                   13801:     }
                   13802:     if (@notified > 0) {
                   13803:         my $notifylist;
                   13804:         if (@notified > 1) {
                   13805:             $notifylist = join(',',@notified);
                   13806:         } else {
                   13807:             $notifylist = $notified[0];
                   13808:         }
                   13809:         $cenv{'internal.notifylist'} = $notifylist;
                   13810:     }
                   13811:     if (@badclasses > 0) {
                   13812:         my %lt=&Apache::lonlocal::texthash(
                   13813:                 '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',
                   13814:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   13815:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   13816:         );
1.541     raeburn  13817:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   13818:                            ' ('.$lt{'adby'}.')';
                   13819:         if ($context eq 'auto') {
                   13820:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 13821:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  13822:             foreach my $item (@badclasses) {
                   13823:                 if ($context eq 'auto') {
                   13824:                     $outcome .= " - $item\n";
                   13825:                 } else {
                   13826:                     $outcome .= "<li>$item</li>\n";
                   13827:                 }
                   13828:             }
                   13829:             if ($context eq 'auto') {
                   13830:                 $outcome .= $linefeed;
                   13831:             } else {
1.566     albertel 13832:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  13833:             }
                   13834:         } 
1.444     albertel 13835:     }
                   13836:     if ($args->{'no_end_date'}) {
                   13837:         $args->{'endaccess'} = 0;
                   13838:     }
                   13839:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   13840:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   13841:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   13842:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   13843:     if ($args->{'showphotos'}) {
                   13844:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   13845:     }
                   13846:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   13847:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   13848:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   13849:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  13850:             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'); 
                   13851:             if ($context eq 'auto') {
                   13852:                 $outcome .= $krb_msg;
                   13853:             } else {
1.566     albertel 13854:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  13855:             }
                   13856:             $outcome .= $linefeed;
1.444     albertel 13857:         }
                   13858:     }
                   13859:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   13860:        if ($args->{'setpolicy'}) {
                   13861:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13862:        }
                   13863:        if ($args->{'setcontent'}) {
                   13864:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13865:        }
                   13866:     }
                   13867:     if ($args->{'reshome'}) {
                   13868: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   13869: 	$cenv{'reshome'}=~s/\/+$/\//;
                   13870:     }
                   13871: #
                   13872: # course has keyed access
                   13873: #
                   13874:     if ($args->{'setkeys'}) {
                   13875:        $cenv{'keyaccess'}='yes';
                   13876:     }
                   13877: # if specified, key authority is not course, but user
                   13878: # only active if keyaccess is yes
                   13879:     if ($args->{'keyauth'}) {
1.487     albertel 13880: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   13881: 	$user = &LONCAPA::clean_username($user);
                   13882: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     13883: 	if ($user ne '' && $domain ne '') {
1.487     albertel 13884: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 13885: 	}
                   13886:     }
                   13887: 
                   13888:     if ($args->{'disresdis'}) {
                   13889:         $cenv{'pch.roles.denied'}='st';
                   13890:     }
                   13891:     if ($args->{'disablechat'}) {
                   13892:         $cenv{'plc.roles.denied'}='st';
                   13893:     }
                   13894: 
                   13895:     # Record we've not yet viewed the Course Initialization Helper for this 
                   13896:     # course
                   13897:     $cenv{'course.helper.not.run'} = 1;
                   13898:     #
                   13899:     # Use new Randomseed
                   13900:     #
                   13901:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   13902:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   13903:     #
                   13904:     # The encryption code and receipt prefix for this course
                   13905:     #
                   13906:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   13907:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   13908:     #
                   13909:     # By default, use standard grading
                   13910:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   13911: 
1.541     raeburn  13912:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   13913:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13914: #
                   13915: # Open all assignments
                   13916: #
                   13917:     if ($args->{'openall'}) {
                   13918:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   13919:        my %storecontent = ($storeunder         => time,
                   13920:                            $storeunder.'.type' => 'date_start');
                   13921:        
                   13922:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  13923:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13924:    }
                   13925: #
                   13926: # Set first page
                   13927: #
                   13928:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   13929: 	    || ($cloneid)) {
1.445     albertel 13930: 	use LONCAPA::map;
1.444     albertel 13931: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 13932: 
                   13933: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   13934:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   13935: 
1.444     albertel 13936:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   13937:         my $title; my $url;
                   13938:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   13939: 	    $title=&mt('Syllabus');
1.444     albertel 13940:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   13941:         } else {
1.963     raeburn  13942:             $title=&mt('Table of Contents');
1.444     albertel 13943:             $url='/adm/navmaps';
                   13944:         }
1.445     albertel 13945: 
                   13946:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   13947: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   13948: 
                   13949: 	if ($errtext) { $fatal=2; }
1.541     raeburn  13950:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 13951:     }
1.566     albertel 13952: 
                   13953:     return (1,$outcome);
1.444     albertel 13954: }
                   13955: 
                   13956: ############################################################
                   13957: ############################################################
                   13958: 
1.953     droeschl 13959: #SD
                   13960: # only Community and Course, or anything else?
1.378     raeburn  13961: sub course_type {
                   13962:     my ($cid) = @_;
                   13963:     if (!defined($cid)) {
                   13964:         $cid = $env{'request.course.id'};
                   13965:     }
1.404     albertel 13966:     if (defined($env{'course.'.$cid.'.type'})) {
                   13967:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  13968:     } else {
                   13969:         return 'Course';
1.377     raeburn  13970:     }
                   13971: }
1.156     albertel 13972: 
1.406     raeburn  13973: sub group_term {
                   13974:     my $crstype = &course_type();
                   13975:     my %names = (
                   13976:                   'Course' => 'group',
1.865     raeburn  13977:                   'Community' => 'group',
1.406     raeburn  13978:                 );
                   13979:     return $names{$crstype};
                   13980: }
                   13981: 
1.902     raeburn  13982: sub course_types {
                   13983:     my @types = ('official','unofficial','community');
                   13984:     my %typename = (
                   13985:                          official   => 'Official course',
                   13986:                          unofficial => 'Unofficial course',
                   13987:                          community  => 'Community',
                   13988:                    );
                   13989:     return (\@types,\%typename);
                   13990: }
                   13991: 
1.156     albertel 13992: sub icon {
                   13993:     my ($file)=@_;
1.505     albertel 13994:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 13995:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 13996:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 13997:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   13998: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   13999: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14000: 	            $curfext.".gif") {
                   14001: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14002: 		$curfext.".gif";
                   14003: 	}
                   14004:     }
1.249     albertel 14005:     return &lonhttpdurl($iconname);
1.154     albertel 14006: } 
1.84      albertel 14007: 
1.575     albertel 14008: sub lonhttpdurl {
1.692     www      14009: #
                   14010: # Had been used for "small fry" static images on separate port 8080.
                   14011: # Modify here if lightweight http functionality desired again.
                   14012: # Currently eliminated due to increasing firewall issues.
                   14013: #
1.575     albertel 14014:     my ($url)=@_;
1.692     www      14015:     return $url;
1.215     albertel 14016: }
                   14017: 
1.213     albertel 14018: sub connection_aborted {
                   14019:     my ($r)=@_;
                   14020:     $r->print(" ");$r->rflush();
                   14021:     my $c = $r->connection;
                   14022:     return $c->aborted();
                   14023: }
                   14024: 
1.221     foxr     14025: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14026: #    strings as 'strings'.
                   14027: sub escape_single {
1.221     foxr     14028:     my ($input) = @_;
1.223     albertel 14029:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14030:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14031:     return $input;
                   14032: }
1.223     albertel 14033: 
1.222     foxr     14034: #  Same as escape_single, but escape's "'s  This 
                   14035: #  can be used for  "strings"
                   14036: sub escape_double {
                   14037:     my ($input) = @_;
                   14038:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14039:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14040:     return $input;
                   14041: }
1.223     albertel 14042:  
1.222     foxr     14043: #   Escapes the last element of a full URL.
                   14044: sub escape_url {
                   14045:     my ($url)   = @_;
1.238     raeburn  14046:     my @urlslices = split(/\//, $url,-1);
1.369     www      14047:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 14048:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     14049: }
1.462     albertel 14050: 
1.820     raeburn  14051: sub compare_arrays {
                   14052:     my ($arrayref1,$arrayref2) = @_;
                   14053:     my (@difference,%count);
                   14054:     @difference = ();
                   14055:     %count = ();
                   14056:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14057:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14058:         foreach my $element (keys(%count)) {
                   14059:             if ($count{$element} == 1) {
                   14060:                 push(@difference,$element);
                   14061:             }
                   14062:         }
                   14063:     }
                   14064:     return @difference;
                   14065: }
                   14066: 
1.817     bisitz   14067: # -------------------------------------------------------- Initialize user login
1.462     albertel 14068: sub init_user_environment {
1.463     albertel 14069:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14070:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14071: 
                   14072:     my $public=($username eq 'public' && $domain eq 'public');
                   14073: 
                   14074: # See if old ID present, if so, remove
                   14075: 
1.1062    raeburn  14076:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14077:     my $now=time;
                   14078: 
                   14079:     if ($public) {
                   14080: 	my $max_public=100;
                   14081: 	my $oldest;
                   14082: 	my $oldest_time=0;
                   14083: 	for(my $next=1;$next<=$max_public;$next++) {
                   14084: 	    if (-e $lonids."/publicuser_$next.id") {
                   14085: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14086: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14087: 		    $oldest_time=$mtime;
                   14088: 		    $oldest=$next;
                   14089: 		}
                   14090: 	    } else {
                   14091: 		$cookie="publicuser_$next";
                   14092: 		last;
                   14093: 	    }
                   14094: 	}
                   14095: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14096:     } else {
1.463     albertel 14097: 	# if this isn't a robot, kill any existing non-robot sessions
                   14098: 	if (!$args->{'robot'}) {
                   14099: 	    opendir(DIR,$lonids);
                   14100: 	    while ($filename=readdir(DIR)) {
                   14101: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14102: 		    unlink($lonids.'/'.$filename);
                   14103: 		}
1.462     albertel 14104: 	    }
1.463     albertel 14105: 	    closedir(DIR);
1.462     albertel 14106: 	}
                   14107: # Give them a new cookie
1.463     albertel 14108: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14109: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14110: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14111:     
                   14112: # Initialize roles
                   14113: 
1.1062    raeburn  14114: 	($userroles,$firstaccenv,$timerintenv) = 
                   14115:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14116:     }
                   14117: # ------------------------------------ Check browser type and MathML capability
                   14118: 
                   14119:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   14120:         $clientunicode,$clientos) = &decode_user_agent($r);
                   14121: 
                   14122: # ------------------------------------------------------------- Get environment
                   14123: 
                   14124:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14125:     my ($tmp) = keys(%userenv);
                   14126:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14127:     } else {
                   14128: 	undef(%userenv);
                   14129:     }
                   14130:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14131: 	$form->{'interface'}=$userenv{'interface'};
                   14132:     }
                   14133:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14134: 
                   14135: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14136:     foreach my $option ('interface','localpath','localres') {
                   14137:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14138:     }
                   14139: # --------------------------------------------------------- Write first profile
                   14140: 
                   14141:     {
                   14142: 	my %initial_env = 
                   14143: 	    ("user.name"          => $username,
                   14144: 	     "user.domain"        => $domain,
                   14145: 	     "user.home"          => $authhost,
                   14146: 	     "browser.type"       => $clientbrowser,
                   14147: 	     "browser.version"    => $clientversion,
                   14148: 	     "browser.mathml"     => $clientmathml,
                   14149: 	     "browser.unicode"    => $clientunicode,
                   14150: 	     "browser.os"         => $clientos,
                   14151: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14152: 	     "request.course.fn"  => '',
                   14153: 	     "request.course.uri" => '',
                   14154: 	     "request.course.sec" => '',
                   14155: 	     "request.role"       => 'cm',
                   14156: 	     "request.role.adv"   => $env{'user.adv'},
                   14157: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14158: 
                   14159:         if ($form->{'localpath'}) {
                   14160: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14161: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14162:         }
                   14163: 	
                   14164: 	if ($form->{'interface'}) {
                   14165: 	    $form->{'interface'}=~s/\W//gs;
                   14166: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14167: 	    $env{'browser.interface'}=$form->{'interface'};
                   14168: 	}
                   14169: 
1.981     raeburn  14170:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14171:         my %domdef;
                   14172:         unless ($domain eq 'public') {
                   14173:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14174:         }
1.980     raeburn  14175: 
1.1081    raeburn  14176:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14177:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14178:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14179:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14180:         }
                   14181: 
1.864     raeburn  14182:         foreach my $crstype ('official','unofficial','community') {
1.765     raeburn  14183:             $userenv{'canrequest.'.$crstype} =
                   14184:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14185:                                                   'reload','requestcourses',
                   14186:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14187:         }
                   14188: 
1.1092    raeburn  14189:         $userenv{'canrequest.author'} =
                   14190:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14191:                                         'reload','requestauthor',
                   14192:                                         \%userenv,\%domdef,\%is_adv);
                   14193:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14194:                                              $domain,$username);
                   14195:         my $reqstatus = $reqauthor{'author_status'};
                   14196:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   14197:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14198:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14199:                                                   $reqauthor{'author'}{'timestamp'};
                   14200:             }
                   14201:         }
                   14202: 
1.462     albertel 14203: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14204: 
1.462     albertel 14205: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14206: 		 &GDBM_WRCREAT(),0640)) {
                   14207: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14208: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14209: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14210:             if (ref($firstaccenv) eq 'HASH') {
                   14211:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14212:             }
                   14213:             if (ref($timerintenv) eq 'HASH') {
                   14214:                 &_add_to_env(\%disk_env,$timerintenv);
                   14215:             }
1.463     albertel 14216: 	    if (ref($args->{'extra_env'})) {
                   14217: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14218: 	    }
1.462     albertel 14219: 	    untie(%disk_env);
                   14220: 	} else {
1.705     tempelho 14221: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14222: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14223: 	    return 'error: '.$!;
                   14224: 	}
                   14225:     }
                   14226:     $env{'request.role'}='cm';
                   14227:     $env{'request.role.adv'}=$env{'user.adv'};
                   14228:     $env{'browser.type'}=$clientbrowser;
                   14229: 
                   14230:     return $cookie;
                   14231: 
                   14232: }
                   14233: 
                   14234: sub _add_to_env {
                   14235:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14236:     if (ref($env_data) eq 'HASH') {
                   14237:         while (my ($key,$value) = each(%$env_data)) {
                   14238: 	    $idf->{$prefix.$key} = $value;
                   14239: 	    $env{$prefix.$key}   = $value;
                   14240:         }
1.462     albertel 14241:     }
                   14242: }
                   14243: 
1.685     tempelho 14244: # --- Get the symbolic name of a problem and the url
                   14245: sub get_symb {
                   14246:     my ($request,$silent) = @_;
1.726     raeburn  14247:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14248:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14249:     if ($symb eq '') {
                   14250:         if (!$silent) {
1.1071    raeburn  14251:             if (ref($request)) { 
                   14252:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14253:             }
1.685     tempelho 14254:             return ();
                   14255:         }
                   14256:     }
                   14257:     &Apache::lonenc::check_decrypt(\$symb);
                   14258:     return ($symb);
                   14259: }
                   14260: 
                   14261: # --------------------------------------------------------------Get annotation
                   14262: 
                   14263: sub get_annotation {
                   14264:     my ($symb,$enc) = @_;
                   14265: 
                   14266:     my $key = $symb;
                   14267:     if (!$enc) {
                   14268:         $key =
                   14269:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14270:     }
                   14271:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14272:     return $annotation{$key};
                   14273: }
                   14274: 
                   14275: sub clean_symb {
1.731     raeburn  14276:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14277: 
                   14278:     &Apache::lonenc::check_decrypt(\$symb);
                   14279:     my $enc = $env{'request.enc'};
1.731     raeburn  14280:     if ($delete_enc) {
1.730     raeburn  14281:         delete($env{'request.enc'});
                   14282:     }
1.685     tempelho 14283: 
                   14284:     return ($symb,$enc);
                   14285: }
1.462     albertel 14286: 
1.990     raeburn  14287: sub build_release_hashes {
                   14288:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14289:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14290:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14291:                   (ref($randomizetry) eq 'HASH'));
                   14292:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14293:         my ($item,$name,$value) = split(/:/,$key);
                   14294:         if ($item eq 'parameter') {
                   14295:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14296:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14297:                     push(@{$checkparms->{$name}},$value);
                   14298:                 }
                   14299:             } else {
                   14300:                 push(@{$checkparms->{$name}},$value);
                   14301:             }
                   14302:         } elsif ($item eq 'resourcetag') {
                   14303:             if ($name eq 'responsetype') {
                   14304:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14305:             }
                   14306:         } elsif ($item eq 'course') {
                   14307:             if ($name eq 'crstype') {
                   14308:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14309:             }
                   14310:         }
                   14311:     }
                   14312:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14313:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14314:     return;
                   14315: }
                   14316: 
1.1083    raeburn  14317: sub update_content_constraints {
                   14318:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14319:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14320:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14321:     my %checkresponsetypes;
                   14322:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14323:         my ($item,$name,$value) = split(/:/,$key);
                   14324:         if ($item eq 'resourcetag') {
                   14325:             if ($name eq 'responsetype') {
                   14326:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14327:             }
                   14328:         }
                   14329:     }
                   14330:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14331:     if (defined($navmap)) {
                   14332:         my %allresponses;
                   14333:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14334:             my %responses = $res->responseTypes();
                   14335:             foreach my $key (keys(%responses)) {
                   14336:                 next unless(exists($checkresponsetypes{$key}));
                   14337:                 $allresponses{$key} += $responses{$key};
                   14338:             }
                   14339:         }
                   14340:         foreach my $key (keys(%allresponses)) {
                   14341:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14342:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14343:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14344:             }
                   14345:         }
                   14346:         undef($navmap);
                   14347:     }
                   14348:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14349:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14350:     }
                   14351:     return;
                   14352: }
                   14353: 
1.1110    raeburn  14354: sub allmaps_incourse {
                   14355:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14356:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   14357:         $cid = $env{'request.course.id'};
                   14358:         $cdom = $env{'course.'.$cid.'.domain'};
                   14359:         $cnum = $env{'course.'.$cid.'.num'};
                   14360:         $chome = $env{'course.'.$cid.'.home'};
                   14361:     }
                   14362:     my %allmaps = ();
                   14363:     my $lastchange =
                   14364:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   14365:     if ($lastchange > $env{'request.course.tied'}) {
                   14366:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   14367:         unless ($ferr) {
                   14368:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   14369:         }
                   14370:     }
                   14371:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14372:     if (defined($navmap)) {
                   14373:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   14374:             $allmaps{$res->src()} = 1;
                   14375:         }
                   14376:     }
                   14377:     return \%allmaps;
                   14378: }
                   14379: 
1.1083    raeburn  14380: sub parse_supplemental_title {
                   14381:     my ($title) = @_;
                   14382: 
                   14383:     my ($foldertitle,$renametitle);
                   14384:     if ($title =~ /&amp;&amp;&amp;/) {
                   14385:         $title = &HTML::Entites::decode($title);
                   14386:     }
                   14387:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14388:         $renametitle=$4;
                   14389:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14390:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14391:         my $name =  &plainname($uname,$udom);
                   14392:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14393:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14394:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14395:             $name.': <br />'.$foldertitle;
                   14396:     }
                   14397:     if (wantarray) {
                   14398:         return ($title,$foldertitle,$renametitle);
                   14399:     }
                   14400:     return $title;
                   14401: }
                   14402: 
1.1101    raeburn  14403: sub symb_to_docspath {
                   14404:     my ($symb) = @_;
                   14405:     return unless ($symb);
                   14406:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14407:     if ($resurl=~/\.(sequence|page)$/) {
                   14408:         $mapurl=$resurl;
                   14409:     } elsif ($resurl eq 'adm/navmaps') {
                   14410:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14411:     }
                   14412:     my $mapresobj;
                   14413:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14414:     if (ref($navmap)) {
                   14415:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14416:     }
                   14417:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14418:     my $type=$2;
                   14419:     my $path;
                   14420:     if (ref($mapresobj)) {
                   14421:         my $pcslist = $mapresobj->map_hierarchy();
                   14422:         if ($pcslist ne '') {
                   14423:             foreach my $pc (split(/,/,$pcslist)) {
                   14424:                 next if ($pc <= 1);
                   14425:                 my $res = $navmap->getByMapPc($pc);
                   14426:                 if (ref($res)) {
                   14427:                     my $thisurl = $res->src();
                   14428:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14429:                     my $thistitle = $res->title();
                   14430:                     $path .= '&'.
                   14431:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   14432:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
                   14433:                              ':'.$res->randompick().
                   14434:                              ':'.$res->randomout().
                   14435:                              ':'.$res->encrypted().
                   14436:                              ':'.$res->randomorder().
                   14437:                              ':'.$res->is_page();
                   14438:                 }
                   14439:             }
                   14440:         }
                   14441:         $path =~ s/^\&//;
                   14442:         my $maptitle = $mapresobj->title();
                   14443:         if ($mapurl eq 'default') {
1.1129    raeburn  14444:             $maptitle = 'Main Content';
1.1101    raeburn  14445:         }
                   14446:         $path .= (($path ne '')? '&' : '').
                   14447:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14448:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
                   14449:                  ':'.$mapresobj->randompick().
                   14450:                  ':'.$mapresobj->randomout().
                   14451:                  ':'.$mapresobj->encrypted().
                   14452:                  ':'.$mapresobj->randomorder().
                   14453:                  ':'.$mapresobj->is_page();
                   14454:     } else {
                   14455:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14456:         my $ispage = (($type eq 'page')? 1 : '');
                   14457:         if ($mapurl eq 'default') {
1.1129    raeburn  14458:             $maptitle = 'Main Content';
1.1101    raeburn  14459:         }
                   14460:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14461:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   14462:     }
                   14463:     unless ($mapurl eq 'default') {
                   14464:         $path = 'default&'.
1.1129    raeburn  14465:                 &Apache::lonhtmlcommon::entity_encode('Main Content').
1.1101    raeburn  14466:                 ':::::&'.$path;
                   14467:     }
                   14468:     return $path;
                   14469: }
                   14470: 
1.1094    raeburn  14471: sub captcha_display {
                   14472:     my ($context,$lonhost) = @_;
                   14473:     my ($output,$error);
                   14474:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14475:     if ($captcha eq 'original') {
1.1094    raeburn  14476:         $output = &create_captcha();
                   14477:         unless ($output) {
                   14478:             $error = 'captcha'; 
                   14479:         }
                   14480:     } elsif ($captcha eq 'recaptcha') {
                   14481:         $output = &create_recaptcha($pubkey);
                   14482:         unless ($output) {
1.1095    raeburn  14483:             $error = 'recaptcha'; 
1.1094    raeburn  14484:         }
                   14485:     }
                   14486:     return ($output,$error);
                   14487: }
                   14488: 
                   14489: sub captcha_response {
                   14490:     my ($context,$lonhost) = @_;
                   14491:     my ($captcha_chk,$captcha_error);
                   14492:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14493:     if ($captcha eq 'original') {
1.1094    raeburn  14494:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14495:     } elsif ($captcha eq 'recaptcha') {
                   14496:         $captcha_chk = &check_recaptcha($privkey);
                   14497:     } else {
                   14498:         $captcha_chk = 1;
                   14499:     }
                   14500:     return ($captcha_chk,$captcha_error);
                   14501: }
                   14502: 
                   14503: sub get_captcha_config {
                   14504:     my ($context,$lonhost) = @_;
1.1095    raeburn  14505:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  14506:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14507:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14508:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  14509:     if ($context eq 'usercreation') {
                   14510:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14511:         if (ref($domconfig{$context}) eq 'HASH') {
                   14512:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14513:             if (ref($hashtocheck) eq 'HASH') {
                   14514:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14515:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14516:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14517:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14518:                     }
                   14519:                     if ($privkey && $pubkey) {
                   14520:                         $captcha = 'recaptcha';
                   14521:                     } else {
                   14522:                         $captcha = 'original';
                   14523:                     }
                   14524:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14525:                     $captcha = 'original';
                   14526:                 }
1.1094    raeburn  14527:             }
1.1095    raeburn  14528:         } else {
                   14529:             $captcha = 'captcha';
                   14530:         }
                   14531:     } elsif ($context eq 'login') {
                   14532:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14533:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14534:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14535:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  14536:             if ($privkey && $pubkey) {
                   14537:                 $captcha = 'recaptcha';
1.1095    raeburn  14538:             } else {
                   14539:                 $captcha = 'original';
1.1094    raeburn  14540:             }
1.1095    raeburn  14541:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14542:             $captcha = 'original';
1.1094    raeburn  14543:         }
                   14544:     }
                   14545:     return ($captcha,$pubkey,$privkey);
                   14546: }
                   14547: 
                   14548: sub create_captcha {
                   14549:     my %captcha_params = &captcha_settings();
                   14550:     my ($output,$maxtries,$tries) = ('',10,0);
                   14551:     while ($tries < $maxtries) {
                   14552:         $tries ++;
                   14553:         my $captcha = Authen::Captcha->new (
                   14554:                                            output_folder => $captcha_params{'output_dir'},
                   14555:                                            data_folder   => $captcha_params{'db_dir'},
                   14556:                                           );
                   14557:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14558: 
                   14559:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14560:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14561:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14562:                      '<input type="text" size="5" name="code" value="" /><br />'.
                   14563:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
                   14564:             last;
                   14565:         }
                   14566:     }
                   14567:     return $output;
                   14568: }
                   14569: 
                   14570: sub captcha_settings {
                   14571:     my %captcha_params = (
                   14572:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14573:                            www_output_dir => "/captchaspool",
                   14574:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14575:                            numchars       => '5',
                   14576:                          );
                   14577:     return %captcha_params;
                   14578: }
                   14579: 
                   14580: sub check_captcha {
                   14581:     my ($captcha_chk,$captcha_error);
                   14582:     my $code = $env{'form.code'};
                   14583:     my $md5sum = $env{'form.crypt'};
                   14584:     my %captcha_params = &captcha_settings();
                   14585:     my $captcha = Authen::Captcha->new(
                   14586:                       output_folder => $captcha_params{'output_dir'},
                   14587:                       data_folder   => $captcha_params{'db_dir'},
                   14588:                   );
1.1109    raeburn  14589:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  14590:     my %captcha_hash = (
                   14591:                         0       => 'Code not checked (file error)',
                   14592:                        -1      => 'Failed: code expired',
                   14593:                        -2      => 'Failed: invalid code (not in database)',
                   14594:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   14595:     );
                   14596:     if ($captcha_chk != 1) {
                   14597:         $captcha_error = $captcha_hash{$captcha_chk}
                   14598:     }
                   14599:     return ($captcha_chk,$captcha_error);
                   14600: }
                   14601: 
                   14602: sub create_recaptcha {
                   14603:     my ($pubkey) = @_;
                   14604:     my $captcha = Captcha::reCAPTCHA->new;
                   14605:     return $captcha->get_options_setter({theme => 'white'})."\n".
                   14606:            $captcha->get_html($pubkey).
                   14607:            &mt('If either word is hard to read, [_1] will replace them.',
1.1133    raeburn  14608:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  14609:            '<br /><br />';
                   14610: }
                   14611: 
                   14612: sub check_recaptcha {
                   14613:     my ($privkey) = @_;
                   14614:     my $captcha_chk;
                   14615:     my $captcha = Captcha::reCAPTCHA->new;
                   14616:     my $captcha_result =
                   14617:         $captcha->check_answer(
                   14618:                                 $privkey,
                   14619:                                 $ENV{'REMOTE_ADDR'},
                   14620:                                 $env{'form.recaptcha_challenge_field'},
                   14621:                                 $env{'form.recaptcha_response_field'},
                   14622:                               );
                   14623:     if ($captcha_result->{is_valid}) {
                   14624:         $captcha_chk = 1;
                   14625:     }
                   14626:     return $captcha_chk;
                   14627: }
                   14628: 
1.41      ng       14629: =pod
                   14630: 
                   14631: =back
                   14632: 
1.112     bowersj2 14633: =cut
1.41      ng       14634: 
1.112     bowersj2 14635: 1;
                   14636: __END__;
1.41      ng       14637: 

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