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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.92! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.91 2015/04/06 19:06:45 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.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.687     raeburn    75: use DateTime::Locale::Catalog;
1.1075.2.14  raeburn    76: use Authen::Captcha;
                     77: use Captcha::reCAPTCHA;
1.1075.2.64  raeburn    78: use Crypt::DES;
                     79: use DynaLoader; # for Crypt::DES version
1.117     www        80: 
1.517     raeburn    81: # ---------------------------------------------- Designs
                     82: use vars qw(%defaultdesign);
                     83: 
1.22      www        84: my $readit;
                     85: 
1.517     raeburn    86: 
1.157     matthew    87: ##
                     88: ## Global Variables
                     89: ##
1.46      matthew    90: 
1.643     foxr       91: 
                     92: # ----------------------------------------------- SSI with retries:
                     93: #
                     94: 
                     95: =pod
                     96: 
1.648     raeburn    97: =head1 Server Side include with retries:
1.643     foxr       98: 
                     99: =over 4
                    100: 
1.648     raeburn   101: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      102: 
                    103: Performs an ssi with some number of retries.  Retries continue either
                    104: until the result is ok or until the retry count supplied by the
                    105: caller is exhausted.  
                    106: 
                    107: Inputs:
1.648     raeburn   108: 
                    109: =over 4
                    110: 
1.643     foxr      111: resource   - Identifies the resource to insert.
1.648     raeburn   112: 
1.643     foxr      113: retries    - Count of the number of retries allowed.
1.648     raeburn   114: 
1.643     foxr      115: form       - Hash that identifies the rendering options.
                    116: 
1.648     raeburn   117: =back
                    118: 
                    119: Returns:
                    120: 
                    121: =over 4
                    122: 
1.643     foxr      123: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   124: 
1.643     foxr      125: response   - The response from the last attempt (which may or may not have been successful.
                    126: 
1.648     raeburn   127: =back
                    128: 
                    129: =back
                    130: 
1.643     foxr      131: =cut
                    132: 
                    133: sub ssi_with_retries {
                    134:     my ($resource, $retries, %form) = @_;
                    135: 
                    136: 
                    137:     my $ok = 0;			# True if we got a good response.
                    138:     my $content;
                    139:     my $response;
                    140: 
                    141:     # Try to get the ssi done. within the retries count:
                    142: 
                    143:     do {
                    144: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    145: 	$ok      = $response->is_success;
1.650     www       146:         if (!$ok) {
                    147:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    148:         }
1.643     foxr      149: 	$retries--;
                    150:     } while (!$ok && ($retries > 0));
                    151: 
                    152:     if (!$ok) {
                    153: 	$content = '';		# On error return an empty content.
                    154:     }
                    155:     return ($content, $response);
                    156: 
                    157: }
                    158: 
                    159: 
                    160: 
1.20      www       161: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  162: my %language;
1.124     www       163: my %supported_language;
1.1048    foxr      164: my %latex_language;		# For choosing hyphenation in <transl..>
                    165: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  166: my %cprtag;
1.192     taceyjo1  167: my %scprtag;
1.351     www       168: my %fe; my %fd; my %fm;
1.41      ng        169: my %category_extensions;
1.12      harris41  170: 
1.46      matthew   171: # ---------------------------------------------- Thesaurus variables
1.144     matthew   172: #
                    173: # %Keywords:
                    174: #      A hash used by &keyword to determine if a word is considered a keyword.
                    175: # $thesaurus_db_file 
                    176: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   177: 
                    178: my %Keywords;
                    179: my $thesaurus_db_file;
                    180: 
1.144     matthew   181: #
                    182: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    183: # thesaurus.tab, and filecategories.tab.
                    184: #
1.18      www       185: BEGIN {
1.46      matthew   186:     # Variable initialization
                    187:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    188:     #
1.22      www       189:     unless ($readit) {
1.12      harris41  190: # ------------------------------------------------------------------- languages
                    191:     {
1.158     raeburn   192:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    193:                                    '/language.tab';
                    194:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  195:             while (my $line = <$fh>) {
                    196:                 next if ($line=~/^\#/);
                    197:                 chomp($line);
1.1048    foxr      198:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   199:                 $language{$key}=$val.' - '.$enc;
                    200:                 if ($sup) {
                    201:                     $supported_language{$key}=$sup;
                    202:                 }
1.1048    foxr      203: 		if ($latex) {
                    204: 		    $latex_language_bykey{$key} = $latex;
                    205: 		    $latex_language{$two} = $latex;
                    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.1075.2.31  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.1075.2.31  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]);
                    669:             if (n !== n) { // shortcut for verifying if it's NaN
                    670:                 n = 0;
                    671:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    672:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    673:             }
                    674:         }
                    675:         if (n >= len) {
                    676:             return -1;
                    677:         }
                    678:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    679:         for (; k < len; k++) {
                    680:             if (k in t && t[k] === searchElement) {
                    681:                 return k;
                    682:             }
                    683:         }
                    684:         return -1;
                    685:     }
                    686: }
                    687: 
                    688: // ]]>
                    689: </script>
                    690: 
                    691: ENDJS
                    692: 
                    693: }
                    694: 
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.1075.2.31  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.1075.2.31  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.1075.2.14  raeburn   905:             if (!field[i].disabled) {
                    906:                 field[i].checked = true;
                    907:             }
1.273     raeburn   908:         }
                    909:     } else {
1.1075.2.14  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.1075.2.32  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.1075.2.32  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.648     raeburn  1020: =item * &linked_select_forms(...)
1.36      matthew  1021: 
                   1022: linked_select_forms returns a string containing a <script></script> block
                   1023: and html for two <select> menus.  The select menus will be linked in that
                   1024: changing the value of the first menu will result in new values being placed
                   1025: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1026: order unless a defined order is provided.
1.36      matthew  1027: 
                   1028: linked_select_forms takes the following ordered inputs:
                   1029: 
                   1030: =over 4
                   1031: 
1.112     bowersj2 1032: =item * $formname, the name of the <form> tag
1.36      matthew  1033: 
1.112     bowersj2 1034: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1035: 
1.112     bowersj2 1036: =item * $firstdefault, the default value for the first menu
1.36      matthew  1037: 
1.112     bowersj2 1038: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1039: 
1.112     bowersj2 1040: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1041: 
1.112     bowersj2 1042: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1043: 
1.609     raeburn  1044: =item * $menuorder, the order of values in the first menu
                   1045: 
1.1075.2.31  raeburn  1046: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1047:         event for the first <select> tag
                   1048: 
                   1049: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1050:         event for the second <select> tag
                   1051: 
1.41      ng       1052: =back 
                   1053: 
1.36      matthew  1054: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1055: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1056: values for the first select menu.  The text that coincides with the 
1.41      ng       1057: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1058: and text for the second menu are given in the hash pointed to by 
                   1059: $menu{$choice1}->{'select2'}.  
                   1060: 
1.112     bowersj2 1061:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1062:                        default => "B3",
                   1063:                        select2 => { 
                   1064:                            B1 => "Choice B1",
                   1065:                            B2 => "Choice B2",
                   1066:                            B3 => "Choice B3",
                   1067:                            B4 => "Choice B4"
1.609     raeburn  1068:                            },
                   1069:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1070:                    },
                   1071:                A2 => { text =>"Choice A2" ,
                   1072:                        default => "C2",
                   1073:                        select2 => { 
                   1074:                            C1 => "Choice C1",
                   1075:                            C2 => "Choice C2",
                   1076:                            C3 => "Choice C3"
1.609     raeburn  1077:                            },
                   1078:                        order => ['C2','C1','C3'],
1.112     bowersj2 1079:                    },
                   1080:                A3 => { text =>"Choice A3" ,
                   1081:                        default => "D6",
                   1082:                        select2 => { 
                   1083:                            D1 => "Choice D1",
                   1084:                            D2 => "Choice D2",
                   1085:                            D3 => "Choice D3",
                   1086:                            D4 => "Choice D4",
                   1087:                            D5 => "Choice D5",
                   1088:                            D6 => "Choice D6",
                   1089:                            D7 => "Choice D7"
1.609     raeburn  1090:                            },
                   1091:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1092:                    }
                   1093:                );
1.36      matthew  1094: 
                   1095: =cut
                   1096: 
                   1097: sub linked_select_forms {
                   1098:     my ($formname,
                   1099:         $middletext,
                   1100:         $firstdefault,
                   1101:         $firstselectname,
                   1102:         $secondselectname, 
1.609     raeburn  1103:         $hashref,
                   1104:         $menuorder,
1.1075.2.31  raeburn  1105:         $onchangefirst,
                   1106:         $onchangesecond
1.36      matthew  1107:         ) = @_;
                   1108:     my $second = "document.$formname.$secondselectname";
                   1109:     my $first = "document.$formname.$firstselectname";
                   1110:     # output the javascript to do the changing
                   1111:     my $result = '';
1.776     bisitz   1112:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1113:     $result.="// <![CDATA[\n";
1.36      matthew  1114:     $result.="var select2data = new Object();\n";
                   1115:     $" = '","';
                   1116:     my $debug = '';
                   1117:     foreach my $s1 (sort(keys(%$hashref))) {
                   1118:         $result.="select2data.d_$s1 = new Object();\n";        
                   1119:         $result.="select2data.d_$s1.def = new String('".
                   1120:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1121:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1122:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1123:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1124:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1125:         }
1.36      matthew  1126:         $result.="\"@s2values\");\n";
                   1127:         $result.="select2data.d_$s1.texts = new Array(";        
                   1128:         my @s2texts;
                   1129:         foreach my $value (@s2values) {
                   1130:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1131:         }
                   1132:         $result.="\"@s2texts\");\n";
                   1133:     }
                   1134:     $"=' ';
                   1135:     $result.= <<"END";
                   1136: 
                   1137: function select1_changed() {
                   1138:     // Determine new choice
                   1139:     var newvalue = "d_" + $first.value;
                   1140:     // update select2
                   1141:     var values     = select2data[newvalue].values;
                   1142:     var texts      = select2data[newvalue].texts;
                   1143:     var select2def = select2data[newvalue].def;
                   1144:     var i;
                   1145:     // out with the old
                   1146:     for (i = 0; i < $second.options.length; i++) {
                   1147:         $second.options[i] = null;
                   1148:     }
                   1149:     // in with the nuclear
                   1150:     for (i=0;i<values.length; i++) {
                   1151:         $second.options[i] = new Option(values[i]);
1.143     matthew  1152:         $second.options[i].value = values[i];
1.36      matthew  1153:         $second.options[i].text = texts[i];
                   1154:         if (values[i] == select2def) {
                   1155:             $second.options[i].selected = true;
                   1156:         }
                   1157:     }
                   1158: }
1.824     bisitz   1159: // ]]>
1.36      matthew  1160: </script>
                   1161: END
                   1162:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1163:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1164:     my @order = sort(keys(%{$hashref}));
                   1165:     if (ref($menuorder) eq 'ARRAY') {
                   1166:         @order = @{$menuorder};
                   1167:     }
                   1168:     foreach my $value (@order) {
1.36      matthew  1169:         $result.="    <option value=\"$value\" ";
1.253     albertel 1170:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1171:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1172:     }
                   1173:     $result .= "</select>\n";
                   1174:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1175:     $result .= $middletext;
1.1075.2.31  raeburn  1176:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1177:     if ($onchangesecond) {
                   1178:         $result .= ' onchange="'.$onchangesecond.'"';
                   1179:     }
                   1180:     $result .= ">\n";
1.36      matthew  1181:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1182:     
                   1183:     my @secondorder = sort(keys(%select2));
                   1184:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1185:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1186:     }
                   1187:     foreach my $value (@secondorder) {
1.36      matthew  1188:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1189:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1190:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1191:     }
                   1192:     $result .= "</select>\n";
                   1193:     #    return $debug;
                   1194:     return $result;
                   1195: }   #  end of sub linked_select_forms {
                   1196: 
1.45      matthew  1197: =pod
1.44      bowersj2 1198: 
1.973     raeburn  1199: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1200: 
1.112     bowersj2 1201: Returns a string corresponding to an HTML link to the given help
                   1202: $topic, where $topic corresponds to the name of a .tex file in
                   1203: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1204: spaces. 
                   1205: 
                   1206: $text will optionally be linked to the same topic, allowing you to
                   1207: link text in addition to the graphic. If you do not want to link
                   1208: text, but wish to specify one of the later parameters, pass an
                   1209: empty string. 
                   1210: 
                   1211: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1212: the link will not open a new window. If false, the link will open
                   1213: a new window using Javascript. (Default is false.) 
                   1214: 
                   1215: $width and $height are optional numerical parameters that will
                   1216: override the width and height of the popped up window, which may
1.973     raeburn  1217: be useful for certain help topics with big pictures included.
                   1218: 
                   1219: $imgid is the id of the img tag used for the help icon. This may be
                   1220: used in a javascript call to switch the image src.  See 
                   1221: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1222: 
                   1223: =cut
                   1224: 
                   1225: sub help_open_topic {
1.973     raeburn  1226:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1227:     $text = "" if (not defined $text);
1.44      bowersj2 1228:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1229:     $width = 500 if (not defined $width);
1.44      bowersj2 1230:     $height = 400 if (not defined $height);
                   1231:     my $filename = $topic;
                   1232:     $filename =~ s/ /_/g;
                   1233: 
1.48      bowersj2 1234:     my $template = "";
                   1235:     my $link;
1.572     banghart 1236:     
1.159     www      1237:     $topic=~s/\W/\_/g;
1.44      bowersj2 1238: 
1.572     banghart 1239:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1240:         if ($env{'browser.mobile'}) {
                   1241: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1242:         } else {
                   1243:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1244:         }
1.1037    www      1245:     } elsif ($stayOnPage eq 'popup') {
                   1246:         $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 1247:     } else {
1.48      bowersj2 1248: 	$link = "/adm/help/${filename}.hlp";
                   1249:     }
                   1250: 
                   1251:     # Add the text
1.755     neumanie 1252:     if ($text ne "") {	
1.763     bisitz   1253: 	$template.='<span class="LC_help_open_topic">'
                   1254:                   .'<a target="_top" href="'.$link.'">'
                   1255:                   .$text.'</a>';
1.48      bowersj2 1256:     }
                   1257: 
1.763     bisitz   1258:     # (Always) Add the graphic
1.179     matthew  1259:     my $title = &mt('Online Help');
1.667     raeburn  1260:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1261:     if ($imgid ne '') {
                   1262:         $imgid = ' id="'.$imgid.'"';
                   1263:     }
1.763     bisitz   1264:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1265:               .'<img src="'.$helpicon.'" border="0"'
                   1266:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1267:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1268:               .' /></a>';
                   1269:     if ($text ne "") {	
                   1270:         $template.='</span>';
                   1271:     }
1.44      bowersj2 1272:     return $template;
                   1273: 
1.106     bowersj2 1274: }
                   1275: 
                   1276: # This is a quicky function for Latex cheatsheet editing, since it 
                   1277: # appears in at least four places
                   1278: sub helpLatexCheatsheet {
1.1037    www      1279:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1280:     my $out;
1.106     bowersj2 1281:     my $addOther = '';
1.732     raeburn  1282:     if ($topic) {
1.1037    www      1283: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1284:     }
                   1285:     $out = '<span>' # Start cheatsheet
                   1286: 	  .$addOther
                   1287:           .'<span>'
1.1037    www      1288: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1289: 	  .'</span> <span>'
1.1037    www      1290: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1291: 	  .'</span>';
1.732     raeburn  1292:     unless ($not_author) {
1.763     bisitz   1293:         $out .= ' <span>'
1.1037    www      1294: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1295: 	       .'</span> <span>'
1.1075.2.78  raeburn  1296:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1297:                .'</span>';
1.732     raeburn  1298:     }
1.763     bisitz   1299:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1300:     return $out;
1.172     www      1301: }
                   1302: 
1.430     albertel 1303: sub general_help {
                   1304:     my $helptopic='Student_Intro';
                   1305:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1306: 	$helptopic='Authoring_Intro';
1.907     raeburn  1307:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1308: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1309:     } elsif ($env{'request.role'}=~/^dc/) {
                   1310:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1311:     }
                   1312:     return $helptopic;
                   1313: }
                   1314: 
                   1315: sub update_help_link {
                   1316:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1317:     my $origurl = $ENV{'REQUEST_URI'};
                   1318:     $origurl=~s|^/~|/priv/|;
                   1319:     my $timestamp = time;
                   1320:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1321:         $$datum = &escape($$datum);
                   1322:     }
                   1323: 
                   1324:     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";
                   1325:     my $output .= <<"ENDOUTPUT";
                   1326: <script type="text/javascript">
1.824     bisitz   1327: // <![CDATA[
1.430     albertel 1328: banner_link = '$banner_link';
1.824     bisitz   1329: // ]]>
1.430     albertel 1330: </script>
                   1331: ENDOUTPUT
                   1332:     return $output;
                   1333: }
                   1334: 
                   1335: # now just updates the help link and generates a blue icon
1.193     raeburn  1336: sub help_open_menu {
1.430     albertel 1337:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1338: 	= @_;    
1.949     droeschl 1339:     $stayOnPage = 1;
1.430     albertel 1340:     my $output;
                   1341:     if ($component_help) {
                   1342: 	if (!$text) {
                   1343: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1344: 				       $width,$height);
                   1345: 	} else {
                   1346: 	    my $help_text;
                   1347: 	    $help_text=&unescape($topic);
                   1348: 	    $output='<table><tr><td>'.
                   1349: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1350: 				 $width,$height).'</td></tr></table>';
                   1351: 	}
                   1352:     }
                   1353:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1354:     return $output.$banner_link;
                   1355: }
                   1356: 
                   1357: sub top_nav_help {
                   1358:     my ($text) = @_;
1.436     albertel 1359:     $text = &mt($text);
1.1075.2.60  raeburn  1360:     my $stay_on_page;
                   1361:     unless ($env{'environment.remote'} eq 'on') {
                   1362:         $stay_on_page = 1;
                   1363:     }
1.1075.2.61  raeburn  1364:     my ($link,$banner_link);
                   1365:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1366:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1367: 	                         : "javascript:helpMenu('open')";
                   1368:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1369:     }
1.201     raeburn  1370:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1371:     if ($link) {
                   1372:         return <<"END";
1.436     albertel 1373: $banner_link
1.1075.2.56  raeburn  1374: <a href="$link" title="$title">$text</a>
1.436     albertel 1375: END
1.1075.2.61  raeburn  1376:     } else {
                   1377:         return '&nbsp;'.$text.'&nbsp;';
                   1378:     }
1.436     albertel 1379: }
                   1380: 
                   1381: sub help_menu_js {
1.1075.2.52  raeburn  1382:     my ($httphost) = @_;
1.949     droeschl 1383:     my $stayOnPage = 1;
1.436     albertel 1384:     my $width = 620;
                   1385:     my $height = 600;
1.430     albertel 1386:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1387:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1388:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1389:     my $start_page =
                   1390:         &Apache::loncommon::start_page('Help Menu', undef,
                   1391: 				       {'frameset'    => 1,
                   1392: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1393:                                         'use_absolute' => $httphost, 
1.331     albertel 1394: 					'add_entries' => {
                   1395: 					    'border' => '0',
1.579     raeburn  1396: 					    'rows'   => "110,*",},});
1.331     albertel 1397:     my $end_page =
                   1398:         &Apache::loncommon::end_page({'frameset' => 1,
                   1399: 				      'js_ready' => 1,});
                   1400: 
1.436     albertel 1401:     my $template .= <<"ENDTEMPLATE";
                   1402: <script type="text/javascript">
1.877     bisitz   1403: // <![CDATA[
1.253     albertel 1404: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1405: var banner_link = '';
1.243     raeburn  1406: function helpMenu(target) {
                   1407:     var caller = this;
                   1408:     if (target == 'open') {
                   1409:         var newWindow = null;
                   1410:         try {
1.262     albertel 1411:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1412:         }
                   1413:         catch(error) {
                   1414:             writeHelp(caller);
                   1415:             return;
                   1416:         }
                   1417:         if (newWindow) {
                   1418:             caller = newWindow;
                   1419:         }
1.193     raeburn  1420:     }
1.243     raeburn  1421:     writeHelp(caller);
                   1422:     return;
                   1423: }
                   1424: function writeHelp(caller) {
1.1075.2.61  raeburn  1425:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1426:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1427:     caller.document.close();
                   1428:     caller.focus();
1.193     raeburn  1429: }
1.877     bisitz   1430: // END LON-CAPA Internal -->
1.253     albertel 1431: // ]]>
1.436     albertel 1432: </script>
1.193     raeburn  1433: ENDTEMPLATE
                   1434:     return $template;
                   1435: }
                   1436: 
1.172     www      1437: sub help_open_bug {
                   1438:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1439:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1440:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1441:     $text = "" if (not defined $text);
                   1442: 	$stayOnPage=1;
1.184     albertel 1443:     $width = 600 if (not defined $width);
                   1444:     $height = 600 if (not defined $height);
1.172     www      1445: 
                   1446:     $topic=~s/\W+/\+/g;
                   1447:     my $link='';
                   1448:     my $template='';
1.379     albertel 1449:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1450: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1451:     if (!$stayOnPage)
                   1452:     {
                   1453: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1454:     }
                   1455:     else
                   1456:     {
                   1457: 	$link = $url;
                   1458:     }
                   1459:     # Add the text
                   1460:     if ($text ne "")
                   1461:     {
                   1462: 	$template .= 
                   1463:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1464:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1465:     }
                   1466: 
                   1467:     # Add the graphic
1.179     matthew  1468:     my $title = &mt('Report a Bug');
1.215     albertel 1469:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1470:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1471:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1472: ENDTEMPLATE
                   1473:     if ($text ne '') { $template.='</td></tr></table>' };
                   1474:     return $template;
                   1475: 
                   1476: }
                   1477: 
                   1478: sub help_open_faq {
                   1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1480:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1481:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1482:     $text = "" if (not defined $text);
                   1483: 	$stayOnPage=1;
                   1484:     $width = 350 if (not defined $width);
                   1485:     $height = 400 if (not defined $height);
                   1486: 
                   1487:     $topic=~s/\W+/\+/g;
                   1488:     my $link='';
                   1489:     my $template='';
                   1490:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1491:     if (!$stayOnPage)
                   1492:     {
                   1493: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1494:     }
                   1495:     else
                   1496:     {
                   1497: 	$link = $url;
                   1498:     }
                   1499: 
                   1500:     # Add the text
                   1501:     if ($text ne "")
                   1502:     {
                   1503: 	$template .= 
1.173     www      1504:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1505:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1506:     }
                   1507: 
                   1508:     # Add the graphic
1.179     matthew  1509:     my $title = &mt('View the FAQ');
1.215     albertel 1510:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1511:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1512:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1513: ENDTEMPLATE
                   1514:     if ($text ne '') { $template.='</td></tr></table>' };
                   1515:     return $template;
                   1516: 
1.44      bowersj2 1517: }
1.37      matthew  1518: 
1.180     matthew  1519: ###############################################################
                   1520: ###############################################################
                   1521: 
1.45      matthew  1522: =pod
                   1523: 
1.648     raeburn  1524: =item * &change_content_javascript():
1.256     matthew  1525: 
                   1526: This and the next function allow you to create small sections of an
                   1527: otherwise static HTML page that you can update on the fly with
                   1528: Javascript, even in Netscape 4.
                   1529: 
                   1530: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1531: must be written to the HTML page once. It will prove the Javascript
                   1532: function "change(name, content)". Calling the change function with the
                   1533: name of the section 
                   1534: you want to update, matching the name passed to C<changable_area>, and
                   1535: the new content you want to put in there, will put the content into
                   1536: that area.
                   1537: 
                   1538: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1539: to contain room for the original contents. You need to "make space"
                   1540: for whatever changes you wish to make, and be B<sure> to check your
                   1541: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1542: it's adequate for updating a one-line status display, but little more.
                   1543: This script will set the space to 100% width, so you only need to
                   1544: worry about height in Netscape 4.
                   1545: 
                   1546: Modern browsers are much less limiting, and if you can commit to the
                   1547: user not using Netscape 4, this feature may be used freely with
                   1548: pretty much any HTML.
                   1549: 
                   1550: =cut
                   1551: 
                   1552: sub change_content_javascript {
                   1553:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1554:     if ($env{'browser.type'} eq 'netscape' &&
                   1555: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1556: 	return (<<NETSCAPE4);
                   1557: 	function change(name, content) {
                   1558: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1559: 	    doc.open();
                   1560: 	    doc.write(content);
                   1561: 	    doc.close();
                   1562: 	}
                   1563: NETSCAPE4
                   1564:     } else {
                   1565: 	# Otherwise, we need to use semi-standards-compliant code
                   1566: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1567: 	# is really scary, and every useful browser supports it
                   1568: 	return (<<DOMBASED);
                   1569: 	function change(name, content) {
                   1570: 	    element = document.getElementById(name);
                   1571: 	    element.innerHTML = content;
                   1572: 	}
                   1573: DOMBASED
                   1574:     }
                   1575: }
                   1576: 
                   1577: =pod
                   1578: 
1.648     raeburn  1579: =item * &changable_area($name,$origContent):
1.256     matthew  1580: 
                   1581: This provides a "changable area" that can be modified on the fly via
                   1582: the Javascript code provided in C<change_content_javascript>. $name is
                   1583: the name you will use to reference the area later; do not repeat the
                   1584: same name on a given HTML page more then once. $origContent is what
                   1585: the area will originally contain, which can be left blank.
                   1586: 
                   1587: =cut
                   1588: 
                   1589: sub changable_area {
                   1590:     my ($name, $origContent) = @_;
                   1591: 
1.258     albertel 1592:     if ($env{'browser.type'} eq 'netscape' &&
                   1593: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1594: 	# If this is netscape 4, we need to use the Layer tag
                   1595: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1596:     } else {
                   1597: 	return "<span id='$name'>$origContent</span>";
                   1598:     }
                   1599: }
                   1600: 
                   1601: =pod
                   1602: 
1.648     raeburn  1603: =item * &viewport_geometry_js 
1.590     raeburn  1604: 
                   1605: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1606: 
                   1607: =cut
                   1608: 
                   1609: 
                   1610: sub viewport_geometry_js { 
                   1611:     return <<"GEOMETRY";
                   1612: var Geometry = {};
                   1613: function init_geometry() {
                   1614:     if (Geometry.init) { return };
                   1615:     Geometry.init=1;
                   1616:     if (window.innerHeight) {
                   1617:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1618:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1619:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1620:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1621:     }
                   1622:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1623:         Geometry.getViewportHeight =
                   1624:             function() { return document.documentElement.clientHeight; };
                   1625:         Geometry.getViewportWidth =
                   1626:             function() { return document.documentElement.clientWidth; };
                   1627: 
                   1628:         Geometry.getHorizontalScroll =
                   1629:             function() { return document.documentElement.scrollLeft; };
                   1630:         Geometry.getVerticalScroll =
                   1631:             function() { return document.documentElement.scrollTop; };
                   1632:     }
                   1633:     else if (document.body.clientHeight) {
                   1634:         Geometry.getViewportHeight =
                   1635:             function() { return document.body.clientHeight; };
                   1636:         Geometry.getViewportWidth =
                   1637:             function() { return document.body.clientWidth; };
                   1638:         Geometry.getHorizontalScroll =
                   1639:             function() { return document.body.scrollLeft; };
                   1640:         Geometry.getVerticalScroll =
                   1641:             function() { return document.body.scrollTop; };
                   1642:     }
                   1643: }
                   1644: 
                   1645: GEOMETRY
                   1646: }
                   1647: 
                   1648: =pod
                   1649: 
1.648     raeburn  1650: =item * &viewport_size_js()
1.590     raeburn  1651: 
                   1652: 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. 
                   1653: 
                   1654: =cut
                   1655: 
                   1656: sub viewport_size_js {
                   1657:     my $geometry = &viewport_geometry_js();
                   1658:     return <<"DIMS";
                   1659: 
                   1660: $geometry
                   1661: 
                   1662: function getViewportDims(width,height) {
                   1663:     init_geometry();
                   1664:     width.value = Geometry.getViewportWidth();
                   1665:     height.value = Geometry.getViewportHeight();
                   1666:     return;
                   1667: }
                   1668: 
                   1669: DIMS
                   1670: }
                   1671: 
                   1672: =pod
                   1673: 
1.648     raeburn  1674: =item * &resize_textarea_js()
1.565     albertel 1675: 
                   1676: emits the needed javascript to resize a textarea to be as big as possible
                   1677: 
                   1678: creates a function resize_textrea that takes two IDs first should be
                   1679: the id of the element to resize, second should be the id of a div that
                   1680: surrounds everything that comes after the textarea, this routine needs
                   1681: to be attached to the <body> for the onload and onresize events.
                   1682: 
1.648     raeburn  1683: =back
1.565     albertel 1684: 
                   1685: =cut
                   1686: 
                   1687: sub resize_textarea_js {
1.590     raeburn  1688:     my $geometry = &viewport_geometry_js();
1.565     albertel 1689:     return <<"RESIZE";
                   1690:     <script type="text/javascript">
1.824     bisitz   1691: // <![CDATA[
1.590     raeburn  1692: $geometry
1.565     albertel 1693: 
1.588     albertel 1694: function getX(element) {
                   1695:     var x = 0;
                   1696:     while (element) {
                   1697: 	x += element.offsetLeft;
                   1698: 	element = element.offsetParent;
                   1699:     }
                   1700:     return x;
                   1701: }
                   1702: function getY(element) {
                   1703:     var y = 0;
                   1704:     while (element) {
                   1705: 	y += element.offsetTop;
                   1706: 	element = element.offsetParent;
                   1707:     }
                   1708:     return y;
                   1709: }
                   1710: 
                   1711: 
1.565     albertel 1712: function resize_textarea(textarea_id,bottom_id) {
                   1713:     init_geometry();
                   1714:     var textarea        = document.getElementById(textarea_id);
                   1715:     //alert(textarea);
                   1716: 
1.588     albertel 1717:     var textarea_top    = getY(textarea);
1.565     albertel 1718:     var textarea_height = textarea.offsetHeight;
                   1719:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1720:     var bottom_top      = getY(bottom);
1.565     albertel 1721:     var bottom_height   = bottom.offsetHeight;
                   1722:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1723:     var fudge           = 23;
1.565     albertel 1724:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1725:     if (new_height < 300) {
                   1726: 	new_height = 300;
                   1727:     }
                   1728:     textarea.style.height=new_height+'px';
                   1729: }
1.824     bisitz   1730: // ]]>
1.565     albertel 1731: </script>
                   1732: RESIZE
                   1733: 
                   1734: }
                   1735: 
                   1736: =pod
                   1737: 
1.256     matthew  1738: =head1 Excel and CSV file utility routines
                   1739: 
                   1740: =cut
                   1741: 
                   1742: ###############################################################
                   1743: ###############################################################
                   1744: 
                   1745: =pod
                   1746: 
1.1075.2.56  raeburn  1747: =over 4
                   1748: 
1.648     raeburn  1749: =item * &csv_translate($text) 
1.37      matthew  1750: 
1.185     www      1751: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1752: format.
                   1753: 
                   1754: =cut
                   1755: 
1.180     matthew  1756: ###############################################################
                   1757: ###############################################################
1.37      matthew  1758: sub csv_translate {
                   1759:     my $text = shift;
                   1760:     $text =~ s/\"/\"\"/g;
1.209     albertel 1761:     $text =~ s/\n/ /g;
1.37      matthew  1762:     return $text;
                   1763: }
1.180     matthew  1764: 
                   1765: ###############################################################
                   1766: ###############################################################
                   1767: 
                   1768: =pod
                   1769: 
1.648     raeburn  1770: =item * &define_excel_formats()
1.180     matthew  1771: 
                   1772: Define some commonly used Excel cell formats.
                   1773: 
                   1774: Currently supported formats:
                   1775: 
                   1776: =over 4
                   1777: 
                   1778: =item header
                   1779: 
                   1780: =item bold
                   1781: 
                   1782: =item h1
                   1783: 
                   1784: =item h2
                   1785: 
                   1786: =item h3
                   1787: 
1.256     matthew  1788: =item h4
                   1789: 
                   1790: =item i
                   1791: 
1.180     matthew  1792: =item date
                   1793: 
                   1794: =back
                   1795: 
                   1796: Inputs: $workbook
                   1797: 
                   1798: Returns: $format, a hash reference.
                   1799: 
1.1057    foxr     1800: 
1.180     matthew  1801: =cut
                   1802: 
                   1803: ###############################################################
                   1804: ###############################################################
                   1805: sub define_excel_formats {
                   1806:     my ($workbook) = @_;
                   1807:     my $format;
                   1808:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1809:                                                 bottom    => 1,
                   1810:                                                 align     => 'center');
                   1811:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1812:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1813:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1814:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1815:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1816:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1817:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1818:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1819:     return $format;
                   1820: }
                   1821: 
                   1822: ###############################################################
                   1823: ###############################################################
1.113     bowersj2 1824: 
                   1825: =pod
                   1826: 
1.648     raeburn  1827: =item * &create_workbook()
1.255     matthew  1828: 
                   1829: Create an Excel worksheet.  If it fails, output message on the
                   1830: request object and return undefs.
                   1831: 
                   1832: Inputs: Apache request object
                   1833: 
                   1834: Returns (undef) on failure, 
                   1835:     Excel worksheet object, scalar with filename, and formats 
                   1836:     from &Apache::loncommon::define_excel_formats on success
                   1837: 
                   1838: =cut
                   1839: 
                   1840: ###############################################################
                   1841: ###############################################################
                   1842: sub create_workbook {
                   1843:     my ($r) = @_;
                   1844:         #
                   1845:     # Create the excel spreadsheet
                   1846:     my $filename = '/prtspool/'.
1.258     albertel 1847:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1848:         time.'_'.rand(1000000000).'.xls';
                   1849:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1850:     if (! defined($workbook)) {
                   1851:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1852:         $r->print(
                   1853:             '<p class="LC_error">'
                   1854:            .&mt('Problems occurred in creating the new Excel file.')
                   1855:            .' '.&mt('This error has been logged.')
                   1856:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1857:            .'</p>'
                   1858:         );
1.255     matthew  1859:         return (undef);
                   1860:     }
                   1861:     #
1.1014    foxr     1862:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1863:     #
                   1864:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1865:     return ($workbook,$filename,$format);
                   1866: }
                   1867: 
                   1868: ###############################################################
                   1869: ###############################################################
                   1870: 
                   1871: =pod
                   1872: 
1.648     raeburn  1873: =item * &create_text_file()
1.113     bowersj2 1874: 
1.542     raeburn  1875: Create a file to write to and eventually make available to the user.
1.256     matthew  1876: If file creation fails, outputs an error message on the request object and 
                   1877: return undefs.
1.113     bowersj2 1878: 
1.256     matthew  1879: Inputs: Apache request object, and file suffix
1.113     bowersj2 1880: 
1.256     matthew  1881: Returns (undef) on failure, 
                   1882:     Filehandle and filename on success.
1.113     bowersj2 1883: 
                   1884: =cut
                   1885: 
1.256     matthew  1886: ###############################################################
                   1887: ###############################################################
                   1888: sub create_text_file {
                   1889:     my ($r,$suffix) = @_;
                   1890:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1891:     my $fh;
                   1892:     my $filename = '/prtspool/'.
1.258     albertel 1893:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1894:         time.'_'.rand(1000000000).'.'.$suffix;
                   1895:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1896:     if (! defined($fh)) {
                   1897:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1898:         $r->print(
                   1899:             '<p class="LC_error">'
                   1900:            .&mt('Problems occurred in creating the output file.')
                   1901:            .' '.&mt('This error has been logged.')
                   1902:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1903:            .'</p>'
                   1904:         );
1.113     bowersj2 1905:     }
1.256     matthew  1906:     return ($fh,$filename)
1.113     bowersj2 1907: }
                   1908: 
                   1909: 
1.256     matthew  1910: =pod 
1.113     bowersj2 1911: 
                   1912: =back
                   1913: 
                   1914: =cut
1.37      matthew  1915: 
                   1916: ###############################################################
1.33      matthew  1917: ##        Home server <option> list generating code          ##
                   1918: ###############################################################
1.35      matthew  1919: 
1.169     www      1920: # ------------------------------------------
                   1921: 
                   1922: sub domain_select {
                   1923:     my ($name,$value,$multiple)=@_;
                   1924:     my %domains=map { 
1.514     albertel 1925: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1926:     } &Apache::lonnet::all_domains();
1.169     www      1927:     if ($multiple) {
                   1928: 	$domains{''}=&mt('Any domain');
1.550     albertel 1929: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1930: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1931:     } else {
1.550     albertel 1932: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1933: 	return &select_form($name,$value,\%domains);
1.169     www      1934:     }
                   1935: }
                   1936: 
1.282     albertel 1937: #-------------------------------------------
                   1938: 
                   1939: =pod
                   1940: 
1.519     raeburn  1941: =head1 Routines for form select boxes
                   1942: 
                   1943: =over 4
                   1944: 
1.648     raeburn  1945: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1946: 
                   1947: Returns a string containing a <select> element int multiple mode
                   1948: 
                   1949: 
                   1950: Args:
                   1951:   $name - name of the <select> element
1.506     raeburn  1952:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1953:   $size - number of rows long the select element is
1.283     albertel 1954:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1955:           (shown text should already have been &mt())
1.506     raeburn  1956:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1957: 
1.282     albertel 1958: =cut
                   1959: 
                   1960: #-------------------------------------------
1.169     www      1961: sub multiple_select_form {
1.284     albertel 1962:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1963:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1964:     my $output='';
1.191     matthew  1965:     if (! defined($size)) {
                   1966:         $size = 4;
1.283     albertel 1967:         if (scalar(keys(%$hash))<4) {
                   1968:             $size = scalar(keys(%$hash));
1.191     matthew  1969:         }
                   1970:     }
1.734     bisitz   1971:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1972:     my @order;
1.506     raeburn  1973:     if (ref($order) eq 'ARRAY')  {
                   1974:         @order = @{$order};
                   1975:     } else {
                   1976:         @order = sort(keys(%$hash));
1.501     banghart 1977:     }
                   1978:     if (exists($$hash{'select_form_order'})) {
                   1979:         @order = @{$$hash{'select_form_order'}};
                   1980:     }
                   1981:         
1.284     albertel 1982:     foreach my $key (@order) {
1.356     albertel 1983:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1984:         $output.='selected="selected" ' if ($selected{$key});
                   1985:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1986:     }
                   1987:     $output.="</select>\n";
                   1988:     return $output;
                   1989: }
                   1990: 
1.88      www      1991: #-------------------------------------------
                   1992: 
                   1993: =pod
                   1994: 
1.970     raeburn  1995: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1996: 
                   1997: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1998: allow a user to select options from a ref to a hash containing:
                   1999: option_name => displayed text. An optional $onchange can include
                   2000: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2001: 
1.88      www      2002: See lonrights.pm for an example invocation and use.
                   2003: 
                   2004: =cut
                   2005: 
                   2006: #-------------------------------------------
                   2007: sub select_form {
1.970     raeburn  2008:     my ($def,$name,$hashref,$onchange) = @_;
                   2009:     return unless (ref($hashref) eq 'HASH');
                   2010:     if ($onchange) {
                   2011:         $onchange = ' onchange="'.$onchange.'"';
                   2012:     }
                   2013:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2014:     my @keys;
1.970     raeburn  2015:     if (exists($hashref->{'select_form_order'})) {
                   2016: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2017:     } else {
1.970     raeburn  2018: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2019:     }
1.356     albertel 2020:     foreach my $key (@keys) {
                   2021:         $selectform.=
                   2022: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2023:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2024:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2025:     }
                   2026:     $selectform.="</select>";
                   2027:     return $selectform;
                   2028: }
                   2029: 
1.475     www      2030: # For display filters
                   2031: 
                   2032: sub display_filter {
1.1074    raeburn  2033:     my ($context) = @_;
1.475     www      2034:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2035:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2036:     my $phraseinput = 'hidden';
                   2037:     my $includeinput = 'hidden';
                   2038:     my ($checked,$includetypestext);
                   2039:     if ($env{'form.displayfilter'} eq 'containing') {
                   2040:         $phraseinput = 'text'; 
                   2041:         if ($context eq 'parmslog') {
                   2042:             $includeinput = 'checkbox';
                   2043:             if ($env{'form.includetypes'}) {
                   2044:                 $checked = ' checked="checked"';
                   2045:             }
                   2046:             $includetypestext = &mt('Include parameter types');
                   2047:         }
                   2048:     } else {
                   2049:         $includetypestext = '&nbsp;';
                   2050:     }
                   2051:     my ($additional,$secondid,$thirdid);
                   2052:     if ($context eq 'parmslog') {
                   2053:         $additional = 
                   2054:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2055:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2056:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2057:             '</label>';
                   2058:         $secondid = 'includetypes';
                   2059:         $thirdid = 'includetypestext';
                   2060:     }
                   2061:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2062:                                                     '$secondid','$thirdid')";
                   2063:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2064: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2065: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2066: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2067:            &mt('Filter: [_1]',
1.477     www      2068: 	   &select_form($env{'form.displayfilter'},
                   2069: 			'displayfilter',
1.970     raeburn  2070: 			{'currentfolder' => 'Current folder/page',
1.477     www      2071: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2072: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2073: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2074:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2075:                          '" />'.$additional;
                   2076: }
                   2077: 
                   2078: sub display_filter_js {
                   2079:     my $includetext = &mt('Include parameter types');
                   2080:     return <<"ENDJS";
                   2081:   
                   2082: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2083:     var firstType = 'hidden';
                   2084:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2085:         firstType = 'text';
                   2086:     }
                   2087:     firstObject = document.getElementById(firstid);
                   2088:     if (typeof(firstObject) == 'object') {
                   2089:         if (firstObject.type != firstType) {
                   2090:             changeInputType(firstObject,firstType);
                   2091:         }
                   2092:     }
                   2093:     if (context == 'parmslog') {
                   2094:         var secondType = 'hidden';
                   2095:         if (firstType == 'text') {
                   2096:             secondType = 'checkbox';
                   2097:         }
                   2098:         secondObject = document.getElementById(secondid);  
                   2099:         if (typeof(secondObject) == 'object') {
                   2100:             if (secondObject.type != secondType) {
                   2101:                 changeInputType(secondObject,secondType);
                   2102:             }
                   2103:         }
                   2104:         var textItem = document.getElementById(thirdid);
                   2105:         var currtext = textItem.innerHTML;
                   2106:         var newtext;
                   2107:         if (firstType == 'text') {
                   2108:             newtext = '$includetext';
                   2109:         } else {
                   2110:             newtext = '&nbsp;';
                   2111:         }
                   2112:         if (currtext != newtext) {
                   2113:             textItem.innerHTML = newtext;
                   2114:         }
                   2115:     }
                   2116:     return;
                   2117: }
                   2118: 
                   2119: function changeInputType(oldObject,newType) {
                   2120:     var newObject = document.createElement('input');
                   2121:     newObject.type = newType;
                   2122:     if (oldObject.size) {
                   2123:         newObject.size = oldObject.size;
                   2124:     }
                   2125:     if (oldObject.value) {
                   2126:         newObject.value = oldObject.value;
                   2127:     }
                   2128:     if (oldObject.name) {
                   2129:         newObject.name = oldObject.name;
                   2130:     }
                   2131:     if (oldObject.id) {
                   2132:         newObject.id = oldObject.id;
                   2133:     }
                   2134:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2135:     return;
                   2136: }
                   2137: 
                   2138: ENDJS
1.475     www      2139: }
                   2140: 
1.167     www      2141: sub gradeleveldescription {
                   2142:     my $gradelevel=shift;
                   2143:     my %gradelevels=(0 => 'Not specified',
                   2144: 		     1 => 'Grade 1',
                   2145: 		     2 => 'Grade 2',
                   2146: 		     3 => 'Grade 3',
                   2147: 		     4 => 'Grade 4',
                   2148: 		     5 => 'Grade 5',
                   2149: 		     6 => 'Grade 6',
                   2150: 		     7 => 'Grade 7',
                   2151: 		     8 => 'Grade 8',
                   2152: 		     9 => 'Grade 9',
                   2153: 		     10 => 'Grade 10',
                   2154: 		     11 => 'Grade 11',
                   2155: 		     12 => 'Grade 12',
                   2156: 		     13 => 'Grade 13',
                   2157: 		     14 => '100 Level',
                   2158: 		     15 => '200 Level',
                   2159: 		     16 => '300 Level',
                   2160: 		     17 => '400 Level',
                   2161: 		     18 => 'Graduate Level');
                   2162:     return &mt($gradelevels{$gradelevel});
                   2163: }
                   2164: 
1.163     www      2165: sub select_level_form {
                   2166:     my ($deflevel,$name)=@_;
                   2167:     unless ($deflevel) { $deflevel=0; }
1.167     www      2168:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2169:     for (my $i=0; $i<=18; $i++) {
                   2170:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2171:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2172:                 ">".&gradeleveldescription($i)."</option>\n";
                   2173:     }
                   2174:     $selectform.="</select>";
                   2175:     return $selectform;
1.163     www      2176: }
1.167     www      2177: 
1.35      matthew  2178: #-------------------------------------------
                   2179: 
1.45      matthew  2180: =pod
                   2181: 
1.1075.2.42  raeburn  2182: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2183: 
                   2184: Returns a string containing a <select name='$name' size='1'> form to 
                   2185: allow a user to select the domain to preform an operation in.  
                   2186: See loncreateuser.pm for an example invocation and use.
                   2187: 
1.90      www      2188: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2189: selected");
                   2190: 
1.743     raeburn  2191: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2192: 
1.910     raeburn  2193: 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.
                   2194: 
1.1075.2.36  raeburn  2195: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2196: 
                   2197: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
1.563     raeburn  2198: 
1.35      matthew  2199: =cut
                   2200: 
                   2201: #-------------------------------------------
1.34      matthew  2202: sub select_dom_form {
1.1075.2.36  raeburn  2203:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2204:     if ($onchange) {
1.874     raeburn  2205:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2206:     }
1.1075.2.36  raeburn  2207:     my (@domains,%exclude);
1.910     raeburn  2208:     if (ref($incdoms) eq 'ARRAY') {
                   2209:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2210:     } else {
                   2211:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2212:     }
1.90      www      2213:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2214:     if (ref($excdoms) eq 'ARRAY') {
                   2215:         map { $exclude{$_} = 1; } @{$excdoms};
                   2216:     }
1.743     raeburn  2217:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2218:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2219:         next if ($exclude{$dom});
1.356     albertel 2220:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2221:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2222:         if ($showdomdesc) {
                   2223:             if ($dom ne '') {
                   2224:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2225:                 if ($domdesc ne '') {
                   2226:                     $selectdomain .= ' ('.$domdesc.')';
                   2227:                 }
                   2228:             } 
                   2229:         }
                   2230:         $selectdomain .= "</option>\n";
1.34      matthew  2231:     }
                   2232:     $selectdomain.="</select>";
                   2233:     return $selectdomain;
                   2234: }
                   2235: 
1.35      matthew  2236: #-------------------------------------------
                   2237: 
1.45      matthew  2238: =pod
                   2239: 
1.648     raeburn  2240: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2241: 
1.586     raeburn  2242: input: 4 arguments (two required, two optional) - 
                   2243:     $domain - domain of new user
                   2244:     $name - name of form element
                   2245:     $default - Value of 'default' causes a default item to be first 
                   2246:                             option, and selected by default. 
                   2247:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2248:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2249: output: returns 2 items: 
1.586     raeburn  2250: (a) form element which contains either:
                   2251:    (i) <select name="$name">
                   2252:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2253:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2254:        </select>
                   2255:        form item if there are multiple library servers in $domain, or
                   2256:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2257:        if there is only one library server in $domain.
                   2258: 
                   2259: (b) number of library servers found.
                   2260: 
                   2261: See loncreateuser.pm for example of use.
1.35      matthew  2262: 
                   2263: =cut
                   2264: 
                   2265: #-------------------------------------------
1.586     raeburn  2266: sub home_server_form_item {
                   2267:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2268:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2269:     my $result;
                   2270:     my $numlib = keys(%servers);
                   2271:     if ($numlib > 1) {
                   2272:         $result .= '<select name="'.$name.'" />'."\n";
                   2273:         if ($default) {
1.804     bisitz   2274:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2275:                        '</option>'."\n";
                   2276:         }
                   2277:         foreach my $hostid (sort(keys(%servers))) {
                   2278:             $result.= '<option value="'.$hostid.'">'.
                   2279: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2280:         }
                   2281:         $result .= '</select>'."\n";
                   2282:     } elsif ($numlib == 1) {
                   2283:         my $hostid;
                   2284:         foreach my $item (keys(%servers)) {
                   2285:             $hostid = $item;
                   2286:         }
                   2287:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2288:                    $hostid.'" />';
                   2289:                    if (!$hide) {
                   2290:                        $result .= $hostid.' '.$servers{$hostid};
                   2291:                    }
                   2292:                    $result .= "\n";
                   2293:     } elsif ($default) {
                   2294:         $result .= '<input type="hidden" name="'.$name.
                   2295:                    '" value="default" />';
                   2296:                    if (!$hide) {
                   2297:                        $result .= &mt('default');
                   2298:                    }
                   2299:                    $result .= "\n";
1.33      matthew  2300:     }
1.586     raeburn  2301:     return ($result,$numlib);
1.33      matthew  2302: }
1.112     bowersj2 2303: 
                   2304: =pod
                   2305: 
1.534     albertel 2306: =back 
                   2307: 
1.112     bowersj2 2308: =cut
1.87      matthew  2309: 
                   2310: ###############################################################
1.112     bowersj2 2311: ##                  Decoding User Agent                      ##
1.87      matthew  2312: ###############################################################
                   2313: 
                   2314: =pod
                   2315: 
1.112     bowersj2 2316: =head1 Decoding the User Agent
                   2317: 
                   2318: =over 4
                   2319: 
                   2320: =item * &decode_user_agent()
1.87      matthew  2321: 
                   2322: Inputs: $r
                   2323: 
                   2324: Outputs:
                   2325: 
                   2326: =over 4
                   2327: 
1.112     bowersj2 2328: =item * $httpbrowser
1.87      matthew  2329: 
1.112     bowersj2 2330: =item * $clientbrowser
1.87      matthew  2331: 
1.112     bowersj2 2332: =item * $clientversion
1.87      matthew  2333: 
1.112     bowersj2 2334: =item * $clientmathml
1.87      matthew  2335: 
1.112     bowersj2 2336: =item * $clientunicode
1.87      matthew  2337: 
1.112     bowersj2 2338: =item * $clientos
1.87      matthew  2339: 
1.1075.2.42  raeburn  2340: =item * $clientmobile
                   2341: 
                   2342: =item * $clientinfo
                   2343: 
1.1075.2.77  raeburn  2344: =item * $clientosversion
                   2345: 
1.87      matthew  2346: =back
                   2347: 
1.157     matthew  2348: =back 
                   2349: 
1.87      matthew  2350: =cut
                   2351: 
                   2352: ###############################################################
                   2353: ###############################################################
                   2354: sub decode_user_agent {
1.247     albertel 2355:     my ($r)=@_;
1.87      matthew  2356:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2357:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2358:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2359:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2360:     my $clientbrowser='unknown';
                   2361:     my $clientversion='0';
                   2362:     my $clientmathml='';
                   2363:     my $clientunicode='0';
1.1075.2.42  raeburn  2364:     my $clientmobile=0;
1.1075.2.77  raeburn  2365:     my $clientosversion='';
1.87      matthew  2366:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2367:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2368: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2369: 	    $clientbrowser=$bname;
                   2370:             $httpbrowser=~/$vreg/i;
                   2371: 	    $clientversion=$1;
                   2372:             $clientmathml=($clientversion>=$minv);
                   2373:             $clientunicode=($clientversion>=$univ);
                   2374: 	}
                   2375:     }
                   2376:     my $clientos='unknown';
1.1075.2.42  raeburn  2377:     my $clientinfo;
1.87      matthew  2378:     if (($httpbrowser=~/linux/i) ||
                   2379:         ($httpbrowser=~/unix/i) ||
                   2380:         ($httpbrowser=~/ux/i) ||
                   2381:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2382:     if (($httpbrowser=~/vax/i) ||
                   2383:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2384:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2385:     if (($httpbrowser=~/mac/i) ||
                   2386:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2387:     if ($httpbrowser=~/win/i) {
                   2388:         $clientos='win';
                   2389:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2390:             $clientosversion = $1;
                   2391:         }
                   2392:     }
1.87      matthew  2393:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2394:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2395:         $clientmobile=lc($1);
                   2396:     }
                   2397:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2398:         $clientinfo = 'firefox-'.$1;
                   2399:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2400:         $clientinfo = 'chromeframe-'.$1;
                   2401:     }
1.87      matthew  2402:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2403:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2404:             $clientosversion);
1.87      matthew  2405: }
                   2406: 
1.32      matthew  2407: ###############################################################
                   2408: ##    Authentication changing form generation subroutines    ##
                   2409: ###############################################################
                   2410: ##
                   2411: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2412: ## hash, and have reasonable default values.
                   2413: ##
                   2414: ##    formname = the name given in the <form> tag.
1.35      matthew  2415: #-------------------------------------------
                   2416: 
1.45      matthew  2417: =pod
                   2418: 
1.112     bowersj2 2419: =head1 Authentication Routines
                   2420: 
                   2421: =over 4
                   2422: 
1.648     raeburn  2423: =item * &authform_xxxxxx()
1.35      matthew  2424: 
                   2425: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2426: handle some of the conveniences required for authentication forms.  
                   2427: This is not an optimal method, but it works.  
                   2428: 
                   2429: =over 4
                   2430: 
1.112     bowersj2 2431: =item * authform_header
1.35      matthew  2432: 
1.112     bowersj2 2433: =item * authform_authorwarning
1.35      matthew  2434: 
1.112     bowersj2 2435: =item * authform_nochange
1.35      matthew  2436: 
1.112     bowersj2 2437: =item * authform_kerberos
1.35      matthew  2438: 
1.112     bowersj2 2439: =item * authform_internal
1.35      matthew  2440: 
1.112     bowersj2 2441: =item * authform_filesystem
1.35      matthew  2442: 
                   2443: =back
                   2444: 
1.648     raeburn  2445: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2446: 
1.35      matthew  2447: =cut
                   2448: 
                   2449: #-------------------------------------------
1.32      matthew  2450: sub authform_header{  
                   2451:     my %in = (
                   2452:         formname => 'cu',
1.80      albertel 2453:         kerb_def_dom => '',
1.32      matthew  2454:         @_,
                   2455:     );
                   2456:     $in{'formname'} = 'document.' . $in{'formname'};
                   2457:     my $result='';
1.80      albertel 2458: 
                   2459: #---------------------------------------------- Code for upper case translation
                   2460:     my $Javascript_toUpperCase;
                   2461:     unless ($in{kerb_def_dom}) {
                   2462:         $Javascript_toUpperCase =<<"END";
                   2463:         switch (choice) {
                   2464:            case 'krb': currentform.elements[choicearg].value =
                   2465:                currentform.elements[choicearg].value.toUpperCase();
                   2466:                break;
                   2467:            default:
                   2468:         }
                   2469: END
                   2470:     } else {
                   2471:         $Javascript_toUpperCase = "";
                   2472:     }
                   2473: 
1.165     raeburn  2474:     my $radioval = "'nochange'";
1.591     raeburn  2475:     if (defined($in{'curr_authtype'})) {
                   2476:         if ($in{'curr_authtype'} ne '') {
                   2477:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2478:         }
1.174     matthew  2479:     }
1.165     raeburn  2480:     my $argfield = 'null';
1.591     raeburn  2481:     if (defined($in{'mode'})) {
1.165     raeburn  2482:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2483:             if (defined($in{'curr_autharg'})) {
                   2484:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2485:                     $argfield = "'$in{'curr_autharg'}'";
                   2486:                 }
                   2487:             }
                   2488:         }
                   2489:     }
                   2490: 
1.32      matthew  2491:     $result.=<<"END";
                   2492: var current = new Object();
1.165     raeburn  2493: current.radiovalue = $radioval;
                   2494: current.argfield = $argfield;
1.32      matthew  2495: 
                   2496: function changed_radio(choice,currentform) {
                   2497:     var choicearg = choice + 'arg';
                   2498:     // If a radio button in changed, we need to change the argfield
                   2499:     if (current.radiovalue != choice) {
                   2500:         current.radiovalue = choice;
                   2501:         if (current.argfield != null) {
                   2502:             currentform.elements[current.argfield].value = '';
                   2503:         }
                   2504:         if (choice == 'nochange') {
                   2505:             current.argfield = null;
                   2506:         } else {
                   2507:             current.argfield = choicearg;
                   2508:             switch(choice) {
                   2509:                 case 'krb': 
                   2510:                     currentform.elements[current.argfield].value = 
                   2511:                         "$in{'kerb_def_dom'}";
                   2512:                 break;
                   2513:               default:
                   2514:                 break;
                   2515:             }
                   2516:         }
                   2517:     }
                   2518:     return;
                   2519: }
1.22      www      2520: 
1.32      matthew  2521: function changed_text(choice,currentform) {
                   2522:     var choicearg = choice + 'arg';
                   2523:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2524:         $Javascript_toUpperCase
1.32      matthew  2525:         // clear old field
                   2526:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2527:             currentform.elements[current.argfield].value = '';
                   2528:         }
                   2529:         current.argfield = choicearg;
                   2530:     }
                   2531:     set_auth_radio_buttons(choice,currentform);
                   2532:     return;
1.20      www      2533: }
1.32      matthew  2534: 
                   2535: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2536:     var numauthchoices = currentform.login.length;
                   2537:     if (typeof numauthchoices  == "undefined") {
                   2538:         return;
                   2539:     } 
1.32      matthew  2540:     var i=0;
1.986     raeburn  2541:     while (i < numauthchoices) {
1.32      matthew  2542:         if (currentform.login[i].value == newvalue) { break; }
                   2543:         i++;
                   2544:     }
1.986     raeburn  2545:     if (i == numauthchoices) {
1.32      matthew  2546:         return;
                   2547:     }
                   2548:     current.radiovalue = newvalue;
                   2549:     currentform.login[i].checked = true;
                   2550:     return;
                   2551: }
                   2552: END
                   2553:     return $result;
                   2554: }
                   2555: 
1.1075.2.20  raeburn  2556: sub authform_authorwarning {
1.32      matthew  2557:     my $result='';
1.144     matthew  2558:     $result='<i>'.
                   2559:         &mt('As a general rule, only authors or co-authors should be '.
                   2560:             'filesystem authenticated '.
                   2561:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2562:     return $result;
                   2563: }
                   2564: 
1.1075.2.20  raeburn  2565: sub authform_nochange {
1.32      matthew  2566:     my %in = (
                   2567:               formname => 'document.cu',
                   2568:               kerb_def_dom => 'MSU.EDU',
                   2569:               @_,
                   2570:           );
1.1075.2.20  raeburn  2571:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2572:     my $result;
1.1075.2.20  raeburn  2573:     if (!$authnum) {
                   2574:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2575:     } else {
                   2576:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2577:                   '<input type="radio" name="login" value="nochange" '.
                   2578:                   'checked="checked" onclick="'.
1.281     albertel 2579:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2580: 	    '</label>';
1.586     raeburn  2581:     }
1.32      matthew  2582:     return $result;
                   2583: }
                   2584: 
1.591     raeburn  2585: sub authform_kerberos {
1.32      matthew  2586:     my %in = (
                   2587:               formname => 'document.cu',
                   2588:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2589:               kerb_def_auth => 'krb4',
1.32      matthew  2590:               @_,
                   2591:               );
1.586     raeburn  2592:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2593:         $autharg,$jscall);
1.1075.2.20  raeburn  2594:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2595:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2596:        $check5 = ' checked="checked"';
1.80      albertel 2597:     } else {
1.772     bisitz   2598:        $check4 = ' checked="checked"';
1.80      albertel 2599:     }
1.165     raeburn  2600:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2601:     if (defined($in{'curr_authtype'})) {
                   2602:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2603:             $krbcheck = ' checked="checked"';
1.623     raeburn  2604:             if (defined($in{'mode'})) {
                   2605:                 if ($in{'mode'} eq 'modifyuser') {
                   2606:                     $krbcheck = '';
                   2607:                 }
                   2608:             }
1.591     raeburn  2609:             if (defined($in{'curr_kerb_ver'})) {
                   2610:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2611:                     $check5 = ' checked="checked"';
1.591     raeburn  2612:                     $check4 = '';
                   2613:                 } else {
1.772     bisitz   2614:                     $check4 = ' checked="checked"';
1.591     raeburn  2615:                     $check5 = '';
                   2616:                 }
1.586     raeburn  2617:             }
1.591     raeburn  2618:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2619:                 $krbarg = $in{'curr_autharg'};
                   2620:             }
1.586     raeburn  2621:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2622:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2623:                     $result = 
                   2624:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2625:         $in{'curr_autharg'},$krbver);
                   2626:                 } else {
                   2627:                     $result =
                   2628:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2629:                 }
                   2630:                 return $result; 
                   2631:             }
                   2632:         }
                   2633:     } else {
                   2634:         if ($authnum == 1) {
1.784     bisitz   2635:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2636:         }
                   2637:     }
1.586     raeburn  2638:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2639:         return;
1.587     raeburn  2640:     } elsif ($authtype eq '') {
1.591     raeburn  2641:         if (defined($in{'mode'})) {
1.587     raeburn  2642:             if ($in{'mode'} eq 'modifycourse') {
                   2643:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2644:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2645:                 }
                   2646:             }
                   2647:         }
1.586     raeburn  2648:     }
                   2649:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2650:     if ($authtype eq '') {
                   2651:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2652:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2653:                     $krbcheck.' />';
                   2654:     }
                   2655:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2656:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2657:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2658:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2659:          $in{'curr_authtype'} eq 'krb4')) {
                   2660:         $result .= &mt
1.144     matthew  2661:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2662:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2663:          '<label>'.$authtype,
1.281     albertel 2664:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2665:              'value="'.$krbarg.'" '.
1.144     matthew  2666:              'onchange="'.$jscall.'" />',
1.281     albertel 2667:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2668:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2669: 	 '</label>');
1.586     raeburn  2670:     } elsif ($can_assign{'krb4'}) {
                   2671:         $result .= &mt
                   2672:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2673:          '[_3] Version 4 [_4]',
                   2674:          '<label>'.$authtype,
                   2675:          '</label><input type="text" size="10" name="krbarg" '.
                   2676:              'value="'.$krbarg.'" '.
                   2677:              'onchange="'.$jscall.'" />',
                   2678:          '<label><input type="hidden" name="krbver" value="4" />',
                   2679:          '</label>');
                   2680:     } elsif ($can_assign{'krb5'}) {
                   2681:         $result .= &mt
                   2682:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2683:          '[_3] Version 5 [_4]',
                   2684:          '<label>'.$authtype,
                   2685:          '</label><input type="text" size="10" name="krbarg" '.
                   2686:              'value="'.$krbarg.'" '.
                   2687:              'onchange="'.$jscall.'" />',
                   2688:          '<label><input type="hidden" name="krbver" value="5" />',
                   2689:          '</label>');
                   2690:     }
1.32      matthew  2691:     return $result;
                   2692: }
                   2693: 
1.1075.2.20  raeburn  2694: sub authform_internal {
1.586     raeburn  2695:     my %in = (
1.32      matthew  2696:                 formname => 'document.cu',
                   2697:                 kerb_def_dom => 'MSU.EDU',
                   2698:                 @_,
                   2699:                 );
1.586     raeburn  2700:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2701:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2702:     if (defined($in{'curr_authtype'})) {
                   2703:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2704:             if ($can_assign{'int'}) {
1.772     bisitz   2705:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2706:                 if (defined($in{'mode'})) {
                   2707:                     if ($in{'mode'} eq 'modifyuser') {
                   2708:                         $intcheck = '';
                   2709:                     }
                   2710:                 }
1.591     raeburn  2711:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2712:                     $intarg = $in{'curr_autharg'};
                   2713:                 }
                   2714:             } else {
                   2715:                 $result = &mt('Currently internally authenticated.');
                   2716:                 return $result;
1.165     raeburn  2717:             }
                   2718:         }
1.586     raeburn  2719:     } else {
                   2720:         if ($authnum == 1) {
1.784     bisitz   2721:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2722:         }
                   2723:     }
                   2724:     if (!$can_assign{'int'}) {
                   2725:         return;
1.587     raeburn  2726:     } elsif ($authtype eq '') {
1.591     raeburn  2727:         if (defined($in{'mode'})) {
1.587     raeburn  2728:             if ($in{'mode'} eq 'modifycourse') {
                   2729:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2730:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2731:                 }
                   2732:             }
                   2733:         }
1.165     raeburn  2734:     }
1.586     raeburn  2735:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2736:     if ($authtype eq '') {
                   2737:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2738:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2739:     }
1.605     bisitz   2740:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2741:                $intarg.'" onchange="'.$jscall.'" />';
                   2742:     $result = &mt
1.144     matthew  2743:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2744:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2745:     $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  2746:     return $result;
                   2747: }
                   2748: 
1.1075.2.20  raeburn  2749: sub authform_local {
1.32      matthew  2750:     my %in = (
                   2751:               formname => 'document.cu',
                   2752:               kerb_def_dom => 'MSU.EDU',
                   2753:               @_,
                   2754:               );
1.586     raeburn  2755:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2756:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2757:     if (defined($in{'curr_authtype'})) {
                   2758:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2759:             if ($can_assign{'loc'}) {
1.772     bisitz   2760:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2761:                 if (defined($in{'mode'})) {
                   2762:                     if ($in{'mode'} eq 'modifyuser') {
                   2763:                         $loccheck = '';
                   2764:                     }
                   2765:                 }
1.591     raeburn  2766:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2767:                     $locarg = $in{'curr_autharg'};
                   2768:                 }
                   2769:             } else {
                   2770:                 $result = &mt('Currently using local (institutional) authentication.');
                   2771:                 return $result;
1.165     raeburn  2772:             }
                   2773:         }
1.586     raeburn  2774:     } else {
                   2775:         if ($authnum == 1) {
1.784     bisitz   2776:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2777:         }
                   2778:     }
                   2779:     if (!$can_assign{'loc'}) {
                   2780:         return;
1.587     raeburn  2781:     } elsif ($authtype eq '') {
1.591     raeburn  2782:         if (defined($in{'mode'})) {
1.587     raeburn  2783:             if ($in{'mode'} eq 'modifycourse') {
                   2784:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2785:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2786:                 }
                   2787:             }
                   2788:         }
1.165     raeburn  2789:     }
1.586     raeburn  2790:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2791:     if ($authtype eq '') {
                   2792:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2793:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2794:                     $jscall.'" />';
                   2795:     }
                   2796:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2797:                $locarg.'" onchange="'.$jscall.'" />';
                   2798:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2799:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2800:     return $result;
                   2801: }
                   2802: 
1.1075.2.20  raeburn  2803: sub authform_filesystem {
1.32      matthew  2804:     my %in = (
                   2805:               formname => 'document.cu',
                   2806:               kerb_def_dom => 'MSU.EDU',
                   2807:               @_,
                   2808:               );
1.586     raeburn  2809:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2810:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2811:     if (defined($in{'curr_authtype'})) {
                   2812:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2813:             if ($can_assign{'fsys'}) {
1.772     bisitz   2814:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2815:                 if (defined($in{'mode'})) {
                   2816:                     if ($in{'mode'} eq 'modifyuser') {
                   2817:                         $fsyscheck = '';
                   2818:                     }
                   2819:                 }
1.586     raeburn  2820:             } else {
                   2821:                 $result = &mt('Currently Filesystem Authenticated.');
                   2822:                 return $result;
                   2823:             }           
                   2824:         }
                   2825:     } else {
                   2826:         if ($authnum == 1) {
1.784     bisitz   2827:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2828:         }
                   2829:     }
                   2830:     if (!$can_assign{'fsys'}) {
                   2831:         return;
1.587     raeburn  2832:     } elsif ($authtype eq '') {
1.591     raeburn  2833:         if (defined($in{'mode'})) {
1.587     raeburn  2834:             if ($in{'mode'} eq 'modifycourse') {
                   2835:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2836:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2837:                 }
                   2838:             }
                   2839:         }
1.586     raeburn  2840:     }
                   2841:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2842:     if ($authtype eq '') {
                   2843:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2844:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2845:                     $jscall.'" />';
                   2846:     }
                   2847:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2848:                ' onchange="'.$jscall.'" />';
                   2849:     $result = &mt
1.144     matthew  2850:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2851:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2852:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2853:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2854:                   'onchange="'.$jscall.'" />');
1.32      matthew  2855:     return $result;
                   2856: }
                   2857: 
1.586     raeburn  2858: sub get_assignable_auth {
                   2859:     my ($dom) = @_;
                   2860:     if ($dom eq '') {
                   2861:         $dom = $env{'request.role.domain'};
                   2862:     }
                   2863:     my %can_assign = (
                   2864:                           krb4 => 1,
                   2865:                           krb5 => 1,
                   2866:                           int  => 1,
                   2867:                           loc  => 1,
                   2868:                      );
                   2869:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2870:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2871:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2872:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2873:             my $context;
                   2874:             if ($env{'request.role'} =~ /^au/) {
                   2875:                 $context = 'author';
                   2876:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2877:                 $context = 'domain';
                   2878:             } elsif ($env{'request.course.id'}) {
                   2879:                 $context = 'course';
                   2880:             }
                   2881:             if ($context) {
                   2882:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2883:                    %can_assign = %{$authhash->{$context}}; 
                   2884:                 }
                   2885:             }
                   2886:         }
                   2887:     }
                   2888:     my $authnum = 0;
                   2889:     foreach my $key (keys(%can_assign)) {
                   2890:         if ($can_assign{$key}) {
                   2891:             $authnum ++;
                   2892:         }
                   2893:     }
                   2894:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2895:         $authnum --;
                   2896:     }
                   2897:     return ($authnum,%can_assign);
                   2898: }
                   2899: 
1.80      albertel 2900: ###############################################################
                   2901: ##    Get Kerberos Defaults for Domain                 ##
                   2902: ###############################################################
                   2903: ##
                   2904: ## Returns default kerberos version and an associated argument
                   2905: ## as listed in file domain.tab. If not listed, provides
                   2906: ## appropriate default domain and kerberos version.
                   2907: ##
                   2908: #-------------------------------------------
                   2909: 
                   2910: =pod
                   2911: 
1.648     raeburn  2912: =item * &get_kerberos_defaults()
1.80      albertel 2913: 
                   2914: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2915: version and domain. If not found, it defaults to version 4 and the 
                   2916: domain of the server.
1.80      albertel 2917: 
1.648     raeburn  2918: =over 4
                   2919: 
1.80      albertel 2920: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2921: 
1.648     raeburn  2922: =back
                   2923: 
                   2924: =back
                   2925: 
1.80      albertel 2926: =cut
                   2927: 
                   2928: #-------------------------------------------
                   2929: sub get_kerberos_defaults {
                   2930:     my $domain=shift;
1.641     raeburn  2931:     my ($krbdef,$krbdefdom);
                   2932:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2933:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2934:         $krbdef = $domdefaults{'auth_def'};
                   2935:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2936:     } else {
1.80      albertel 2937:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2938:         my $krbdefdom=$1;
                   2939:         $krbdefdom=~tr/a-z/A-Z/;
                   2940:         $krbdef = "krb4";
                   2941:     }
                   2942:     return ($krbdef,$krbdefdom);
                   2943: }
1.112     bowersj2 2944: 
1.32      matthew  2945: 
1.46      matthew  2946: ###############################################################
                   2947: ##                Thesaurus Functions                        ##
                   2948: ###############################################################
1.20      www      2949: 
1.46      matthew  2950: =pod
1.20      www      2951: 
1.112     bowersj2 2952: =head1 Thesaurus Functions
                   2953: 
                   2954: =over 4
                   2955: 
1.648     raeburn  2956: =item * &initialize_keywords()
1.46      matthew  2957: 
                   2958: Initializes the package variable %Keywords if it is empty.  Uses the
                   2959: package variable $thesaurus_db_file.
                   2960: 
                   2961: =cut
                   2962: 
                   2963: ###################################################
                   2964: 
                   2965: sub initialize_keywords {
                   2966:     return 1 if (scalar keys(%Keywords));
                   2967:     # If we are here, %Keywords is empty, so fill it up
                   2968:     #   Make sure the file we need exists...
                   2969:     if (! -e $thesaurus_db_file) {
                   2970:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2971:                                  " failed because it does not exist");
                   2972:         return 0;
                   2973:     }
                   2974:     #   Set up the hash as a database
                   2975:     my %thesaurus_db;
                   2976:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2977:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2978:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2979:                                  $thesaurus_db_file);
                   2980:         return 0;
                   2981:     } 
                   2982:     #  Get the average number of appearances of a word.
                   2983:     my $avecount = $thesaurus_db{'average.count'};
                   2984:     #  Put keywords (those that appear > average) into %Keywords
                   2985:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2986:         my ($count,undef) = split /:/,$data;
                   2987:         $Keywords{$word}++ if ($count > $avecount);
                   2988:     }
                   2989:     untie %thesaurus_db;
                   2990:     # Remove special values from %Keywords.
1.356     albertel 2991:     foreach my $value ('total.count','average.count') {
                   2992:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2993:   }
1.46      matthew  2994:     return 1;
                   2995: }
                   2996: 
                   2997: ###################################################
                   2998: 
                   2999: =pod
                   3000: 
1.648     raeburn  3001: =item * &keyword($word)
1.46      matthew  3002: 
                   3003: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3004: than the average number of times in the thesaurus database.  Calls 
                   3005: &initialize_keywords
                   3006: 
                   3007: =cut
                   3008: 
                   3009: ###################################################
1.20      www      3010: 
                   3011: sub keyword {
1.46      matthew  3012:     return if (!&initialize_keywords());
                   3013:     my $word=lc(shift());
                   3014:     $word=~s/\W//g;
                   3015:     return exists($Keywords{$word});
1.20      www      3016: }
1.46      matthew  3017: 
                   3018: ###############################################################
                   3019: 
                   3020: =pod 
1.20      www      3021: 
1.648     raeburn  3022: =item * &get_related_words()
1.46      matthew  3023: 
1.160     matthew  3024: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3025: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3026: will be returned.  The order of the words returned is determined by the
                   3027: database which holds them.
                   3028: 
                   3029: Uses global $thesaurus_db_file.
                   3030: 
1.1057    foxr     3031: 
1.46      matthew  3032: =cut
                   3033: 
                   3034: ###############################################################
                   3035: sub get_related_words {
                   3036:     my $keyword = shift;
                   3037:     my %thesaurus_db;
                   3038:     if (! -e $thesaurus_db_file) {
                   3039:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3040:                                  "failed because the file does not exist");
                   3041:         return ();
                   3042:     }
                   3043:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3044:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3045:         return ();
                   3046:     } 
                   3047:     my @Words=();
1.429     www      3048:     my $count=0;
1.46      matthew  3049:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3050: 	# The first element is the number of times
                   3051: 	# the word appears.  We do not need it now.
1.429     www      3052: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3053: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3054: 	my $threshold=$mostfrequentcount/10;
                   3055:         foreach my $possibleword (@RelatedWords) {
                   3056:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3057:             if ($wordcount>$threshold) {
                   3058: 		push(@Words,$word);
                   3059:                 $count++;
                   3060:                 if ($count>10) { last; }
                   3061: 	    }
1.20      www      3062:         }
                   3063:     }
1.46      matthew  3064:     untie %thesaurus_db;
                   3065:     return @Words;
1.14      harris41 3066: }
1.46      matthew  3067: 
1.112     bowersj2 3068: =pod
                   3069: 
                   3070: =back
                   3071: 
                   3072: =cut
1.61      www      3073: 
                   3074: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3075: =pod
                   3076: 
1.112     bowersj2 3077: =head1 User Name Functions
                   3078: 
                   3079: =over 4
                   3080: 
1.648     raeburn  3081: =item * &plainname($uname,$udom,$first)
1.81      albertel 3082: 
1.112     bowersj2 3083: Takes a users logon name and returns it as a string in
1.226     albertel 3084: "first middle last generation" form 
                   3085: if $first is set to 'lastname' then it returns it as
                   3086: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3087: 
                   3088: =cut
1.61      www      3089: 
1.295     www      3090: 
1.81      albertel 3091: ###############################################################
1.61      www      3092: sub plainname {
1.226     albertel 3093:     my ($uname,$udom,$first)=@_;
1.537     albertel 3094:     return if (!defined($uname) || !defined($udom));
1.295     www      3095:     my %names=&getnames($uname,$udom);
1.226     albertel 3096:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3097: 					  $names{'middlename'},
                   3098: 					  $names{'lastname'},
                   3099: 					  $names{'generation'},$first);
                   3100:     $name=~s/^\s+//;
1.62      www      3101:     $name=~s/\s+$//;
                   3102:     $name=~s/\s+/ /g;
1.353     albertel 3103:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3104:     return $name;
1.61      www      3105: }
1.66      www      3106: 
                   3107: # -------------------------------------------------------------------- Nickname
1.81      albertel 3108: =pod
                   3109: 
1.648     raeburn  3110: =item * &nickname($uname,$udom)
1.81      albertel 3111: 
                   3112: Gets a users name and returns it as a string as
                   3113: 
                   3114: "&quot;nickname&quot;"
1.66      www      3115: 
1.81      albertel 3116: if the user has a nickname or
                   3117: 
                   3118: "first middle last generation"
                   3119: 
                   3120: if the user does not
                   3121: 
                   3122: =cut
1.66      www      3123: 
                   3124: sub nickname {
                   3125:     my ($uname,$udom)=@_;
1.537     albertel 3126:     return if (!defined($uname) || !defined($udom));
1.295     www      3127:     my %names=&getnames($uname,$udom);
1.68      albertel 3128:     my $name=$names{'nickname'};
1.66      www      3129:     if ($name) {
                   3130:        $name='&quot;'.$name.'&quot;'; 
                   3131:     } else {
                   3132:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3133: 	     $names{'lastname'}.' '.$names{'generation'};
                   3134:        $name=~s/\s+$//;
                   3135:        $name=~s/\s+/ /g;
                   3136:     }
                   3137:     return $name;
                   3138: }
                   3139: 
1.295     www      3140: sub getnames {
                   3141:     my ($uname,$udom)=@_;
1.537     albertel 3142:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3143:     if ($udom eq 'public' && $uname eq 'public') {
                   3144: 	return ('lastname' => &mt('Public'));
                   3145:     }
1.295     www      3146:     my $id=$uname.':'.$udom;
                   3147:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3148:     if ($cached) {
                   3149: 	return %{$names};
                   3150:     } else {
                   3151: 	my %loadnames=&Apache::lonnet::get('environment',
                   3152:                     ['firstname','middlename','lastname','generation','nickname'],
                   3153: 					 $udom,$uname);
                   3154: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3155: 	return %loadnames;
                   3156:     }
                   3157: }
1.61      www      3158: 
1.542     raeburn  3159: # -------------------------------------------------------------------- getemails
1.648     raeburn  3160: 
1.542     raeburn  3161: =pod
                   3162: 
1.648     raeburn  3163: =item * &getemails($uname,$udom)
1.542     raeburn  3164: 
                   3165: Gets a user's email information and returns it as a hash with keys:
                   3166: notification, critnotification, permanentemail
                   3167: 
                   3168: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3169: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3170:  
1.648     raeburn  3171: 
1.542     raeburn  3172: =cut
                   3173: 
1.648     raeburn  3174: 
1.466     albertel 3175: sub getemails {
                   3176:     my ($uname,$udom)=@_;
                   3177:     if ($udom eq 'public' && $uname eq 'public') {
                   3178: 	return;
                   3179:     }
1.467     www      3180:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3181:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3182:     my $id=$uname.':'.$udom;
                   3183:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3184:     if ($cached) {
                   3185: 	return %{$names};
                   3186:     } else {
                   3187: 	my %loadnames=&Apache::lonnet::get('environment',
                   3188:                     			   ['notification','critnotification',
                   3189: 					    'permanentemail'],
                   3190: 					   $udom,$uname);
                   3191: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3192: 	return %loadnames;
                   3193:     }
                   3194: }
                   3195: 
1.551     albertel 3196: sub flush_email_cache {
                   3197:     my ($uname,$udom)=@_;
                   3198:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3199:     if (!$uname) { $uname=$env{'user.name'};   }
                   3200:     return if ($udom eq 'public' && $uname eq 'public');
                   3201:     my $id=$uname.':'.$udom;
                   3202:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3203: }
                   3204: 
1.728     raeburn  3205: # -------------------------------------------------------------------- getlangs
                   3206: 
                   3207: =pod
                   3208: 
                   3209: =item * &getlangs($uname,$udom)
                   3210: 
                   3211: Gets a user's language preference and returns it as a hash with key:
                   3212: language.
                   3213: 
                   3214: =cut
                   3215: 
                   3216: 
                   3217: sub getlangs {
                   3218:     my ($uname,$udom) = @_;
                   3219:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3220:     if (!$uname) { $uname=$env{'user.name'};   }
                   3221:     my $id=$uname.':'.$udom;
                   3222:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3223:     if ($cached) {
                   3224:         return %{$langs};
                   3225:     } else {
                   3226:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3227:                                            $udom,$uname);
                   3228:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3229:         return %loadlangs;
                   3230:     }
                   3231: }
                   3232: 
                   3233: sub flush_langs_cache {
                   3234:     my ($uname,$udom)=@_;
                   3235:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3236:     if (!$uname) { $uname=$env{'user.name'};   }
                   3237:     return if ($udom eq 'public' && $uname eq 'public');
                   3238:     my $id=$uname.':'.$udom;
                   3239:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3240: }
                   3241: 
1.61      www      3242: # ------------------------------------------------------------------ Screenname
1.81      albertel 3243: 
                   3244: =pod
                   3245: 
1.648     raeburn  3246: =item * &screenname($uname,$udom)
1.81      albertel 3247: 
                   3248: Gets a users screenname and returns it as a string
                   3249: 
                   3250: =cut
1.61      www      3251: 
                   3252: sub screenname {
                   3253:     my ($uname,$udom)=@_;
1.258     albertel 3254:     if ($uname eq $env{'user.name'} &&
                   3255: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3256:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3257:     return $names{'screenname'};
1.62      www      3258: }
                   3259: 
1.212     albertel 3260: 
1.802     bisitz   3261: # ------------------------------------------------------------- Confirm Wrapper
                   3262: =pod
                   3263: 
1.1075.2.42  raeburn  3264: =item * &confirmwrapper($message)
1.802     bisitz   3265: 
                   3266: Wrap messages about completion of operation in box
                   3267: 
                   3268: =cut
                   3269: 
                   3270: sub confirmwrapper {
                   3271:     my ($message)=@_;
                   3272:     if ($message) {
                   3273:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3274:                .$message."\n"
                   3275:                .'</div>'."\n";
                   3276:     } else {
                   3277:         return $message;
                   3278:     }
                   3279: }
                   3280: 
1.62      www      3281: # ------------------------------------------------------------- Message Wrapper
                   3282: 
                   3283: sub messagewrapper {
1.369     www      3284:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3285:     return 
1.441     albertel 3286:         '<a href="/adm/email?compose=individual&amp;'.
                   3287:         'recname='.$username.'&amp;recdom='.$domain.
                   3288: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3289:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3290: }
1.802     bisitz   3291: 
1.74      www      3292: # --------------------------------------------------------------- Notes Wrapper
                   3293: 
                   3294: sub noteswrapper {
                   3295:     my ($link,$un,$do)=@_;
                   3296:     return 
1.896     amueller 3297: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3298: }
1.802     bisitz   3299: 
1.62      www      3300: # ------------------------------------------------------------- Aboutme Wrapper
                   3301: 
                   3302: sub aboutmewrapper {
1.1070    raeburn  3303:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3304:     if (!defined($username)  && !defined($domain)) {
                   3305:         return;
                   3306:     }
1.1075.2.15  raeburn  3307:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3308: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3309: }
                   3310: 
                   3311: # ------------------------------------------------------------ Syllabus Wrapper
                   3312: 
                   3313: sub syllabuswrapper {
1.707     bisitz   3314:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3315:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3316: }
1.14      harris41 3317: 
1.802     bisitz   3318: # -----------------------------------------------------------------------------
                   3319: 
1.208     matthew  3320: sub track_student_link {
1.887     raeburn  3321:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3322:     my $link ="/adm/trackstudent?";
1.208     matthew  3323:     my $title = 'View recent activity';
                   3324:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3325:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3326:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3327:         $title .= ' of this student';
1.268     albertel 3328:     } 
1.208     matthew  3329:     if (defined($target) && $target !~ /^\s*$/) {
                   3330:         $target = qq{target="$target"};
                   3331:     } else {
                   3332:         $target = '';
                   3333:     }
1.268     albertel 3334:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3335:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3336:     $title = &mt($title);
                   3337:     $linktext = &mt($linktext);
1.448     albertel 3338:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3339: 	&help_open_topic('View_recent_activity');
1.208     matthew  3340: }
                   3341: 
1.781     raeburn  3342: sub slot_reservations_link {
                   3343:     my ($linktext,$sname,$sdom,$target) = @_;
                   3344:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3345:     my $title = 'View slot reservation history';
                   3346:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3347:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3348:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3349:         $title .= ' of this student';
                   3350:     }
                   3351:     if (defined($target) && $target !~ /^\s*$/) {
                   3352:         $target = qq{target="$target"};
                   3353:     } else {
                   3354:         $target = '';
                   3355:     }
                   3356:     $title = &mt($title);
                   3357:     $linktext = &mt($linktext);
                   3358:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3359: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3360: 
                   3361: }
                   3362: 
1.508     www      3363: # ===================================================== Display a student photo
                   3364: 
                   3365: 
1.509     albertel 3366: sub student_image_tag {
1.508     www      3367:     my ($domain,$user)=@_;
                   3368:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3369:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3370: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3371:     } else {
                   3372: 	return '';
                   3373:     }
                   3374: }
                   3375: 
1.112     bowersj2 3376: =pod
                   3377: 
                   3378: =back
                   3379: 
                   3380: =head1 Access .tab File Data
                   3381: 
                   3382: =over 4
                   3383: 
1.648     raeburn  3384: =item * &languageids() 
1.112     bowersj2 3385: 
                   3386: returns list of all language ids
                   3387: 
                   3388: =cut
                   3389: 
1.14      harris41 3390: sub languageids {
1.16      harris41 3391:     return sort(keys(%language));
1.14      harris41 3392: }
                   3393: 
1.112     bowersj2 3394: =pod
                   3395: 
1.648     raeburn  3396: =item * &languagedescription() 
1.112     bowersj2 3397: 
                   3398: returns description of a specified language id
                   3399: 
                   3400: =cut
                   3401: 
1.14      harris41 3402: sub languagedescription {
1.125     www      3403:     my $code=shift;
                   3404:     return  ($supported_language{$code}?'* ':'').
                   3405:             $language{$code}.
1.126     www      3406: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3407: }
                   3408: 
1.1048    foxr     3409: =pod
                   3410: 
                   3411: =item * &plainlanguagedescription
                   3412: 
                   3413: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3414: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3415: 
                   3416: =cut
                   3417: 
1.145     www      3418: sub plainlanguagedescription {
                   3419:     my $code=shift;
                   3420:     return $language{$code};
                   3421: }
                   3422: 
1.1048    foxr     3423: =pod
                   3424: 
                   3425: =item * &supportedlanguagecode
                   3426: 
                   3427: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3428: code.
                   3429: 
                   3430: =cut
                   3431: 
1.145     www      3432: sub supportedlanguagecode {
                   3433:     my $code=shift;
                   3434:     return $supported_language{$code};
1.97      www      3435: }
                   3436: 
1.112     bowersj2 3437: =pod
                   3438: 
1.1048    foxr     3439: =item * &latexlanguage()
                   3440: 
                   3441: Given a language key code returns the correspondnig language to use
                   3442: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3443: is no supported hyphenation for the language code.
                   3444: 
                   3445: =cut
                   3446: 
                   3447: sub latexlanguage {
                   3448:     my $code = shift;
                   3449:     return $latex_language{$code};
                   3450: }
                   3451: 
                   3452: =pod
                   3453: 
                   3454: =item * &latexhyphenation()
                   3455: 
                   3456: Same as above but what's supplied is the language as it might be stored
                   3457: in the metadata.
                   3458: 
                   3459: =cut
                   3460: 
                   3461: sub latexhyphenation {
                   3462:     my $key = shift;
                   3463:     return $latex_language_bykey{$key};
                   3464: }
                   3465: 
                   3466: =pod
                   3467: 
1.648     raeburn  3468: =item * &copyrightids() 
1.112     bowersj2 3469: 
                   3470: returns list of all copyrights
                   3471: 
                   3472: =cut
                   3473: 
                   3474: sub copyrightids {
                   3475:     return sort(keys(%cprtag));
                   3476: }
                   3477: 
                   3478: =pod
                   3479: 
1.648     raeburn  3480: =item * &copyrightdescription() 
1.112     bowersj2 3481: 
                   3482: returns description of a specified copyright id
                   3483: 
                   3484: =cut
                   3485: 
                   3486: sub copyrightdescription {
1.166     www      3487:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3488: }
1.197     matthew  3489: 
                   3490: =pod
                   3491: 
1.648     raeburn  3492: =item * &source_copyrightids() 
1.192     taceyjo1 3493: 
                   3494: returns list of all source copyrights
                   3495: 
                   3496: =cut
                   3497: 
                   3498: sub source_copyrightids {
                   3499:     return sort(keys(%scprtag));
                   3500: }
                   3501: 
                   3502: =pod
                   3503: 
1.648     raeburn  3504: =item * &source_copyrightdescription() 
1.192     taceyjo1 3505: 
                   3506: returns description of a specified source copyright id
                   3507: 
                   3508: =cut
                   3509: 
                   3510: sub source_copyrightdescription {
                   3511:     return &mt($scprtag{shift(@_)});
                   3512: }
1.112     bowersj2 3513: 
                   3514: =pod
                   3515: 
1.648     raeburn  3516: =item * &filecategories() 
1.112     bowersj2 3517: 
                   3518: returns list of all file categories
                   3519: 
                   3520: =cut
                   3521: 
                   3522: sub filecategories {
                   3523:     return sort(keys(%category_extensions));
                   3524: }
                   3525: 
                   3526: =pod
                   3527: 
1.648     raeburn  3528: =item * &filecategorytypes() 
1.112     bowersj2 3529: 
                   3530: returns list of file types belonging to a given file
                   3531: category
                   3532: 
                   3533: =cut
                   3534: 
                   3535: sub filecategorytypes {
1.356     albertel 3536:     my ($cat) = @_;
                   3537:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3538: }
                   3539: 
                   3540: =pod
                   3541: 
1.648     raeburn  3542: =item * &fileembstyle() 
1.112     bowersj2 3543: 
                   3544: returns embedding style for a specified file type
                   3545: 
                   3546: =cut
                   3547: 
                   3548: sub fileembstyle {
                   3549:     return $fe{lc(shift(@_))};
1.169     www      3550: }
                   3551: 
1.351     www      3552: sub filemimetype {
                   3553:     return $fm{lc(shift(@_))};
                   3554: }
                   3555: 
1.169     www      3556: 
                   3557: sub filecategoryselect {
                   3558:     my ($name,$value)=@_;
1.189     matthew  3559:     return &select_form($value,$name,
1.970     raeburn  3560:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3561: }
                   3562: 
                   3563: =pod
                   3564: 
1.648     raeburn  3565: =item * &filedescription() 
1.112     bowersj2 3566: 
                   3567: returns description for a specified file type
                   3568: 
                   3569: =cut
                   3570: 
                   3571: sub filedescription {
1.188     matthew  3572:     my $file_description = $fd{lc(shift())};
                   3573:     $file_description =~ s:([\[\]]):~$1:g;
                   3574:     return &mt($file_description);
1.112     bowersj2 3575: }
                   3576: 
                   3577: =pod
                   3578: 
1.648     raeburn  3579: =item * &filedescriptionex() 
1.112     bowersj2 3580: 
                   3581: returns description for a specified file type with
                   3582: extra formatting
                   3583: 
                   3584: =cut
                   3585: 
                   3586: sub filedescriptionex {
                   3587:     my $ex=shift;
1.188     matthew  3588:     my $file_description = $fd{lc($ex)};
                   3589:     $file_description =~ s:([\[\]]):~$1:g;
                   3590:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3591: }
                   3592: 
                   3593: # End of .tab access
                   3594: =pod
                   3595: 
                   3596: =back
                   3597: 
                   3598: =cut
                   3599: 
                   3600: # ------------------------------------------------------------------ File Types
                   3601: sub fileextensions {
                   3602:     return sort(keys(%fe));
                   3603: }
                   3604: 
1.97      www      3605: # ----------------------------------------------------------- Display Languages
                   3606: # returns a hash with all desired display languages
                   3607: #
                   3608: 
                   3609: sub display_languages {
                   3610:     my %languages=();
1.695     raeburn  3611:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3612: 	$languages{$lang}=1;
1.97      www      3613:     }
                   3614:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3615:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3616: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3617: 	    $languages{$lang}=1;
1.97      www      3618:         }
                   3619:     }
                   3620:     return %languages;
1.14      harris41 3621: }
                   3622: 
1.582     albertel 3623: sub languages {
                   3624:     my ($possible_langs) = @_;
1.695     raeburn  3625:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3626:     if (!ref($possible_langs)) {
                   3627: 	if( wantarray ) {
                   3628: 	    return @preferred_langs;
                   3629: 	} else {
                   3630: 	    return $preferred_langs[0];
                   3631: 	}
                   3632:     }
                   3633:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3634:     my @preferred_possibilities;
                   3635:     foreach my $preferred_lang (@preferred_langs) {
                   3636: 	if (exists($possibilities{$preferred_lang})) {
                   3637: 	    push(@preferred_possibilities, $preferred_lang);
                   3638: 	}
                   3639:     }
                   3640:     if( wantarray ) {
                   3641: 	return @preferred_possibilities;
                   3642:     }
                   3643:     return $preferred_possibilities[0];
                   3644: }
                   3645: 
1.742     raeburn  3646: sub user_lang {
                   3647:     my ($touname,$toudom,$fromcid) = @_;
                   3648:     my @userlangs;
                   3649:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3650:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3651:                     $env{'course.'.$fromcid.'.languages'}));
                   3652:     } else {
                   3653:         my %langhash = &getlangs($touname,$toudom);
                   3654:         if ($langhash{'languages'} ne '') {
                   3655:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3656:         } else {
                   3657:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3658:             if ($domdefs{'lang_def'} ne '') {
                   3659:                 @userlangs = ($domdefs{'lang_def'});
                   3660:             }
                   3661:         }
                   3662:     }
                   3663:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3664:     my $user_lh = Apache::localize->get_handle(@languages);
                   3665:     return $user_lh;
                   3666: }
                   3667: 
                   3668: 
1.112     bowersj2 3669: ###############################################################
                   3670: ##               Student Answer Attempts                     ##
                   3671: ###############################################################
                   3672: 
                   3673: =pod
                   3674: 
                   3675: =head1 Alternate Problem Views
                   3676: 
                   3677: =over 4
                   3678: 
1.648     raeburn  3679: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3680:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3681: 
                   3682: Return string with previous attempt on problem. Arguments:
                   3683: 
                   3684: =over 4
                   3685: 
                   3686: =item * $symb: Problem, including path
                   3687: 
                   3688: =item * $username: username of the desired student
                   3689: 
                   3690: =item * $domain: domain of the desired student
1.14      harris41 3691: 
1.112     bowersj2 3692: =item * $course: Course ID
1.14      harris41 3693: 
1.112     bowersj2 3694: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3695:     something
1.14      harris41 3696: 
1.112     bowersj2 3697: =item * $regexp: if string matches this regexp, the string will be
                   3698:     sent to $gradesub
1.14      harris41 3699: 
1.112     bowersj2 3700: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3701: 
1.1075.2.86  raeburn  3702: =item * $usec: section of the desired student
                   3703: 
                   3704: =item * $identifier: counter for student (multiple students one problem) or
                   3705:     problem (one student; whole sequence).
                   3706: 
1.112     bowersj2 3707: =back
1.14      harris41 3708: 
1.112     bowersj2 3709: The output string is a table containing all desired attempts, if any.
1.16      harris41 3710: 
1.112     bowersj2 3711: =cut
1.1       albertel 3712: 
                   3713: sub get_previous_attempt {
1.1075.2.86  raeburn  3714:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3715:   my $prevattempts='';
1.43      ng       3716:   no strict 'refs';
1.1       albertel 3717:   if ($symb) {
1.3       albertel 3718:     my (%returnhash)=
                   3719:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3720:     if ($returnhash{'version'}) {
                   3721:       my %lasthash=();
                   3722:       my $version;
                   3723:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3724:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3725:             if ($key =~ /\.rawrndseed$/) {
                   3726:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   3727:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   3728:             } else {
                   3729:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   3730:             }
1.19      harris41 3731:         }
1.1       albertel 3732:       }
1.596     albertel 3733:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3734:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  3735:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  3736:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3737:       foreach my $key (sort(keys(%lasthash))) {
                   3738: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3739: 	if ($#parts > 0) {
1.31      albertel 3740: 	  my $data=$parts[-1];
1.989     raeburn  3741:           next if ($data eq 'foilorder');
1.31      albertel 3742: 	  pop(@parts);
1.1010    www      3743:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3744:           if ($data eq 'type') {
                   3745:               unless ($showsurv) {
                   3746:                   my $id = join(',',@parts);
                   3747:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3748:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3749:                       $lasthidden{$ign.'.'.$id} = 1;
                   3750:                   }
1.945     raeburn  3751:               }
1.1075.2.86  raeburn  3752:               if ($identifier ne '') {
                   3753:                   my $id = join(',',@parts);
                   3754:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   3755:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   3756:                       $hidestatus{$ign.'.'.$id} = 1;
                   3757:                   }
                   3758:               }
                   3759:           } elsif ($data eq 'regrader') {
                   3760:               if (($identifier ne '') && (@parts)) {
                   3761:                   my $id = join(',',@parts);
                   3762:                   $regraded{$ign.'.'.$id} = 1;
                   3763:               }
1.1010    www      3764:           } 
1.31      albertel 3765: 	} else {
1.41      ng       3766: 	  if ($#parts == 0) {
                   3767: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3768: 	  } else {
                   3769: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3770: 	  }
1.31      albertel 3771: 	}
1.16      harris41 3772:       }
1.596     albertel 3773:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3774:       if ($getattempt eq '') {
1.1075.2.86  raeburn  3775:         my (%solved,%resets,%probstatus);
                   3776:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   3777:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   3778:                 foreach my $id (keys(%regraded)) {
                   3779:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   3780:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   3781:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   3782:                         push(@{$resets{$id}},$version);
                   3783:                     }
                   3784:                 }
                   3785:             }
                   3786:         }
1.40      ng       3787: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  3788:             my (@hidden,@unsolved);
1.945     raeburn  3789:             if (%typeparts) {
                   3790:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  3791:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   3792:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  3793:                         push(@hidden,$id);
1.1075.2.86  raeburn  3794:                     } elsif ($identifier ne '') {
                   3795:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   3796:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   3797:                                 ($hidestatus{$id})) {
                   3798:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   3799:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   3800:                                 push(@{$solved{$id}},$version);
                   3801:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   3802:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   3803:                                 my $skip;
                   3804:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   3805:                                     foreach my $reset (@{$resets{$id}}) {
                   3806:                                         if ($reset > $solved{$id}[-1]) {
                   3807:                                             $skip=1;
                   3808:                                             last;
                   3809:                                         }
                   3810:                                     }
                   3811:                                 }
                   3812:                                 unless ($skip) {
                   3813:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   3814:                                     push(@unsolved,$partslist);
                   3815:                                 }
                   3816:                             }
                   3817:                         }
1.945     raeburn  3818:                     }
                   3819:                 }
                   3820:             }
                   3821:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  3822:                            '<td>'.&mt('Transaction [_1]',$version);
                   3823:             if (@unsolved) {
                   3824:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   3825:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   3826:                                  &mt('Hide').'</label></span>';
                   3827:             }
                   3828:             $prevattempts .= '</td>';
1.945     raeburn  3829:             if (@hidden) {
                   3830:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3831:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3832:                     my $hide;
                   3833:                     foreach my $id (@hidden) {
                   3834:                         if ($key =~ /^\Q$id\E/) {
                   3835:                             $hide = 1;
                   3836:                             last;
                   3837:                         }
                   3838:                     }
                   3839:                     if ($hide) {
                   3840:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3841:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3842:                             my $value = &format_previous_attempt_value($key,
                   3843:                                              $returnhash{$version.':'.$key});
                   3844:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3845:                         } else {
                   3846:                             $prevattempts.='<td>&nbsp;</td>';
                   3847:                         }
                   3848:                     } else {
                   3849:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  3850:                             my $value = $returnhash{$version.':'.$key};
                   3851:                             if ($key =~ /\.rndseed$/) {
                   3852:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   3853:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   3854:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   3855:                                 }
                   3856:                             }
                   3857:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   3858:                                            '&nbsp;</td>';
1.945     raeburn  3859:                         } else {
                   3860:                             $prevattempts.='<td>&nbsp;</td>';
                   3861:                         }
                   3862:                     }
                   3863:                 }
                   3864:             } else {
                   3865: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3866:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  3867:                     my $value = $returnhash{$version.':'.$key};
                   3868:                     if ($key =~ /\.rndseed$/) {
                   3869:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   3870:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   3871:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   3872:                         }
                   3873:                     }
                   3874:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   3875:                                    '&nbsp;</td>';
1.945     raeburn  3876: 	        }
                   3877:             }
                   3878: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3879: 	 }
1.1       albertel 3880:       }
1.945     raeburn  3881:       my @currhidden = keys(%lasthidden);
1.596     albertel 3882:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3883:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3884:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3885:           if (%typeparts) {
                   3886:               my $hidden;
                   3887:               foreach my $id (@currhidden) {
                   3888:                   if ($key =~ /^\Q$id\E/) {
                   3889:                       $hidden = 1;
                   3890:                       last;
                   3891:                   }
                   3892:               }
                   3893:               if ($hidden) {
                   3894:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3895:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3896:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3897:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3898:                           $value = &$gradesub($value);
                   3899:                       }
                   3900:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3901:                   } else {
                   3902:                       $prevattempts.='<td>&nbsp;</td>';
                   3903:                   }
                   3904:               } else {
                   3905:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3906:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3907:                       $value = &$gradesub($value);
                   3908:                   }
                   3909:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3910:               }
                   3911:           } else {
                   3912: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3913: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3914:                   $value = &$gradesub($value);
                   3915:               }
                   3916: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3917:           }
1.16      harris41 3918:       }
1.596     albertel 3919:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3920:     } else {
1.596     albertel 3921:       $prevattempts=
                   3922: 	  &start_data_table().&start_data_table_row().
                   3923: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3924: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3925:     }
                   3926:   } else {
1.596     albertel 3927:     $prevattempts=
                   3928: 	  &start_data_table().&start_data_table_row().
                   3929: 	  '<td>'.&mt('No data.').'</td>'.
                   3930: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3931:   }
1.10      albertel 3932: }
                   3933: 
1.581     albertel 3934: sub format_previous_attempt_value {
                   3935:     my ($key,$value) = @_;
1.1011    www      3936:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3937: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3938:     } elsif (ref($value) eq 'ARRAY') {
                   3939: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3940:     } elsif ($key =~ /answerstring$/) {
                   3941:         my %answers = &Apache::lonnet::str2hash($value);
                   3942:         my @anskeys = sort(keys(%answers));
                   3943:         if (@anskeys == 1) {
                   3944:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3945:             if ($answer =~ m{\0}) {
                   3946:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3947:             }
                   3948:             my $tag_internal_answer_name = 'INTERNAL';
                   3949:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3950:                 $value = $answer; 
                   3951:             } else {
                   3952:                 $value = $anskeys[0].'='.$answer;
                   3953:             }
                   3954:         } else {
                   3955:             foreach my $ans (@anskeys) {
                   3956:                 my $answer = $answers{$ans};
1.1001    raeburn  3957:                 if ($answer =~ m{\0}) {
                   3958:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3959:                 }
                   3960:                 $value .=  $ans.'='.$answer.'<br />';;
                   3961:             } 
                   3962:         }
1.581     albertel 3963:     } else {
                   3964: 	$value = &unescape($value);
                   3965:     }
                   3966:     return $value;
                   3967: }
                   3968: 
                   3969: 
1.107     albertel 3970: sub relative_to_absolute {
                   3971:     my ($url,$output)=@_;
                   3972:     my $parser=HTML::TokeParser->new(\$output);
                   3973:     my $token;
                   3974:     my $thisdir=$url;
                   3975:     my @rlinks=();
                   3976:     while ($token=$parser->get_token) {
                   3977: 	if ($token->[0] eq 'S') {
                   3978: 	    if ($token->[1] eq 'a') {
                   3979: 		if ($token->[2]->{'href'}) {
                   3980: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3981: 		}
                   3982: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3983: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3984: 	    } elsif ($token->[1] eq 'base') {
                   3985: 		$thisdir=$token->[2]->{'href'};
                   3986: 	    }
                   3987: 	}
                   3988:     }
                   3989:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3990:     foreach my $link (@rlinks) {
1.726     raeburn  3991: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3992: 		($link=~/^\//) ||
                   3993: 		($link=~/^javascript:/i) ||
                   3994: 		($link=~/^mailto:/i) ||
                   3995: 		($link=~/^\#/)) {
                   3996: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3997: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3998: 	}
                   3999:     }
                   4000: # -------------------------------------------------- Deal with Applet codebases
                   4001:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4002:     return $output;
                   4003: }
                   4004: 
1.112     bowersj2 4005: =pod
                   4006: 
1.648     raeburn  4007: =item * &get_student_view()
1.112     bowersj2 4008: 
                   4009: show a snapshot of what student was looking at
                   4010: 
                   4011: =cut
                   4012: 
1.10      albertel 4013: sub get_student_view {
1.186     albertel 4014:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4015:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4016:   my (%form);
1.10      albertel 4017:   my @elements=('symb','courseid','domain','username');
                   4018:   foreach my $element (@elements) {
1.186     albertel 4019:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4020:   }
1.186     albertel 4021:   if (defined($moreenv)) {
                   4022:       %form=(%form,%{$moreenv});
                   4023:   }
1.236     albertel 4024:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4025:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4026:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4027:   $userview=~s/\<body[^\>]*\>//gi;
                   4028:   $userview=~s/\<\/body\>//gi;
                   4029:   $userview=~s/\<html\>//gi;
                   4030:   $userview=~s/\<\/html\>//gi;
                   4031:   $userview=~s/\<head\>//gi;
                   4032:   $userview=~s/\<\/head\>//gi;
                   4033:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4034:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4035:   if (wantarray) {
                   4036:      return ($userview,$response);
                   4037:   } else {
                   4038:      return $userview;
                   4039:   }
                   4040: }
                   4041: 
                   4042: sub get_student_view_with_retries {
                   4043:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4044: 
                   4045:     my $ok = 0;                 # True if we got a good response.
                   4046:     my $content;
                   4047:     my $response;
                   4048: 
                   4049:     # Try to get the student_view done. within the retries count:
                   4050:     
                   4051:     do {
                   4052:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4053:          $ok      = $response->is_success;
                   4054:          if (!$ok) {
                   4055:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4056:          }
                   4057:          $retries--;
                   4058:     } while (!$ok && ($retries > 0));
                   4059:     
                   4060:     if (!$ok) {
                   4061:        $content = '';          # On error return an empty content.
                   4062:     }
1.651     www      4063:     if (wantarray) {
                   4064:        return ($content, $response);
                   4065:     } else {
                   4066:        return $content;
                   4067:     }
1.11      albertel 4068: }
                   4069: 
1.112     bowersj2 4070: =pod
                   4071: 
1.648     raeburn  4072: =item * &get_student_answers() 
1.112     bowersj2 4073: 
                   4074: show a snapshot of how student was answering problem
                   4075: 
                   4076: =cut
                   4077: 
1.11      albertel 4078: sub get_student_answers {
1.100     sakharuk 4079:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4080:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4081:   my (%moreenv);
1.11      albertel 4082:   my @elements=('symb','courseid','domain','username');
                   4083:   foreach my $element (@elements) {
1.186     albertel 4084:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4085:   }
1.186     albertel 4086:   $moreenv{'grade_target'}='answer';
                   4087:   %moreenv=(%form,%moreenv);
1.497     raeburn  4088:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4089:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4090:   return $userview;
1.1       albertel 4091: }
1.116     albertel 4092: 
                   4093: =pod
                   4094: 
                   4095: =item * &submlink()
                   4096: 
1.242     albertel 4097: Inputs: $text $uname $udom $symb $target
1.116     albertel 4098: 
                   4099: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4100: 
                   4101: =cut
                   4102: 
                   4103: ###############################################
                   4104: sub submlink {
1.242     albertel 4105:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4106:     if (!($uname && $udom)) {
                   4107: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4108: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4109: 	if (!$symb) { $symb=$cursymb; }
                   4110:     }
1.254     matthew  4111:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4112:     $symb=&escape($symb);
1.960     bisitz   4113:     if ($target) { $target=" target=\"$target\""; }
                   4114:     return
                   4115:         '<a href="/adm/grades?command=submission'.
                   4116:         '&amp;symb='.$symb.
                   4117:         '&amp;student='.$uname.
                   4118:         '&amp;userdom='.$udom.'"'.
                   4119:         $target.'>'.$text.'</a>';
1.242     albertel 4120: }
                   4121: ##############################################
                   4122: 
                   4123: =pod
                   4124: 
                   4125: =item * &pgrdlink()
                   4126: 
                   4127: Inputs: $text $uname $udom $symb $target
                   4128: 
                   4129: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4130: 
                   4131: =cut
                   4132: 
                   4133: ###############################################
                   4134: sub pgrdlink {
                   4135:     my $link=&submlink(@_);
                   4136:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4137:     return $link;
                   4138: }
                   4139: ##############################################
                   4140: 
                   4141: =pod
                   4142: 
                   4143: =item * &pprmlink()
                   4144: 
                   4145: Inputs: $text $uname $udom $symb $target
                   4146: 
                   4147: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4148: student and a specific resource
1.242     albertel 4149: 
                   4150: =cut
                   4151: 
                   4152: ###############################################
                   4153: sub pprmlink {
                   4154:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4155:     if (!($uname && $udom)) {
                   4156: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4157: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4158: 	if (!$symb) { $symb=$cursymb; }
                   4159:     }
1.254     matthew  4160:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4161:     $symb=&escape($symb);
1.242     albertel 4162:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4163:     return '<a href="/adm/parmset?command=set&amp;'.
                   4164: 	'symb='.$symb.'&amp;uname='.$uname.
                   4165: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4166: }
                   4167: ##############################################
1.37      matthew  4168: 
1.112     bowersj2 4169: =pod
                   4170: 
                   4171: =back
                   4172: 
                   4173: =cut
                   4174: 
1.37      matthew  4175: ###############################################
1.51      www      4176: 
                   4177: 
                   4178: sub timehash {
1.687     raeburn  4179:     my ($thistime) = @_;
                   4180:     my $timezone = &Apache::lonlocal::gettimezone();
                   4181:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4182:                      ->set_time_zone($timezone);
                   4183:     my $wday = $dt->day_of_week();
                   4184:     if ($wday == 7) { $wday = 0; }
                   4185:     return ( 'second' => $dt->second(),
                   4186:              'minute' => $dt->minute(),
                   4187:              'hour'   => $dt->hour(),
                   4188:              'day'     => $dt->day_of_month(),
                   4189:              'month'   => $dt->month(),
                   4190:              'year'    => $dt->year(),
                   4191:              'weekday' => $wday,
                   4192:              'dayyear' => $dt->day_of_year(),
                   4193:              'dlsav'   => $dt->is_dst() );
1.51      www      4194: }
                   4195: 
1.370     www      4196: sub utc_string {
                   4197:     my ($date)=@_;
1.371     www      4198:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4199: }
                   4200: 
1.51      www      4201: sub maketime {
                   4202:     my %th=@_;
1.687     raeburn  4203:     my ($epoch_time,$timezone,$dt);
                   4204:     $timezone = &Apache::lonlocal::gettimezone();
                   4205:     eval {
                   4206:         $dt = DateTime->new( year   => $th{'year'},
                   4207:                              month  => $th{'month'},
                   4208:                              day    => $th{'day'},
                   4209:                              hour   => $th{'hour'},
                   4210:                              minute => $th{'minute'},
                   4211:                              second => $th{'second'},
                   4212:                              time_zone => $timezone,
                   4213:                          );
                   4214:     };
                   4215:     if (!$@) {
                   4216:         $epoch_time = $dt->epoch;
                   4217:         if ($epoch_time) {
                   4218:             return $epoch_time;
                   4219:         }
                   4220:     }
1.51      www      4221:     return POSIX::mktime(
                   4222:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4223:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4224: }
                   4225: 
                   4226: #########################################
1.51      www      4227: 
                   4228: sub findallcourses {
1.482     raeburn  4229:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4230:     my %roles;
                   4231:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4232:     my %courses;
1.51      www      4233:     my $now=time;
1.482     raeburn  4234:     if (!defined($uname)) {
                   4235:         $uname = $env{'user.name'};
                   4236:     }
                   4237:     if (!defined($udom)) {
                   4238:         $udom = $env{'user.domain'};
                   4239:     }
                   4240:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4241:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4242:         if (!%roles) {
                   4243:             %roles = (
                   4244:                        cc => 1,
1.907     raeburn  4245:                        co => 1,
1.482     raeburn  4246:                        in => 1,
                   4247:                        ep => 1,
                   4248:                        ta => 1,
                   4249:                        cr => 1,
                   4250:                        st => 1,
                   4251:              );
                   4252:         }
                   4253:         foreach my $entry (keys(%roleshash)) {
                   4254:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4255:             if ($trole =~ /^cr/) { 
                   4256:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4257:             } else {
                   4258:                 next if (!exists($roles{$trole}));
                   4259:             }
                   4260:             if ($tend) {
                   4261:                 next if ($tend < $now);
                   4262:             }
                   4263:             if ($tstart) {
                   4264:                 next if ($tstart > $now);
                   4265:             }
1.1058    raeburn  4266:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4267:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4268:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4269:             if ($secpart eq '') {
                   4270:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4271:                 $sec = 'none';
1.1058    raeburn  4272:                 $value .= $cnum.'/';
1.482     raeburn  4273:             } else {
                   4274:                 $cnum = $cnumpart;
                   4275:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4276:                 $value .= $cnum.'/'.$sec;
                   4277:             }
                   4278:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4279:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4280:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4281:                 }
                   4282:             } else {
                   4283:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4284:             }
1.482     raeburn  4285:         }
                   4286:     } else {
                   4287:         foreach my $key (keys(%env)) {
1.483     albertel 4288: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4289:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4290: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4291: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4292: 	        next if (%roles && !exists($roles{$role}));
                   4293: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4294:                 my $active=1;
                   4295:                 if ($starttime) {
                   4296: 		    if ($now<$starttime) { $active=0; }
                   4297:                 }
                   4298:                 if ($endtime) {
                   4299:                     if ($now>$endtime) { $active=0; }
                   4300:                 }
                   4301:                 if ($active) {
1.1058    raeburn  4302:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4303:                     if ($sec eq '') {
                   4304:                         $sec = 'none';
1.1058    raeburn  4305:                     } else {
                   4306:                         $value .= $sec;
                   4307:                     }
                   4308:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4309:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4310:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4311:                         }
                   4312:                     } else {
                   4313:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4314:                     }
1.474     raeburn  4315:                 }
                   4316:             }
1.51      www      4317:         }
                   4318:     }
1.474     raeburn  4319:     return %courses;
1.51      www      4320: }
1.37      matthew  4321: 
1.54      www      4322: ###############################################
1.474     raeburn  4323: 
                   4324: sub blockcheck {
1.1075.2.73  raeburn  4325:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4326: 
1.1075.2.73  raeburn  4327:     if (defined($udom) && defined($uname)) {
                   4328:         # If uname and udom are for a course, check for blocks in the course.
                   4329:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4330:             my ($startblock,$endblock,$triggerblock) =
                   4331:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4332:             return ($startblock,$endblock,$triggerblock);
                   4333:         }
                   4334:     } else {
1.490     raeburn  4335:         $udom = $env{'user.domain'};
                   4336:         $uname = $env{'user.name'};
                   4337:     }
                   4338: 
1.502     raeburn  4339:     my $startblock = 0;
                   4340:     my $endblock = 0;
1.1062    raeburn  4341:     my $triggerblock = '';
1.482     raeburn  4342:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4343: 
1.490     raeburn  4344:     # If uname is for a user, and activity is course-specific, i.e.,
                   4345:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4346: 
1.490     raeburn  4347:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4348:          $activity eq 'groups' || $activity eq 'printout') &&
                   4349:         ($env{'request.course.id'})) {
1.490     raeburn  4350:         foreach my $key (keys(%live_courses)) {
                   4351:             if ($key ne $env{'request.course.id'}) {
                   4352:                 delete($live_courses{$key});
                   4353:             }
                   4354:         }
                   4355:     }
                   4356: 
                   4357:     my $otheruser = 0;
                   4358:     my %own_courses;
                   4359:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4360:         # Resource belongs to user other than current user.
                   4361:         $otheruser = 1;
                   4362:         # Gather courses for current user
                   4363:         %own_courses = 
                   4364:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4365:     }
                   4366: 
                   4367:     # Gather active course roles - course coordinator, instructor, 
                   4368:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4369: 
                   4370:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4371:         my ($cdom,$cnum);
                   4372:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4373:             $cdom = $env{'course.'.$course.'.domain'};
                   4374:             $cnum = $env{'course.'.$course.'.num'};
                   4375:         } else {
1.490     raeburn  4376:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4377:         }
                   4378:         my $no_ownblock = 0;
                   4379:         my $no_userblock = 0;
1.533     raeburn  4380:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4381:             # Check if current user has 'evb' priv for this
                   4382:             if (defined($own_courses{$course})) {
                   4383:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4384:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4385:                     if ($sec ne 'none') {
                   4386:                         $checkrole .= '/'.$sec;
                   4387:                     }
                   4388:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4389:                         $no_ownblock = 1;
                   4390:                         last;
                   4391:                     }
                   4392:                 }
                   4393:             }
                   4394:             # if they have 'evb' priv and are currently not playing student
                   4395:             next if (($no_ownblock) &&
                   4396:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4397:         }
1.474     raeburn  4398:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4399:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4400:             if ($sec ne 'none') {
1.482     raeburn  4401:                 $checkrole .= '/'.$sec;
1.474     raeburn  4402:             }
1.490     raeburn  4403:             if ($otheruser) {
                   4404:                 # Resource belongs to user other than current user.
                   4405:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4406:                 my (%allroles,%userroles);
                   4407:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4408:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4409:                         my ($trole,$tdom,$tnum,$tsec);
                   4410:                         if ($entry =~ /^cr/) {
                   4411:                             ($trole,$tdom,$tnum,$tsec) = 
                   4412:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4413:                         } else {
                   4414:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4415:                         }
                   4416:                         my ($spec,$area,$trest);
                   4417:                         $area = '/'.$tdom.'/'.$tnum;
                   4418:                         $trest = $tnum;
                   4419:                         if ($tsec ne '') {
                   4420:                             $area .= '/'.$tsec;
                   4421:                             $trest .= '/'.$tsec;
                   4422:                         }
                   4423:                         $spec = $trole.'.'.$area;
                   4424:                         if ($trole =~ /^cr/) {
                   4425:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4426:                                                               $tdom,$spec,$trest,$area);
                   4427:                         } else {
                   4428:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4429:                                                                 $tdom,$spec,$trest,$area);
                   4430:                         }
                   4431:                     }
                   4432:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4433:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4434:                         if ($1) {
                   4435:                             $no_userblock = 1;
                   4436:                             last;
                   4437:                         }
1.486     raeburn  4438:                     }
                   4439:                 }
1.490     raeburn  4440:             } else {
                   4441:                 # Resource belongs to current user
                   4442:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4443:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4444:                     $no_ownblock = 1;
                   4445:                     last;
                   4446:                 }
1.474     raeburn  4447:             }
                   4448:         }
                   4449:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4450:         next if (($no_ownblock) &&
1.491     albertel 4451:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4452:         next if ($no_userblock);
1.474     raeburn  4453: 
1.866     kalberla 4454:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4455:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4456:         
1.1062    raeburn  4457:         my ($start,$end,$trigger) = 
                   4458:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4459:         if (($start != 0) && 
                   4460:             (($startblock == 0) || ($startblock > $start))) {
                   4461:             $startblock = $start;
1.1062    raeburn  4462:             if ($trigger ne '') {
                   4463:                 $triggerblock = $trigger;
                   4464:             }
1.502     raeburn  4465:         }
                   4466:         if (($end != 0)  &&
                   4467:             (($endblock == 0) || ($endblock < $end))) {
                   4468:             $endblock = $end;
1.1062    raeburn  4469:             if ($trigger ne '') {
                   4470:                 $triggerblock = $trigger;
                   4471:             }
1.502     raeburn  4472:         }
1.490     raeburn  4473:     }
1.1062    raeburn  4474:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4475: }
                   4476: 
                   4477: sub get_blocks {
1.1062    raeburn  4478:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4479:     my $startblock = 0;
                   4480:     my $endblock = 0;
1.1062    raeburn  4481:     my $triggerblock = '';
1.490     raeburn  4482:     my $course = $cdom.'_'.$cnum;
                   4483:     $setters->{$course} = {};
                   4484:     $setters->{$course}{'staff'} = [];
                   4485:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4486:     $setters->{$course}{'triggers'} = [];
                   4487:     my (@blockers,%triggered);
                   4488:     my $now = time;
                   4489:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4490:     if ($activity eq 'docs') {
                   4491:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4492:         foreach my $block (@blockers) {
                   4493:             if ($block =~ /^firstaccess____(.+)$/) {
                   4494:                 my $item = $1;
                   4495:                 my $type = 'map';
                   4496:                 my $timersymb = $item;
                   4497:                 if ($item eq 'course') {
                   4498:                     $type = 'course';
                   4499:                 } elsif ($item =~ /___\d+___/) {
                   4500:                     $type = 'resource';
                   4501:                 } else {
                   4502:                     $timersymb = &Apache::lonnet::symbread($item);
                   4503:                 }
                   4504:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4505:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4506:                 $triggered{$block} = {
                   4507:                                        start => $start,
                   4508:                                        end   => $end,
                   4509:                                        type  => $type,
                   4510:                                      };
                   4511:             }
                   4512:         }
                   4513:     } else {
                   4514:         foreach my $block (keys(%commblocks)) {
                   4515:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4516:                 my ($start,$end) = ($1,$2);
                   4517:                 if ($start <= time && $end >= time) {
                   4518:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4519:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4520:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4521:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4522:                                     push(@blockers,$block);
                   4523:                                 }
                   4524:                             }
                   4525:                         }
                   4526:                     }
                   4527:                 }
                   4528:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4529:                 my $item = $1;
                   4530:                 my $timersymb = $item; 
                   4531:                 my $type = 'map';
                   4532:                 if ($item eq 'course') {
                   4533:                     $type = 'course';
                   4534:                 } elsif ($item =~ /___\d+___/) {
                   4535:                     $type = 'resource';
                   4536:                 } else {
                   4537:                     $timersymb = &Apache::lonnet::symbread($item);
                   4538:                 }
                   4539:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4540:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4541:                 if ($start && $end) {
                   4542:                     if (($start <= time) && ($end >= time)) {
                   4543:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4544:                             push(@blockers,$block);
                   4545:                             $triggered{$block} = {
                   4546:                                                    start => $start,
                   4547:                                                    end   => $end,
                   4548:                                                    type  => $type,
                   4549:                                                  };
                   4550:                         }
                   4551:                     }
1.490     raeburn  4552:                 }
1.1062    raeburn  4553:             }
                   4554:         }
                   4555:     }
                   4556:     foreach my $blocker (@blockers) {
                   4557:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4558:             &parse_block_record($commblocks{$blocker});
                   4559:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4560:         my ($start,$end,$triggertype);
                   4561:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4562:             ($start,$end) = ($1,$2);
                   4563:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4564:             $start = $triggered{$blocker}{'start'};
                   4565:             $end = $triggered{$blocker}{'end'};
                   4566:             $triggertype = $triggered{$blocker}{'type'};
                   4567:         }
                   4568:         if ($start) {
                   4569:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4570:             if ($triggertype) {
                   4571:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4572:             } else {
                   4573:                 push(@{$$setters{$course}{'triggers'}},0);
                   4574:             }
                   4575:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4576:                 $startblock = $start;
                   4577:                 if ($triggertype) {
                   4578:                     $triggerblock = $blocker;
1.474     raeburn  4579:                 }
                   4580:             }
1.1062    raeburn  4581:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4582:                $endblock = $end;
                   4583:                if ($triggertype) {
                   4584:                    $triggerblock = $blocker;
                   4585:                }
                   4586:             }
1.474     raeburn  4587:         }
                   4588:     }
1.1062    raeburn  4589:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4590: }
                   4591: 
                   4592: sub parse_block_record {
                   4593:     my ($record) = @_;
                   4594:     my ($setuname,$setudom,$title,$blocks);
                   4595:     if (ref($record) eq 'HASH') {
                   4596:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4597:         $title = &unescape($record->{'event'});
                   4598:         $blocks = $record->{'blocks'};
                   4599:     } else {
                   4600:         my @data = split(/:/,$record,3);
                   4601:         if (scalar(@data) eq 2) {
                   4602:             $title = $data[1];
                   4603:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4604:         } else {
                   4605:             ($setuname,$setudom,$title) = @data;
                   4606:         }
                   4607:         $blocks = { 'com' => 'on' };
                   4608:     }
                   4609:     return ($setuname,$setudom,$title,$blocks);
                   4610: }
                   4611: 
1.854     kalberla 4612: sub blocking_status {
1.1075.2.73  raeburn  4613:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4614:     my %setters;
1.890     droeschl 4615: 
1.1061    raeburn  4616: # check for active blocking
1.1062    raeburn  4617:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4618:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4619:     my $blocked = 0;
                   4620:     if ($startblock && $endblock) {
                   4621:         $blocked = 1;
                   4622:     }
1.890     droeschl 4623: 
1.1061    raeburn  4624: # caller just wants to know whether a block is active
                   4625:     if (!wantarray) { return $blocked; }
                   4626: 
                   4627: # build a link to a popup window containing the details
                   4628:     my $querystring  = "?activity=$activity";
                   4629: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4630:     if ($activity eq 'port') {
                   4631:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4632:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4633:     } elsif ($activity eq 'docs') {
                   4634:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4635:     }
1.1061    raeburn  4636: 
                   4637:     my $output .= <<'END_MYBLOCK';
                   4638: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4639:     var options = "width=" + w + ",height=" + h + ",";
                   4640:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4641:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4642:     var newWin = window.open(url, wdwName, options);
                   4643:     newWin.focus();
                   4644: }
1.890     droeschl 4645: END_MYBLOCK
1.854     kalberla 4646: 
1.1061    raeburn  4647:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4648:   
1.1061    raeburn  4649:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4650:     my $text = &mt('Communication Blocked');
                   4651:     if ($activity eq 'docs') {
                   4652:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4653:     } elsif ($activity eq 'printout') {
                   4654:         $text = &mt('Printing Blocked');
1.1062    raeburn  4655:     }
1.1061    raeburn  4656:     $output .= <<"END_BLOCK";
1.867     kalberla 4657: <div class='LC_comblock'>
1.869     kalberla 4658:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4659:   title='$text'>
                   4660:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4661:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4662:   title='$text'>$text</a>
1.867     kalberla 4663: </div>
                   4664: 
                   4665: END_BLOCK
1.474     raeburn  4666: 
1.1061    raeburn  4667:     return ($blocked, $output);
1.854     kalberla 4668: }
1.490     raeburn  4669: 
1.60      matthew  4670: ###############################################
                   4671: 
1.682     raeburn  4672: sub check_ip_acc {
                   4673:     my ($acc)=@_;
                   4674:     &Apache::lonxml::debug("acc is $acc");
                   4675:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4676:         return 1;
                   4677:     }
                   4678:     my $allowed=0;
                   4679:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4680: 
                   4681:     my $name;
                   4682:     foreach my $pattern (split(',',$acc)) {
                   4683:         $pattern =~ s/^\s*//;
                   4684:         $pattern =~ s/\s*$//;
                   4685:         if ($pattern =~ /\*$/) {
                   4686:             #35.8.*
                   4687:             $pattern=~s/\*//;
                   4688:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4689:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4690:             #35.8.3.[34-56]
                   4691:             my $low=$2;
                   4692:             my $high=$3;
                   4693:             $pattern=$1;
                   4694:             if ($ip =~ /^\Q$pattern\E/) {
                   4695:                 my $last=(split(/\./,$ip))[3];
                   4696:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4697:             }
                   4698:         } elsif ($pattern =~ /^\*/) {
                   4699:             #*.msu.edu
                   4700:             $pattern=~s/\*//;
                   4701:             if (!defined($name)) {
                   4702:                 use Socket;
                   4703:                 my $netaddr=inet_aton($ip);
                   4704:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4705:             }
                   4706:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4707:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4708:             #127.0.0.1
                   4709:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4710:         } else {
                   4711:             #some.name.com
                   4712:             if (!defined($name)) {
                   4713:                 use Socket;
                   4714:                 my $netaddr=inet_aton($ip);
                   4715:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4716:             }
                   4717:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4718:         }
                   4719:         if ($allowed) { last; }
                   4720:     }
                   4721:     return $allowed;
                   4722: }
                   4723: 
                   4724: ###############################################
                   4725: 
1.60      matthew  4726: =pod
                   4727: 
1.112     bowersj2 4728: =head1 Domain Template Functions
                   4729: 
                   4730: =over 4
                   4731: 
                   4732: =item * &determinedomain()
1.60      matthew  4733: 
                   4734: Inputs: $domain (usually will be undef)
                   4735: 
1.63      www      4736: Returns: Determines which domain should be used for designs
1.60      matthew  4737: 
                   4738: =cut
1.54      www      4739: 
1.60      matthew  4740: ###############################################
1.63      www      4741: sub determinedomain {
                   4742:     my $domain=shift;
1.531     albertel 4743:     if (! $domain) {
1.60      matthew  4744:         # Determine domain if we have not been given one
1.893     raeburn  4745:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4746:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4747:         if ($env{'request.role.domain'}) { 
                   4748:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4749:         }
                   4750:     }
1.63      www      4751:     return $domain;
                   4752: }
                   4753: ###############################################
1.517     raeburn  4754: 
1.518     albertel 4755: sub devalidate_domconfig_cache {
                   4756:     my ($udom)=@_;
                   4757:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4758: }
                   4759: 
                   4760: # ---------------------- Get domain configuration for a domain
                   4761: sub get_domainconf {
                   4762:     my ($udom) = @_;
                   4763:     my $cachetime=1800;
                   4764:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4765:     if (defined($cached)) { return %{$result}; }
                   4766: 
                   4767:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4768: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4769:     my (%designhash,%legacy);
1.518     albertel 4770:     if (keys(%domconfig) > 0) {
                   4771:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4772:             if (keys(%{$domconfig{'login'}})) {
                   4773:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4774:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  4775:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   4776:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   4777:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   4778:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   4779:                                         if ($key eq 'loginvia') {
                   4780:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4781:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4782:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   4783:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4784:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4785:                                                 } else {
                   4786:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   4787:                                                 }
1.948     raeburn  4788:                                             }
1.1075.2.87  raeburn  4789:                                         } elsif ($key eq 'headtag') {
                   4790:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   4791:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  4792:                                             }
1.946     raeburn  4793:                                         }
1.1075.2.87  raeburn  4794:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   4795:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   4796:                                         }
1.946     raeburn  4797:                                     }
                   4798:                                 }
                   4799:                             }
                   4800:                         } else {
                   4801:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4802:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4803:                                     $domconfig{'login'}{$key}{$img};
                   4804:                             }
1.699     raeburn  4805:                         }
                   4806:                     } else {
                   4807:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4808:                     }
1.632     raeburn  4809:                 }
                   4810:             } else {
                   4811:                 $legacy{'login'} = 1;
1.518     albertel 4812:             }
1.632     raeburn  4813:         } else {
                   4814:             $legacy{'login'} = 1;
1.518     albertel 4815:         }
                   4816:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4817:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4818:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4819:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4820:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4821:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4822:                         }
1.518     albertel 4823:                     }
                   4824:                 }
1.632     raeburn  4825:             } else {
                   4826:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4827:             }
1.632     raeburn  4828:         } else {
                   4829:             $legacy{'rolecolors'} = 1;
1.518     albertel 4830:         }
1.948     raeburn  4831:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4832:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4833:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4834:             }
                   4835:         }
1.632     raeburn  4836:         if (keys(%legacy) > 0) {
                   4837:             my %legacyhash = &get_legacy_domconf($udom);
                   4838:             foreach my $item (keys(%legacyhash)) {
                   4839:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4840:                     if ($legacy{'login'}) { 
                   4841:                         $designhash{$item} = $legacyhash{$item};
                   4842:                     }
                   4843:                 } else {
                   4844:                     if ($legacy{'rolecolors'}) {
                   4845:                         $designhash{$item} = $legacyhash{$item};
                   4846:                     }
1.518     albertel 4847:                 }
                   4848:             }
                   4849:         }
1.632     raeburn  4850:     } else {
                   4851:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4852:     }
                   4853:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4854: 				  $cachetime);
                   4855:     return %designhash;
                   4856: }
                   4857: 
1.632     raeburn  4858: sub get_legacy_domconf {
                   4859:     my ($udom) = @_;
                   4860:     my %legacyhash;
                   4861:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4862:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4863:     if (-e $designfile) {
                   4864:         if ( open (my $fh,"<$designfile") ) {
                   4865:             while (my $line = <$fh>) {
                   4866:                 next if ($line =~ /^\#/);
                   4867:                 chomp($line);
                   4868:                 my ($key,$val)=(split(/\=/,$line));
                   4869:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4870:             }
                   4871:             close($fh);
                   4872:         }
                   4873:     }
1.1026    raeburn  4874:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4875:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4876:     }
                   4877:     return %legacyhash;
                   4878: }
                   4879: 
1.63      www      4880: =pod
                   4881: 
1.112     bowersj2 4882: =item * &domainlogo()
1.63      www      4883: 
                   4884: Inputs: $domain (usually will be undef)
                   4885: 
                   4886: Returns: A link to a domain logo, if the domain logo exists.
                   4887: If the domain logo does not exist, a description of the domain.
                   4888: 
                   4889: =cut
1.112     bowersj2 4890: 
1.63      www      4891: ###############################################
                   4892: sub domainlogo {
1.517     raeburn  4893:     my $domain = &determinedomain(shift);
1.518     albertel 4894:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4895:     # See if there is a logo
                   4896:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4897:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4898:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4899: 	    if ($imgsrc =~ m{^/res/}) {
                   4900: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4901: 		&Apache::lonnet::repcopy($local_name);
                   4902: 	    }
                   4903: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4904:         } 
                   4905:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4906:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4907:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4908:     } else {
1.60      matthew  4909:         return '';
1.59      www      4910:     }
                   4911: }
1.63      www      4912: ##############################################
                   4913: 
                   4914: =pod
                   4915: 
1.112     bowersj2 4916: =item * &designparm()
1.63      www      4917: 
                   4918: Inputs: $which parameter; $domain (usually will be undef)
                   4919: 
                   4920: Returns: value of designparamter $which
                   4921: 
                   4922: =cut
1.112     bowersj2 4923: 
1.397     albertel 4924: 
1.400     albertel 4925: ##############################################
1.397     albertel 4926: sub designparm {
                   4927:     my ($which,$domain)=@_;
                   4928:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4929:         return $env{'environment.color.'.$which};
1.96      www      4930:     }
1.63      www      4931:     $domain=&determinedomain($domain);
1.1016    raeburn  4932:     my %domdesign;
                   4933:     unless ($domain eq 'public') {
                   4934:         %domdesign = &get_domainconf($domain);
                   4935:     }
1.520     raeburn  4936:     my $output;
1.517     raeburn  4937:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4938:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4939:     } else {
1.520     raeburn  4940:         $output = $defaultdesign{$which};
                   4941:     }
                   4942:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4943:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4944:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4945:             if ($output =~ m{^/res/}) {
                   4946:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4947:                 &Apache::lonnet::repcopy($local_name);
                   4948:             }
1.520     raeburn  4949:             $output = &lonhttpdurl($output);
                   4950:         }
1.63      www      4951:     }
1.520     raeburn  4952:     return $output;
1.63      www      4953: }
1.59      www      4954: 
1.822     bisitz   4955: ##############################################
                   4956: =pod
                   4957: 
1.832     bisitz   4958: =item * &authorspace()
                   4959: 
1.1028    raeburn  4960: Inputs: $url (usually will be undef).
1.832     bisitz   4961: 
1.1075.2.40  raeburn  4962: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  4963:          directory being viewed (or for which action is being taken). 
                   4964:          If $url is provided, and begins /priv/<domain>/<uname>
                   4965:          the path will be that portion of the $context argument.
                   4966:          Otherwise the path will be for the author space of the current
                   4967:          user when the current role is author, or for that of the 
                   4968:          co-author/assistant co-author space when the current role 
                   4969:          is co-author or assistant co-author.
1.832     bisitz   4970: 
                   4971: =cut
                   4972: 
                   4973: sub authorspace {
1.1028    raeburn  4974:     my ($url) = @_;
                   4975:     if ($url ne '') {
                   4976:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4977:            return $1;
                   4978:         }
                   4979:     }
1.832     bisitz   4980:     my $caname = '';
1.1024    www      4981:     my $cadom = '';
1.1028    raeburn  4982:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4983:         ($cadom,$caname) =
1.832     bisitz   4984:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4985:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4986:         $caname = $env{'user.name'};
1.1024    www      4987:         $cadom = $env{'user.domain'};
1.832     bisitz   4988:     }
1.1028    raeburn  4989:     if (($caname ne '') && ($cadom ne '')) {
                   4990:         return "/priv/$cadom/$caname/";
                   4991:     }
                   4992:     return;
1.832     bisitz   4993: }
                   4994: 
                   4995: ##############################################
                   4996: =pod
                   4997: 
1.822     bisitz   4998: =item * &head_subbox()
                   4999: 
                   5000: Inputs: $content (contains HTML code with page functions, etc.)
                   5001: 
                   5002: Returns: HTML div with $content
                   5003:          To be included in page header
                   5004: 
                   5005: =cut
                   5006: 
                   5007: sub head_subbox {
                   5008:     my ($content)=@_;
                   5009:     my $output =
1.993     raeburn  5010:         '<div class="LC_head_subbox">'
1.822     bisitz   5011:        .$content
                   5012:        .'</div>'
                   5013: }
                   5014: 
                   5015: ##############################################
                   5016: =pod
                   5017: 
                   5018: =item * &CSTR_pageheader()
                   5019: 
1.1026    raeburn  5020: Input: (optional) filename from which breadcrumb trail is built.
                   5021:        In most cases no input as needed, as $env{'request.filename'}
                   5022:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5023: 
                   5024: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5025:          To be included on Authoring Space pages
1.822     bisitz   5026: 
                   5027: =cut
                   5028: 
                   5029: sub CSTR_pageheader {
1.1026    raeburn  5030:     my ($trailfile) = @_;
                   5031:     if ($trailfile eq '') {
                   5032:         $trailfile = $env{'request.filename'};
                   5033:     }
                   5034: 
                   5035: # this is for resources; directories have customtitle, and crumbs
                   5036: # and select recent are created in lonpubdir.pm
                   5037: 
                   5038:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5039:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5040:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5041:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5042:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5043: 
                   5044:     my $parentpath = '';
                   5045:     my $lastitem = '';
                   5046:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5047:         $parentpath = $1;
                   5048:         $lastitem = $2;
                   5049:     } else {
                   5050:         $lastitem = $thisdisfn;
                   5051:     }
1.921     bisitz   5052: 
                   5053:     my $output =
1.822     bisitz   5054:          '<div>'
                   5055:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5056:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5057:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5058:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5059:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5060: 
                   5061:     if ($lastitem) {
                   5062:         $output .=
                   5063:              '<span class="LC_filename">'
                   5064:             .$lastitem
                   5065:             .'</span>';
                   5066:     }
                   5067:     $output .=
                   5068:          '<br />'
1.822     bisitz   5069:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5070:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5071:         .'</form>'
                   5072:         .&Apache::lonmenu::constspaceform()
                   5073:         .'</div>';
1.921     bisitz   5074: 
                   5075:     return $output;
1.822     bisitz   5076: }
                   5077: 
1.60      matthew  5078: ###############################################
                   5079: ###############################################
                   5080: 
                   5081: =pod
                   5082: 
1.112     bowersj2 5083: =back
                   5084: 
1.549     albertel 5085: =head1 HTML Helpers
1.112     bowersj2 5086: 
                   5087: =over 4
                   5088: 
                   5089: =item * &bodytag()
1.60      matthew  5090: 
                   5091: Returns a uniform header for LON-CAPA web pages.
                   5092: 
                   5093: Inputs: 
                   5094: 
1.112     bowersj2 5095: =over 4
                   5096: 
                   5097: =item * $title, A title to be displayed on the page.
                   5098: 
                   5099: =item * $function, the current role (can be undef).
                   5100: 
                   5101: =item * $addentries, extra parameters for the <body> tag.
                   5102: 
                   5103: =item * $bodyonly, if defined, only return the <body> tag.
                   5104: 
                   5105: =item * $domain, if defined, force a given domain.
                   5106: 
                   5107: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5108:             text interface only)
1.60      matthew  5109: 
1.814     bisitz   5110: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5111:                      navigational links
1.317     albertel 5112: 
1.338     albertel 5113: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5114: 
1.1075.2.12  raeburn  5115: =item * $no_inline_link, if true and in remote mode, don't show the
                   5116:          'Switch To Inline Menu' link
                   5117: 
1.460     albertel 5118: =item * $args, optional argument valid values are
                   5119:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5120:             inherit_jsmath -> when creating popup window in a page,
                   5121:                               should it have jsmath forced on by the
                   5122:                               current page
1.460     albertel 5123: 
1.1075.2.15  raeburn  5124: =item * $advtoolsref, optional argument, ref to an array containing
                   5125:             inlineremote items to be added in "Functions" menu below
                   5126:             breadcrumbs.
                   5127: 
1.112     bowersj2 5128: =back
                   5129: 
1.60      matthew  5130: Returns: A uniform header for LON-CAPA web pages.  
                   5131: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5132: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5133: other decorations will be returned.
                   5134: 
                   5135: =cut
                   5136: 
1.54      www      5137: sub bodytag {
1.831     bisitz   5138:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5139:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5140: 
1.954     raeburn  5141:     my $public;
                   5142:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5143:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5144:         $public = 1;
                   5145:     }
1.460     albertel 5146:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5147:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5148: 
1.183     matthew  5149:     $function = &get_users_function() if (!$function);
1.339     albertel 5150:     my $img =    &designparm($function.'.img',$domain);
                   5151:     my $font =   &designparm($function.'.font',$domain);
                   5152:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5153: 
1.803     bisitz   5154:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5155: 		   'bgcolor' => $pgbg,
1.339     albertel 5156: 		   'text'    => $font,
                   5157:                    'alink'   => &designparm($function.'.alink',$domain),
                   5158: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5159: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5160:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5161: 
1.63      www      5162:  # role and realm
1.1075.2.68  raeburn  5163:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5164:     if ($realm) {
                   5165:         $realm = '/'.$realm;
                   5166:     }
1.378     raeburn  5167:     if ($role  eq 'ca') {
1.479     albertel 5168:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5169:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5170:     } 
1.55      www      5171: # realm
1.258     albertel 5172:     if ($env{'request.course.id'}) {
1.378     raeburn  5173:         if ($env{'request.role'} !~ /^cr/) {
                   5174:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5175:         }
1.898     raeburn  5176:         if ($env{'request.course.sec'}) {
                   5177:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5178:         }   
1.359     albertel 5179: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5180:     } else {
                   5181:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5182:     }
1.433     albertel 5183: 
1.359     albertel 5184:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5185: 
1.438     albertel 5186:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5187: 
1.101     www      5188: # construct main body tag
1.359     albertel 5189:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5190: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5191: 
1.1075.2.38  raeburn  5192:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5193: 
                   5194:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5195:         return $bodytag;
1.1075.2.38  raeburn  5196:     }
1.359     albertel 5197: 
1.954     raeburn  5198:     if ($public) {
1.433     albertel 5199: 	undef($role);
                   5200:     }
1.359     albertel 5201:     
1.762     bisitz   5202:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5203:     #
                   5204:     # Extra info if you are the DC
                   5205:     my $dc_info = '';
                   5206:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5207:                         $env{'course.'.$env{'request.course.id'}.
                   5208:                                  '.domain'}.'/'})) {
                   5209:         my $cid = $env{'request.course.id'};
1.917     raeburn  5210:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5211:         $dc_info =~ s/\s+$//;
1.359     albertel 5212:     }
                   5213: 
1.898     raeburn  5214:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.903     droeschl 5215: 
1.1075.2.13  raeburn  5216:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5217: 
1.1075.2.38  raeburn  5218: 
                   5219: 
1.1075.2.21  raeburn  5220:     my $funclist;
                   5221:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5222:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5223:                     Apache::lonmenu::serverform();
                   5224:         my $forbodytag;
                   5225:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5226:                                             $forcereg,$args->{'group'},
                   5227:                                             $args->{'bread_crumbs'},
                   5228:                                             $advtoolsref,'',\$forbodytag);
                   5229:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5230:             $funclist = $forbodytag;
                   5231:         }
                   5232:     } else {
1.903     droeschl 5233: 
                   5234:         #    if ($env{'request.state'} eq 'construct') {
                   5235:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5236:         #    }
                   5237: 
1.1075.2.38  raeburn  5238:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5239:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5240: 
1.1075.2.38  raeburn  5241:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5242: 
1.916     droeschl 5243:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5244:             if ($dc_info) {
                   5245:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5246:             }
1.1075.2.38  raeburn  5247:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5248:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5249:             return $bodytag;
                   5250:         }
1.894     droeschl 5251: 
1.927     raeburn  5252:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5253:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5254:         }
1.916     droeschl 5255: 
1.1075.2.38  raeburn  5256:         $bodytag .= $right;
1.852     droeschl 5257: 
1.917     raeburn  5258:         if ($dc_info) {
                   5259:             $dc_info = &dc_courseid_toggle($dc_info);
                   5260:         }
                   5261:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5262: 
1.1075.2.61  raeburn  5263:         #if directed to not display the secondary menu, don't.
                   5264:         if ($args->{'no_secondary_menu'}) {
                   5265:             return $bodytag;
                   5266:         }
1.903     droeschl 5267:         #don't show menus for public users
1.954     raeburn  5268:         if (!$public){
1.1075.2.52  raeburn  5269:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5270:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5271:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5272:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5273:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5274:                                 $args->{'bread_crumbs'});
                   5275:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5276:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5277:                                                             $args->{'group'});
1.1075.2.15  raeburn  5278:             } else {
1.1075.2.21  raeburn  5279:                 my $forbodytag;
                   5280:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5281:                                                     $forcereg,$args->{'group'},
                   5282:                                                     $args->{'bread_crumbs'},
                   5283:                                                     $advtoolsref,'',\$forbodytag);
                   5284:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5285:                     $bodytag .= $forbodytag;
                   5286:                 }
1.920     raeburn  5287:             }
1.903     droeschl 5288:         }else{
                   5289:             # this is to seperate menu from content when there's no secondary
                   5290:             # menu. Especially needed for public accessible ressources.
                   5291:             $bodytag .= '<hr style="clear:both" />';
                   5292:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5293:         }
1.903     droeschl 5294: 
1.235     raeburn  5295:         return $bodytag;
1.1075.2.12  raeburn  5296:     }
                   5297: 
                   5298: #
                   5299: # Top frame rendering, Remote is up
                   5300: #
                   5301: 
                   5302:     my $imgsrc = $img;
                   5303:     if ($img =~ /^\/adm/) {
                   5304:         $imgsrc = &lonhttpdurl($img);
                   5305:     }
                   5306:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5307: 
1.1075.2.60  raeburn  5308:     my $help=($no_inline_link?''
                   5309:               :&Apache::loncommon::top_nav_help('Help'));
                   5310: 
1.1075.2.12  raeburn  5311:     # Explicit link to get inline menu
                   5312:     my $menu= ($no_inline_link?''
                   5313:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5314: 
                   5315:     if ($dc_info) {
                   5316:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5317:     }
                   5318: 
1.1075.2.38  raeburn  5319:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5320:     unless ($public) {
                   5321:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5322:                                 undef,'LC_menubuttons_link');
                   5323:     }
                   5324: 
1.1075.2.12  raeburn  5325:     unless ($env{'form.inhibitmenu'}) {
                   5326:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5327:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5328:                        <li>$help</li>
1.1075.2.12  raeburn  5329:                        <li>$menu</li>
                   5330:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5331:     }
1.1075.2.13  raeburn  5332:     if ($env{'request.state'} eq 'construct') {
                   5333:         if (!$public){
                   5334:             if ($env{'request.state'} eq 'construct') {
                   5335:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5336:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5337:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5338:                             &Apache::lonmenu::innerregister($forcereg,
                   5339:                                                             $args->{'bread_crumbs'});
                   5340:             }
                   5341:         }
                   5342:     }
1.1075.2.21  raeburn  5343:     return $bodytag."\n".$funclist;
1.182     matthew  5344: }
                   5345: 
1.917     raeburn  5346: sub dc_courseid_toggle {
                   5347:     my ($dc_info) = @_;
1.980     raeburn  5348:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5349:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5350:            &mt('(More ...)').'</a></span>'.
                   5351:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5352: }
                   5353: 
1.330     albertel 5354: sub make_attr_string {
                   5355:     my ($register,$attr_ref) = @_;
                   5356: 
                   5357:     if ($attr_ref && !ref($attr_ref)) {
                   5358: 	die("addentries Must be a hash ref ".
                   5359: 	    join(':',caller(1))." ".
                   5360: 	    join(':',caller(0))." ");
                   5361:     }
                   5362: 
                   5363:     if ($register) {
1.339     albertel 5364: 	my ($on_load,$on_unload);
                   5365: 	foreach my $key (keys(%{$attr_ref})) {
                   5366: 	    if      (lc($key) eq 'onload') {
                   5367: 		$on_load.=$attr_ref->{$key}.';';
                   5368: 		delete($attr_ref->{$key});
                   5369: 
                   5370: 	    } elsif (lc($key) eq 'onunload') {
                   5371: 		$on_unload.=$attr_ref->{$key}.';';
                   5372: 		delete($attr_ref->{$key});
                   5373: 	    }
                   5374: 	}
1.1075.2.12  raeburn  5375:         if ($env{'environment.remote'} eq 'on') {
                   5376:             $attr_ref->{'onload'}  =
                   5377:                 &Apache::lonmenu::loadevents().  $on_load;
                   5378:             $attr_ref->{'onunload'}=
                   5379:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5380:         } else {  
                   5381: 	    $attr_ref->{'onload'}  = $on_load;
                   5382: 	    $attr_ref->{'onunload'}= $on_unload;
                   5383:         }
1.330     albertel 5384:     }
1.339     albertel 5385: 
1.330     albertel 5386:     my $attr_string;
1.1075.2.56  raeburn  5387:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5388: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5389:     }
                   5390:     return $attr_string;
                   5391: }
                   5392: 
                   5393: 
1.182     matthew  5394: ###############################################
1.251     albertel 5395: ###############################################
                   5396: 
                   5397: =pod
                   5398: 
                   5399: =item * &endbodytag()
                   5400: 
                   5401: Returns a uniform footer for LON-CAPA web pages.
                   5402: 
1.635     raeburn  5403: Inputs: 1 - optional reference to an args hash
                   5404: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5405: a 'Continue' link is not displayed if the page contains an
                   5406: internal redirect in the <head></head> section,
                   5407: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5408: 
                   5409: =cut
                   5410: 
                   5411: sub endbodytag {
1.635     raeburn  5412:     my ($args) = @_;
1.1075.2.6  raeburn  5413:     my $endbodytag;
                   5414:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5415:         $endbodytag='</body>';
                   5416:     }
1.269     albertel 5417:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5418:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5419:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5420: 	    $endbodytag=
                   5421: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5422: 	        &mt('Continue').'</a>'.
                   5423: 	        $endbodytag;
                   5424:         }
1.315     albertel 5425:     }
1.251     albertel 5426:     return $endbodytag;
                   5427: }
                   5428: 
1.352     albertel 5429: =pod
                   5430: 
                   5431: =item * &standard_css()
                   5432: 
                   5433: Returns a style sheet
                   5434: 
                   5435: Inputs: (all optional)
                   5436:             domain         -> force to color decorate a page for a specific
                   5437:                                domain
                   5438:             function       -> force usage of a specific rolish color scheme
                   5439:             bgcolor        -> override the default page bgcolor
                   5440: 
                   5441: =cut
                   5442: 
1.343     albertel 5443: sub standard_css {
1.345     albertel 5444:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5445:     $function  = &get_users_function() if (!$function);
                   5446:     my $img    = &designparm($function.'.img',   $domain);
                   5447:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5448:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5449:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5450: #second colour for later usage
1.345     albertel 5451:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5452:     my $pgbg_or_bgcolor =
                   5453: 	         $bgcolor ||
1.352     albertel 5454: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5455:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5456:     my $alink  = &designparm($function.'.alink', $domain);
                   5457:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5458:     my $link   = &designparm($function.'.link',  $domain);
                   5459: 
1.602     albertel 5460:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5461:     my $mono                 = 'monospace';
1.850     bisitz   5462:     my $data_table_head      = $sidebg;
                   5463:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5464:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5465:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5466:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5467:     my $mail_new             = '#FFBB77';
                   5468:     my $mail_new_hover       = '#DD9955';
                   5469:     my $mail_read            = '#BBBB77';
                   5470:     my $mail_read_hover      = '#999944';
                   5471:     my $mail_replied         = '#AAAA88';
                   5472:     my $mail_replied_hover   = '#888855';
                   5473:     my $mail_other           = '#99BBBB';
                   5474:     my $mail_other_hover     = '#669999';
1.391     albertel 5475:     my $table_header         = '#DDDDDD';
1.489     raeburn  5476:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5477:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5478:     my $button_hover         = '#BF2317';
1.392     albertel 5479: 
1.608     albertel 5480:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5481:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5482:                                              : '0 3px 0 4px';
1.448     albertel 5483: 
1.523     albertel 5484: 
1.343     albertel 5485:     return <<END;
1.947     droeschl 5486: 
                   5487: /* needed for iframe to allow 100% height in FF */
                   5488: body, html { 
                   5489:     margin: 0;
                   5490:     padding: 0 0.5%;
                   5491:     height: 99%; /* to avoid scrollbars */
                   5492: }
                   5493: 
1.795     www      5494: body {
1.911     bisitz   5495:   font-family: $sans;
                   5496:   line-height:130%;
                   5497:   font-size:0.83em;
                   5498:   color:$font;
1.795     www      5499: }
                   5500: 
1.959     onken    5501: a:focus,
                   5502: a:focus img {
1.795     www      5503:   color: red;
                   5504: }
1.698     harmsja  5505: 
1.911     bisitz   5506: form, .inline {
                   5507:   display: inline;
1.795     www      5508: }
1.721     harmsja  5509: 
1.795     www      5510: .LC_right {
1.911     bisitz   5511:   text-align:right;
1.795     www      5512: }
                   5513: 
                   5514: .LC_middle {
1.911     bisitz   5515:   vertical-align:middle;
1.795     www      5516: }
1.721     harmsja  5517: 
1.1075.2.38  raeburn  5518: .LC_floatleft {
                   5519:   float: left;
                   5520: }
                   5521: 
                   5522: .LC_floatright {
                   5523:   float: right;
                   5524: }
                   5525: 
1.911     bisitz   5526: .LC_400Box {
                   5527:   width:400px;
                   5528: }
1.721     harmsja  5529: 
1.947     droeschl 5530: .LC_iframecontainer {
                   5531:     width: 98%;
                   5532:     margin: 0;
                   5533:     position: fixed;
                   5534:     top: 8.5em;
                   5535:     bottom: 0;
                   5536: }
                   5537: 
                   5538: .LC_iframecontainer iframe{
                   5539:     border: none;
                   5540:     width: 100%;
                   5541:     height: 100%;
                   5542: }
                   5543: 
1.778     bisitz   5544: .LC_filename {
                   5545:   font-family: $mono;
                   5546:   white-space:pre;
1.921     bisitz   5547:   font-size: 120%;
1.778     bisitz   5548: }
                   5549: 
                   5550: .LC_fileicon {
                   5551:   border: none;
                   5552:   height: 1.3em;
                   5553:   vertical-align: text-bottom;
                   5554:   margin-right: 0.3em;
                   5555:   text-decoration:none;
                   5556: }
                   5557: 
1.1008    www      5558: .LC_setting {
                   5559:   text-decoration:underline;
                   5560: }
                   5561: 
1.350     albertel 5562: .LC_error {
                   5563:   color: red;
                   5564: }
1.795     www      5565: 
1.1075.2.15  raeburn  5566: .LC_warning {
                   5567:   color: darkorange;
                   5568: }
                   5569: 
1.457     albertel 5570: .LC_diff_removed {
1.733     bisitz   5571:   color: red;
1.394     albertel 5572: }
1.532     albertel 5573: 
                   5574: .LC_info,
1.457     albertel 5575: .LC_success,
                   5576: .LC_diff_added {
1.350     albertel 5577:   color: green;
                   5578: }
1.795     www      5579: 
1.802     bisitz   5580: div.LC_confirm_box {
                   5581:   background-color: #FAFAFA;
                   5582:   border: 1px solid $lg_border_color;
                   5583:   margin-right: 0;
                   5584:   padding: 5px;
                   5585: }
                   5586: 
                   5587: div.LC_confirm_box .LC_error img,
                   5588: div.LC_confirm_box .LC_success img {
                   5589:   vertical-align: middle;
                   5590: }
                   5591: 
1.440     albertel 5592: .LC_icon {
1.771     droeschl 5593:   border: none;
1.790     droeschl 5594:   vertical-align: middle;
1.771     droeschl 5595: }
                   5596: 
1.543     albertel 5597: .LC_docs_spacer {
                   5598:   width: 25px;
                   5599:   height: 1px;
1.771     droeschl 5600:   border: none;
1.543     albertel 5601: }
1.346     albertel 5602: 
1.532     albertel 5603: .LC_internal_info {
1.735     bisitz   5604:   color: #999999;
1.532     albertel 5605: }
                   5606: 
1.794     www      5607: .LC_discussion {
1.1050    www      5608:   background: $data_table_dark;
1.911     bisitz   5609:   border: 1px solid black;
                   5610:   margin: 2px;
1.794     www      5611: }
                   5612: 
                   5613: .LC_disc_action_left {
1.1050    www      5614:   background: $sidebg;
1.911     bisitz   5615:   text-align: left;
1.1050    www      5616:   padding: 4px;
                   5617:   margin: 2px;
1.794     www      5618: }
                   5619: 
                   5620: .LC_disc_action_right {
1.1050    www      5621:   background: $sidebg;
1.911     bisitz   5622:   text-align: right;
1.1050    www      5623:   padding: 4px;
                   5624:   margin: 2px;
1.794     www      5625: }
                   5626: 
                   5627: .LC_disc_new_item {
1.911     bisitz   5628:   background: white;
                   5629:   border: 2px solid red;
1.1050    www      5630:   margin: 4px;
                   5631:   padding: 4px;
1.794     www      5632: }
                   5633: 
                   5634: .LC_disc_old_item {
1.911     bisitz   5635:   background: white;
1.1050    www      5636:   margin: 4px;
                   5637:   padding: 4px;
1.794     www      5638: }
                   5639: 
1.458     albertel 5640: table.LC_pastsubmission {
                   5641:   border: 1px solid black;
                   5642:   margin: 2px;
                   5643: }
                   5644: 
1.924     bisitz   5645: table#LC_menubuttons {
1.345     albertel 5646:   width: 100%;
                   5647:   background: $pgbg;
1.392     albertel 5648:   border: 2px;
1.402     albertel 5649:   border-collapse: separate;
1.803     bisitz   5650:   padding: 0;
1.345     albertel 5651: }
1.392     albertel 5652: 
1.801     tempelho 5653: table#LC_title_bar a {
                   5654:   color: $fontmenu;
                   5655: }
1.836     bisitz   5656: 
1.807     droeschl 5657: table#LC_title_bar {
1.819     tempelho 5658:   clear: both;
1.836     bisitz   5659:   display: none;
1.807     droeschl 5660: }
                   5661: 
1.795     www      5662: table#LC_title_bar,
1.933     droeschl 5663: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5664: table#LC_title_bar.LC_with_remote {
1.359     albertel 5665:   width: 100%;
1.392     albertel 5666:   border-color: $pgbg;
                   5667:   border-style: solid;
                   5668:   border-width: $border;
1.379     albertel 5669:   background: $pgbg;
1.801     tempelho 5670:   color: $fontmenu;
1.392     albertel 5671:   border-collapse: collapse;
1.803     bisitz   5672:   padding: 0;
1.819     tempelho 5673:   margin: 0;
1.359     albertel 5674: }
1.795     www      5675: 
1.933     droeschl 5676: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5677:     margin: 0;
                   5678:     padding: 0;
1.933     droeschl 5679:     position: relative;
                   5680:     list-style: none;
1.913     droeschl 5681: }
1.933     droeschl 5682: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5683:     display: inline;
                   5684: }
1.933     droeschl 5685: 
                   5686: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5687:     padding: 0;
1.933     droeschl 5688:     margin: 0;
                   5689:     float: left;
1.913     droeschl 5690: }
1.933     droeschl 5691: .LC_breadcrumb_tools_tools {
                   5692:     padding: 0;
                   5693:     margin: 0;
1.913     droeschl 5694:     float: right;
                   5695: }
                   5696: 
1.359     albertel 5697: table#LC_title_bar td {
                   5698:   background: $tabbg;
                   5699: }
1.795     www      5700: 
1.911     bisitz   5701: table#LC_menubuttons img {
1.803     bisitz   5702:   border: none;
1.346     albertel 5703: }
1.795     www      5704: 
1.842     droeschl 5705: .LC_breadcrumbs_component {
1.911     bisitz   5706:   float: right;
                   5707:   margin: 0 1em;
1.357     albertel 5708: }
1.842     droeschl 5709: .LC_breadcrumbs_component img {
1.911     bisitz   5710:   vertical-align: middle;
1.777     tempelho 5711: }
1.795     www      5712: 
1.383     albertel 5713: td.LC_table_cell_checkbox {
                   5714:   text-align: center;
                   5715: }
1.795     www      5716: 
                   5717: .LC_fontsize_small {
1.911     bisitz   5718:   font-size: 70%;
1.705     tempelho 5719: }
                   5720: 
1.844     bisitz   5721: #LC_breadcrumbs {
1.911     bisitz   5722:   clear:both;
                   5723:   background: $sidebg;
                   5724:   border-bottom: 1px solid $lg_border_color;
                   5725:   line-height: 2.5em;
1.933     droeschl 5726:   overflow: hidden;
1.911     bisitz   5727:   margin: 0;
                   5728:   padding: 0;
1.995     raeburn  5729:   text-align: left;
1.819     tempelho 5730: }
1.862     bisitz   5731: 
1.1075.2.16  raeburn  5732: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5733:   clear:both;
                   5734:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5735:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5736:   margin: 0 0 10px 0;
1.966     bisitz   5737:   padding: 3px;
1.995     raeburn  5738:   text-align: left;
1.822     bisitz   5739: }
                   5740: 
1.795     www      5741: .LC_fontsize_medium {
1.911     bisitz   5742:   font-size: 85%;
1.705     tempelho 5743: }
                   5744: 
1.795     www      5745: .LC_fontsize_large {
1.911     bisitz   5746:   font-size: 120%;
1.705     tempelho 5747: }
                   5748: 
1.346     albertel 5749: .LC_menubuttons_inline_text {
                   5750:   color: $font;
1.698     harmsja  5751:   font-size: 90%;
1.701     harmsja  5752:   padding-left:3px;
1.346     albertel 5753: }
                   5754: 
1.934     droeschl 5755: .LC_menubuttons_inline_text img{
                   5756:   vertical-align: middle;
                   5757: }
                   5758: 
1.1051    www      5759: li.LC_menubuttons_inline_text img {
1.951     onken    5760:   cursor:pointer;
1.1002    droeschl 5761:   text-decoration: none;
1.951     onken    5762: }
                   5763: 
1.526     www      5764: .LC_menubuttons_link {
                   5765:   text-decoration: none;
                   5766: }
1.795     www      5767: 
1.522     albertel 5768: .LC_menubuttons_category {
1.521     www      5769:   color: $font;
1.526     www      5770:   background: $pgbg;
1.521     www      5771:   font-size: larger;
                   5772:   font-weight: bold;
                   5773: }
                   5774: 
1.346     albertel 5775: td.LC_menubuttons_text {
1.911     bisitz   5776:   color: $font;
1.346     albertel 5777: }
1.706     harmsja  5778: 
1.346     albertel 5779: .LC_current_location {
                   5780:   background: $tabbg;
                   5781: }
1.795     www      5782: 
1.938     bisitz   5783: table.LC_data_table {
1.347     albertel 5784:   border: 1px solid #000000;
1.402     albertel 5785:   border-collapse: separate;
1.426     albertel 5786:   border-spacing: 1px;
1.610     albertel 5787:   background: $pgbg;
1.347     albertel 5788: }
1.795     www      5789: 
1.422     albertel 5790: .LC_data_table_dense {
                   5791:   font-size: small;
                   5792: }
1.795     www      5793: 
1.507     raeburn  5794: table.LC_nested_outer {
                   5795:   border: 1px solid #000000;
1.589     raeburn  5796:   border-collapse: collapse;
1.803     bisitz   5797:   border-spacing: 0;
1.507     raeburn  5798:   width: 100%;
                   5799: }
1.795     www      5800: 
1.879     raeburn  5801: table.LC_innerpickbox,
1.507     raeburn  5802: table.LC_nested {
1.803     bisitz   5803:   border: none;
1.589     raeburn  5804:   border-collapse: collapse;
1.803     bisitz   5805:   border-spacing: 0;
1.507     raeburn  5806:   width: 100%;
                   5807: }
1.795     www      5808: 
1.911     bisitz   5809: table.LC_data_table tr th,
                   5810: table.LC_calendar tr th,
1.879     raeburn  5811: table.LC_prior_tries tr th,
                   5812: table.LC_innerpickbox tr th {
1.349     albertel 5813:   font-weight: bold;
                   5814:   background-color: $data_table_head;
1.801     tempelho 5815:   color:$fontmenu;
1.701     harmsja  5816:   font-size:90%;
1.347     albertel 5817: }
1.795     www      5818: 
1.879     raeburn  5819: table.LC_innerpickbox tr th,
                   5820: table.LC_innerpickbox tr td {
                   5821:   vertical-align: top;
                   5822: }
                   5823: 
1.711     raeburn  5824: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5825:   background-color: #CCCCCC;
1.711     raeburn  5826:   font-weight: bold;
                   5827:   text-align: left;
                   5828: }
1.795     www      5829: 
1.912     bisitz   5830: table.LC_data_table tr.LC_odd_row > td {
                   5831:   background-color: $data_table_light;
                   5832:   padding: 2px;
                   5833:   vertical-align: top;
                   5834: }
                   5835: 
1.809     bisitz   5836: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5837:   background-color: $data_table_light;
1.912     bisitz   5838:   vertical-align: top;
                   5839: }
                   5840: 
                   5841: table.LC_data_table tr.LC_even_row > td {
                   5842:   background-color: $data_table_dark;
1.425     albertel 5843:   padding: 2px;
1.900     bisitz   5844:   vertical-align: top;
1.347     albertel 5845: }
1.795     www      5846: 
1.809     bisitz   5847: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5848:   background-color: $data_table_dark;
1.900     bisitz   5849:   vertical-align: top;
1.347     albertel 5850: }
1.795     www      5851: 
1.425     albertel 5852: table.LC_data_table tr.LC_data_table_highlight td {
                   5853:   background-color: $data_table_darker;
                   5854: }
1.795     www      5855: 
1.639     raeburn  5856: table.LC_data_table tr td.LC_leftcol_header {
                   5857:   background-color: $data_table_head;
                   5858:   font-weight: bold;
                   5859: }
1.795     www      5860: 
1.451     albertel 5861: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5862: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5863:   font-weight: bold;
                   5864:   font-style: italic;
                   5865:   text-align: center;
                   5866:   padding: 8px;
1.347     albertel 5867: }
1.795     www      5868: 
1.1075.2.30  raeburn  5869: table.LC_data_table tr.LC_empty_row td,
                   5870: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5871:   background-color: $sidebg;
                   5872: }
                   5873: 
                   5874: table.LC_nested tr.LC_empty_row td {
                   5875:   background-color: #FFFFFF;
                   5876: }
                   5877: 
1.890     droeschl 5878: table.LC_caption {
                   5879: }
                   5880: 
1.507     raeburn  5881: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5882:   padding: 4ex
                   5883: }
1.795     www      5884: 
1.507     raeburn  5885: table.LC_nested_outer tr th {
                   5886:   font-weight: bold;
1.801     tempelho 5887:   color:$fontmenu;
1.507     raeburn  5888:   background-color: $data_table_head;
1.701     harmsja  5889:   font-size: small;
1.507     raeburn  5890:   border-bottom: 1px solid #000000;
                   5891: }
1.795     www      5892: 
1.507     raeburn  5893: table.LC_nested_outer tr td.LC_subheader {
                   5894:   background-color: $data_table_head;
                   5895:   font-weight: bold;
                   5896:   font-size: small;
                   5897:   border-bottom: 1px solid #000000;
                   5898:   text-align: right;
1.451     albertel 5899: }
1.795     www      5900: 
1.507     raeburn  5901: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5902:   background-color: #CCCCCC;
1.451     albertel 5903:   font-weight: bold;
                   5904:   font-size: small;
1.507     raeburn  5905:   text-align: center;
                   5906: }
1.795     www      5907: 
1.589     raeburn  5908: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5909: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5910:   text-align: left;
1.451     albertel 5911: }
1.795     www      5912: 
1.507     raeburn  5913: table.LC_nested td {
1.735     bisitz   5914:   background-color: #FFFFFF;
1.451     albertel 5915:   font-size: small;
1.507     raeburn  5916: }
1.795     www      5917: 
1.507     raeburn  5918: table.LC_nested_outer tr th.LC_right_item,
                   5919: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5920: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5921: table.LC_nested tr td.LC_right_item {
1.451     albertel 5922:   text-align: right;
                   5923: }
                   5924: 
1.507     raeburn  5925: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5926:   background-color: #EEEEEE;
1.451     albertel 5927: }
                   5928: 
1.473     raeburn  5929: table.LC_createuser {
                   5930: }
                   5931: 
                   5932: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5933:   font-size: small;
1.473     raeburn  5934: }
                   5935: 
                   5936: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5937:   background-color: #CCCCCC;
1.473     raeburn  5938:   font-weight: bold;
                   5939:   text-align: center;
                   5940: }
                   5941: 
1.349     albertel 5942: table.LC_calendar {
                   5943:   border: 1px solid #000000;
                   5944:   border-collapse: collapse;
1.917     raeburn  5945:   width: 98%;
1.349     albertel 5946: }
1.795     www      5947: 
1.349     albertel 5948: table.LC_calendar_pickdate {
                   5949:   font-size: xx-small;
                   5950: }
1.795     www      5951: 
1.349     albertel 5952: table.LC_calendar tr td {
                   5953:   border: 1px solid #000000;
                   5954:   vertical-align: top;
1.917     raeburn  5955:   width: 14%;
1.349     albertel 5956: }
1.795     www      5957: 
1.349     albertel 5958: table.LC_calendar tr td.LC_calendar_day_empty {
                   5959:   background-color: $data_table_dark;
                   5960: }
1.795     www      5961: 
1.779     bisitz   5962: table.LC_calendar tr td.LC_calendar_day_current {
                   5963:   background-color: $data_table_highlight;
1.777     tempelho 5964: }
1.795     www      5965: 
1.938     bisitz   5966: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5967:   background-color: $mail_new;
                   5968: }
1.795     www      5969: 
1.938     bisitz   5970: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5971:   background-color: $mail_new_hover;
                   5972: }
1.795     www      5973: 
1.938     bisitz   5974: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5975:   background-color: $mail_read;
                   5976: }
1.795     www      5977: 
1.938     bisitz   5978: /*
                   5979: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5980:   background-color: $mail_read_hover;
                   5981: }
1.938     bisitz   5982: */
1.795     www      5983: 
1.938     bisitz   5984: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5985:   background-color: $mail_replied;
                   5986: }
1.795     www      5987: 
1.938     bisitz   5988: /*
                   5989: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5990:   background-color: $mail_replied_hover;
                   5991: }
1.938     bisitz   5992: */
1.795     www      5993: 
1.938     bisitz   5994: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5995:   background-color: $mail_other;
                   5996: }
1.795     www      5997: 
1.938     bisitz   5998: /*
                   5999: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6000:   background-color: $mail_other_hover;
                   6001: }
1.938     bisitz   6002: */
1.494     raeburn  6003: 
1.777     tempelho 6004: table.LC_data_table tr > td.LC_browser_file,
                   6005: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6006:   background: #AAEE77;
1.389     albertel 6007: }
1.795     www      6008: 
1.777     tempelho 6009: table.LC_data_table tr > td.LC_browser_file_locked,
                   6010: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6011:   background: #FFAA99;
1.387     albertel 6012: }
1.795     www      6013: 
1.777     tempelho 6014: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6015:   background: #888888;
1.779     bisitz   6016: }
1.795     www      6017: 
1.777     tempelho 6018: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6019: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6020:   background: #F8F866;
1.777     tempelho 6021: }
1.795     www      6022: 
1.696     bisitz   6023: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6024:   background: #E0E8FF;
1.387     albertel 6025: }
1.696     bisitz   6026: 
1.707     bisitz   6027: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6028:   /* background: #77FF77; */
1.707     bisitz   6029: }
1.795     www      6030: 
1.707     bisitz   6031: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6032:   border-right: 8px solid #FFFF77;
1.707     bisitz   6033: }
1.795     www      6034: 
1.707     bisitz   6035: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6036:   border-right: 8px solid #FFAA77;
1.707     bisitz   6037: }
1.795     www      6038: 
1.707     bisitz   6039: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6040:   border-right: 8px solid #FF7777;
1.707     bisitz   6041: }
1.795     www      6042: 
1.707     bisitz   6043: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6044:   border-right: 8px solid #AAFF77;
1.707     bisitz   6045: }
1.795     www      6046: 
1.707     bisitz   6047: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6048:   border-right: 8px solid #11CC55;
1.707     bisitz   6049: }
                   6050: 
1.388     albertel 6051: span.LC_current_location {
1.701     harmsja  6052:   font-size:larger;
1.388     albertel 6053:   background: $pgbg;
                   6054: }
1.387     albertel 6055: 
1.1029    www      6056: span.LC_current_nav_location {
                   6057:   font-weight:bold;
                   6058:   background: $sidebg;
                   6059: }
                   6060: 
1.395     albertel 6061: span.LC_parm_menu_item {
                   6062:   font-size: larger;
                   6063: }
1.795     www      6064: 
1.395     albertel 6065: span.LC_parm_scope_all {
                   6066:   color: red;
                   6067: }
1.795     www      6068: 
1.395     albertel 6069: span.LC_parm_scope_folder {
                   6070:   color: green;
                   6071: }
1.795     www      6072: 
1.395     albertel 6073: span.LC_parm_scope_resource {
                   6074:   color: orange;
                   6075: }
1.795     www      6076: 
1.395     albertel 6077: span.LC_parm_part {
                   6078:   color: blue;
                   6079: }
1.795     www      6080: 
1.911     bisitz   6081: span.LC_parm_folder,
                   6082: span.LC_parm_symb {
1.395     albertel 6083:   font-size: x-small;
                   6084:   font-family: $mono;
                   6085:   color: #AAAAAA;
                   6086: }
                   6087: 
1.977     bisitz   6088: ul.LC_parm_parmlist li {
                   6089:   display: inline-block;
                   6090:   padding: 0.3em 0.8em;
                   6091:   vertical-align: top;
                   6092:   width: 150px;
                   6093:   border-top:1px solid $lg_border_color;
                   6094: }
                   6095: 
1.795     www      6096: td.LC_parm_overview_level_menu,
                   6097: td.LC_parm_overview_map_menu,
                   6098: td.LC_parm_overview_parm_selectors,
                   6099: td.LC_parm_overview_restrictions  {
1.396     albertel 6100:   border: 1px solid black;
                   6101:   border-collapse: collapse;
                   6102: }
1.795     www      6103: 
1.396     albertel 6104: table.LC_parm_overview_restrictions td {
                   6105:   border-width: 1px 4px 1px 4px;
                   6106:   border-style: solid;
                   6107:   border-color: $pgbg;
                   6108:   text-align: center;
                   6109: }
1.795     www      6110: 
1.396     albertel 6111: table.LC_parm_overview_restrictions th {
                   6112:   background: $tabbg;
                   6113:   border-width: 1px 4px 1px 4px;
                   6114:   border-style: solid;
                   6115:   border-color: $pgbg;
                   6116: }
1.795     www      6117: 
1.398     albertel 6118: table#LC_helpmenu {
1.803     bisitz   6119:   border: none;
1.398     albertel 6120:   height: 55px;
1.803     bisitz   6121:   border-spacing: 0;
1.398     albertel 6122: }
                   6123: 
                   6124: table#LC_helpmenu fieldset legend {
                   6125:   font-size: larger;
                   6126: }
1.795     www      6127: 
1.397     albertel 6128: table#LC_helpmenu_links {
                   6129:   width: 100%;
                   6130:   border: 1px solid black;
                   6131:   background: $pgbg;
1.803     bisitz   6132:   padding: 0;
1.397     albertel 6133:   border-spacing: 1px;
                   6134: }
1.795     www      6135: 
1.397     albertel 6136: table#LC_helpmenu_links tr td {
                   6137:   padding: 1px;
                   6138:   background: $tabbg;
1.399     albertel 6139:   text-align: center;
                   6140:   font-weight: bold;
1.397     albertel 6141: }
1.396     albertel 6142: 
1.795     www      6143: table#LC_helpmenu_links a:link,
                   6144: table#LC_helpmenu_links a:visited,
1.397     albertel 6145: table#LC_helpmenu_links a:active {
                   6146:   text-decoration: none;
                   6147:   color: $font;
                   6148: }
1.795     www      6149: 
1.397     albertel 6150: table#LC_helpmenu_links a:hover {
                   6151:   text-decoration: underline;
                   6152:   color: $vlink;
                   6153: }
1.396     albertel 6154: 
1.417     albertel 6155: .LC_chrt_popup_exists {
                   6156:   border: 1px solid #339933;
                   6157:   margin: -1px;
                   6158: }
1.795     www      6159: 
1.417     albertel 6160: .LC_chrt_popup_up {
                   6161:   border: 1px solid yellow;
                   6162:   margin: -1px;
                   6163: }
1.795     www      6164: 
1.417     albertel 6165: .LC_chrt_popup {
                   6166:   border: 1px solid #8888FF;
                   6167:   background: #CCCCFF;
                   6168: }
1.795     www      6169: 
1.421     albertel 6170: table.LC_pick_box {
                   6171:   border-collapse: separate;
                   6172:   background: white;
                   6173:   border: 1px solid black;
                   6174:   border-spacing: 1px;
                   6175: }
1.795     www      6176: 
1.421     albertel 6177: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6178:   background: $sidebg;
1.421     albertel 6179:   font-weight: bold;
1.900     bisitz   6180:   text-align: left;
1.740     bisitz   6181:   vertical-align: top;
1.421     albertel 6182:   width: 184px;
                   6183:   padding: 8px;
                   6184: }
1.795     www      6185: 
1.579     raeburn  6186: table.LC_pick_box td.LC_pick_box_value {
                   6187:   text-align: left;
                   6188:   padding: 8px;
                   6189: }
1.795     www      6190: 
1.579     raeburn  6191: table.LC_pick_box td.LC_pick_box_select {
                   6192:   text-align: left;
                   6193:   padding: 8px;
                   6194: }
1.795     www      6195: 
1.424     albertel 6196: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6197:   padding: 0;
1.421     albertel 6198:   height: 1px;
                   6199:   background: black;
                   6200: }
1.795     www      6201: 
1.421     albertel 6202: table.LC_pick_box td.LC_pick_box_submit {
                   6203:   text-align: right;
                   6204: }
1.795     www      6205: 
1.579     raeburn  6206: table.LC_pick_box td.LC_evenrow_value {
                   6207:   text-align: left;
                   6208:   padding: 8px;
                   6209:   background-color: $data_table_light;
                   6210: }
1.795     www      6211: 
1.579     raeburn  6212: table.LC_pick_box td.LC_oddrow_value {
                   6213:   text-align: left;
                   6214:   padding: 8px;
                   6215:   background-color: $data_table_light;
                   6216: }
1.795     www      6217: 
1.579     raeburn  6218: span.LC_helpform_receipt_cat {
                   6219:   font-weight: bold;
                   6220: }
1.795     www      6221: 
1.424     albertel 6222: table.LC_group_priv_box {
                   6223:   background: white;
                   6224:   border: 1px solid black;
                   6225:   border-spacing: 1px;
                   6226: }
1.795     www      6227: 
1.424     albertel 6228: table.LC_group_priv_box td.LC_pick_box_title {
                   6229:   background: $tabbg;
                   6230:   font-weight: bold;
                   6231:   text-align: right;
                   6232:   width: 184px;
                   6233: }
1.795     www      6234: 
1.424     albertel 6235: table.LC_group_priv_box td.LC_groups_fixed {
                   6236:   background: $data_table_light;
                   6237:   text-align: center;
                   6238: }
1.795     www      6239: 
1.424     albertel 6240: table.LC_group_priv_box td.LC_groups_optional {
                   6241:   background: $data_table_dark;
                   6242:   text-align: center;
                   6243: }
1.795     www      6244: 
1.424     albertel 6245: table.LC_group_priv_box td.LC_groups_functionality {
                   6246:   background: $data_table_darker;
                   6247:   text-align: center;
                   6248:   font-weight: bold;
                   6249: }
1.795     www      6250: 
1.424     albertel 6251: table.LC_group_priv td {
                   6252:   text-align: left;
1.803     bisitz   6253:   padding: 0;
1.424     albertel 6254: }
                   6255: 
                   6256: .LC_navbuttons {
                   6257:   margin: 2ex 0ex 2ex 0ex;
                   6258: }
1.795     www      6259: 
1.423     albertel 6260: .LC_topic_bar {
                   6261:   font-weight: bold;
                   6262:   background: $tabbg;
1.918     wenzelju 6263:   margin: 1em 0em 1em 2em;
1.805     bisitz   6264:   padding: 3px;
1.918     wenzelju 6265:   font-size: 1.2em;
1.423     albertel 6266: }
1.795     www      6267: 
1.423     albertel 6268: .LC_topic_bar span {
1.918     wenzelju 6269:   left: 0.5em;
                   6270:   position: absolute;
1.423     albertel 6271:   vertical-align: middle;
1.918     wenzelju 6272:   font-size: 1.2em;
1.423     albertel 6273: }
1.795     www      6274: 
1.423     albertel 6275: table.LC_course_group_status {
                   6276:   margin: 20px;
                   6277: }
1.795     www      6278: 
1.423     albertel 6279: table.LC_status_selector td {
                   6280:   vertical-align: top;
                   6281:   text-align: center;
1.424     albertel 6282:   padding: 4px;
                   6283: }
1.795     www      6284: 
1.599     albertel 6285: div.LC_feedback_link {
1.616     albertel 6286:   clear: both;
1.829     kalberla 6287:   background: $sidebg;
1.779     bisitz   6288:   width: 100%;
1.829     kalberla 6289:   padding-bottom: 10px;
                   6290:   border: 1px $tabbg solid;
1.833     kalberla 6291:   height: 22px;
                   6292:   line-height: 22px;
                   6293:   padding-top: 5px;
                   6294: }
                   6295: 
                   6296: div.LC_feedback_link img {
                   6297:   height: 22px;
1.867     kalberla 6298:   vertical-align:middle;
1.829     kalberla 6299: }
                   6300: 
1.911     bisitz   6301: div.LC_feedback_link a {
1.829     kalberla 6302:   text-decoration: none;
1.489     raeburn  6303: }
1.795     www      6304: 
1.867     kalberla 6305: div.LC_comblock {
1.911     bisitz   6306:   display:inline;
1.867     kalberla 6307:   color:$font;
                   6308:   font-size:90%;
                   6309: }
                   6310: 
                   6311: div.LC_feedback_link div.LC_comblock {
                   6312:   padding-left:5px;
                   6313: }
                   6314: 
                   6315: div.LC_feedback_link div.LC_comblock a {
                   6316:   color:$font;
                   6317: }
                   6318: 
1.489     raeburn  6319: span.LC_feedback_link {
1.858     bisitz   6320:   /* background: $feedback_link_bg; */
1.599     albertel 6321:   font-size: larger;
                   6322: }
1.795     www      6323: 
1.599     albertel 6324: span.LC_message_link {
1.858     bisitz   6325:   /* background: $feedback_link_bg; */
1.599     albertel 6326:   font-size: larger;
                   6327:   position: absolute;
                   6328:   right: 1em;
1.489     raeburn  6329: }
1.421     albertel 6330: 
1.515     albertel 6331: table.LC_prior_tries {
1.524     albertel 6332:   border: 1px solid #000000;
                   6333:   border-collapse: separate;
                   6334:   border-spacing: 1px;
1.515     albertel 6335: }
1.523     albertel 6336: 
1.515     albertel 6337: table.LC_prior_tries td {
1.524     albertel 6338:   padding: 2px;
1.515     albertel 6339: }
1.523     albertel 6340: 
                   6341: .LC_answer_correct {
1.795     www      6342:   background: lightgreen;
                   6343:   color: darkgreen;
                   6344:   padding: 6px;
1.523     albertel 6345: }
1.795     www      6346: 
1.523     albertel 6347: .LC_answer_charged_try {
1.797     www      6348:   background: #FFAAAA;
1.795     www      6349:   color: darkred;
                   6350:   padding: 6px;
1.523     albertel 6351: }
1.795     www      6352: 
1.779     bisitz   6353: .LC_answer_not_charged_try,
1.523     albertel 6354: .LC_answer_no_grade,
                   6355: .LC_answer_late {
1.795     www      6356:   background: lightyellow;
1.523     albertel 6357:   color: black;
1.795     www      6358:   padding: 6px;
1.523     albertel 6359: }
1.795     www      6360: 
1.523     albertel 6361: .LC_answer_previous {
1.795     www      6362:   background: lightblue;
                   6363:   color: darkblue;
                   6364:   padding: 6px;
1.523     albertel 6365: }
1.795     www      6366: 
1.779     bisitz   6367: .LC_answer_no_message {
1.777     tempelho 6368:   background: #FFFFFF;
                   6369:   color: black;
1.795     www      6370:   padding: 6px;
1.779     bisitz   6371: }
1.795     www      6372: 
1.779     bisitz   6373: .LC_answer_unknown {
                   6374:   background: orange;
                   6375:   color: black;
1.795     www      6376:   padding: 6px;
1.777     tempelho 6377: }
1.795     www      6378: 
1.529     albertel 6379: span.LC_prior_numerical,
                   6380: span.LC_prior_string,
                   6381: span.LC_prior_custom,
                   6382: span.LC_prior_reaction,
                   6383: span.LC_prior_math {
1.925     bisitz   6384:   font-family: $mono;
1.523     albertel 6385:   white-space: pre;
                   6386: }
                   6387: 
1.525     albertel 6388: span.LC_prior_string {
1.925     bisitz   6389:   font-family: $mono;
1.525     albertel 6390:   white-space: pre;
                   6391: }
                   6392: 
1.523     albertel 6393: table.LC_prior_option {
                   6394:   width: 100%;
                   6395:   border-collapse: collapse;
                   6396: }
1.795     www      6397: 
1.911     bisitz   6398: table.LC_prior_rank,
1.795     www      6399: table.LC_prior_match {
1.528     albertel 6400:   border-collapse: collapse;
                   6401: }
1.795     www      6402: 
1.528     albertel 6403: table.LC_prior_option tr td,
                   6404: table.LC_prior_rank tr td,
                   6405: table.LC_prior_match tr td {
1.524     albertel 6406:   border: 1px solid #000000;
1.515     albertel 6407: }
                   6408: 
1.855     bisitz   6409: .LC_nobreak {
1.544     albertel 6410:   white-space: nowrap;
1.519     raeburn  6411: }
                   6412: 
1.576     raeburn  6413: span.LC_cusr_emph {
                   6414:   font-style: italic;
                   6415: }
                   6416: 
1.633     raeburn  6417: span.LC_cusr_subheading {
                   6418:   font-weight: normal;
                   6419:   font-size: 85%;
                   6420: }
                   6421: 
1.861     bisitz   6422: div.LC_docs_entry_move {
1.859     bisitz   6423:   border: 1px solid #BBBBBB;
1.545     albertel 6424:   background: #DDDDDD;
1.861     bisitz   6425:   width: 22px;
1.859     bisitz   6426:   padding: 1px;
                   6427:   margin: 0;
1.545     albertel 6428: }
                   6429: 
1.861     bisitz   6430: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6431: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6432:   font-size: x-small;
                   6433: }
1.795     www      6434: 
1.861     bisitz   6435: .LC_docs_entry_parameter {
                   6436:   white-space: nowrap;
                   6437: }
                   6438: 
1.544     albertel 6439: .LC_docs_copy {
1.545     albertel 6440:   color: #000099;
1.544     albertel 6441: }
1.795     www      6442: 
1.544     albertel 6443: .LC_docs_cut {
1.545     albertel 6444:   color: #550044;
1.544     albertel 6445: }
1.795     www      6446: 
1.544     albertel 6447: .LC_docs_rename {
1.545     albertel 6448:   color: #009900;
1.544     albertel 6449: }
1.795     www      6450: 
1.544     albertel 6451: .LC_docs_remove {
1.545     albertel 6452:   color: #990000;
                   6453: }
                   6454: 
1.547     albertel 6455: .LC_docs_reinit_warn,
                   6456: .LC_docs_ext_edit {
                   6457:   font-size: x-small;
                   6458: }
                   6459: 
1.545     albertel 6460: table.LC_docs_adddocs td,
                   6461: table.LC_docs_adddocs th {
                   6462:   border: 1px solid #BBBBBB;
                   6463:   padding: 4px;
                   6464:   background: #DDDDDD;
1.543     albertel 6465: }
                   6466: 
1.584     albertel 6467: table.LC_sty_begin {
                   6468:   background: #BBFFBB;
                   6469: }
1.795     www      6470: 
1.584     albertel 6471: table.LC_sty_end {
                   6472:   background: #FFBBBB;
                   6473: }
                   6474: 
1.589     raeburn  6475: table.LC_double_column {
1.803     bisitz   6476:   border-width: 0;
1.589     raeburn  6477:   border-collapse: collapse;
                   6478:   width: 100%;
                   6479:   padding: 2px;
                   6480: }
                   6481: 
                   6482: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6483:   top: 2px;
1.589     raeburn  6484:   left: 2px;
                   6485:   width: 47%;
                   6486:   vertical-align: top;
                   6487: }
                   6488: 
                   6489: table.LC_double_column tr td.LC_right_col {
                   6490:   top: 2px;
1.779     bisitz   6491:   right: 2px;
1.589     raeburn  6492:   width: 47%;
                   6493:   vertical-align: top;
                   6494: }
                   6495: 
1.591     raeburn  6496: div.LC_left_float {
                   6497:   float: left;
                   6498:   padding-right: 5%;
1.597     albertel 6499:   padding-bottom: 4px;
1.591     raeburn  6500: }
                   6501: 
                   6502: div.LC_clear_float_header {
1.597     albertel 6503:   padding-bottom: 2px;
1.591     raeburn  6504: }
                   6505: 
                   6506: div.LC_clear_float_footer {
1.597     albertel 6507:   padding-top: 10px;
1.591     raeburn  6508:   clear: both;
                   6509: }
                   6510: 
1.597     albertel 6511: div.LC_grade_show_user {
1.941     bisitz   6512: /*  border-left: 5px solid $sidebg; */
                   6513:   border-top: 5px solid #000000;
                   6514:   margin: 50px 0 0 0;
1.936     bisitz   6515:   padding: 15px 0 5px 10px;
1.597     albertel 6516: }
1.795     www      6517: 
1.936     bisitz   6518: div.LC_grade_show_user_odd_row {
1.941     bisitz   6519: /*  border-left: 5px solid #000000; */
                   6520: }
                   6521: 
                   6522: div.LC_grade_show_user div.LC_Box {
                   6523:   margin-right: 50px;
1.597     albertel 6524: }
                   6525: 
                   6526: div.LC_grade_submissions,
                   6527: div.LC_grade_message_center,
1.936     bisitz   6528: div.LC_grade_info_links {
1.597     albertel 6529:   margin: 5px;
                   6530:   width: 99%;
                   6531:   background: #FFFFFF;
                   6532: }
1.795     www      6533: 
1.597     albertel 6534: div.LC_grade_submissions_header,
1.936     bisitz   6535: div.LC_grade_message_center_header {
1.705     tempelho 6536:   font-weight: bold;
                   6537:   font-size: large;
1.597     albertel 6538: }
1.795     www      6539: 
1.597     albertel 6540: div.LC_grade_submissions_body,
1.936     bisitz   6541: div.LC_grade_message_center_body {
1.597     albertel 6542:   border: 1px solid black;
                   6543:   width: 99%;
                   6544:   background: #FFFFFF;
                   6545: }
1.795     www      6546: 
1.613     albertel 6547: table.LC_scantron_action {
                   6548:   width: 100%;
                   6549: }
1.795     www      6550: 
1.613     albertel 6551: table.LC_scantron_action tr th {
1.698     harmsja  6552:   font-weight:bold;
                   6553:   font-style:normal;
1.613     albertel 6554: }
1.795     www      6555: 
1.779     bisitz   6556: .LC_edit_problem_header,
1.614     albertel 6557: div.LC_edit_problem_footer {
1.705     tempelho 6558:   font-weight: normal;
                   6559:   font-size:  medium;
1.602     albertel 6560:   margin: 2px;
1.1060    bisitz   6561:   background-color: $sidebg;
1.600     albertel 6562: }
1.795     www      6563: 
1.600     albertel 6564: div.LC_edit_problem_header,
1.602     albertel 6565: div.LC_edit_problem_header div,
1.614     albertel 6566: div.LC_edit_problem_footer,
                   6567: div.LC_edit_problem_footer div,
1.602     albertel 6568: div.LC_edit_problem_editxml_header,
                   6569: div.LC_edit_problem_editxml_header div {
1.600     albertel 6570:   margin-top: 5px;
                   6571: }
1.795     www      6572: 
1.600     albertel 6573: div.LC_edit_problem_header_title {
1.705     tempelho 6574:   font-weight: bold;
                   6575:   font-size: larger;
1.602     albertel 6576:   background: $tabbg;
                   6577:   padding: 3px;
1.1060    bisitz   6578:   margin: 0 0 5px 0;
1.602     albertel 6579: }
1.795     www      6580: 
1.602     albertel 6581: table.LC_edit_problem_header_title {
                   6582:   width: 100%;
1.600     albertel 6583:   background: $tabbg;
1.602     albertel 6584: }
                   6585: 
                   6586: div.LC_edit_problem_discards {
                   6587:   float: left;
                   6588:   padding-bottom: 5px;
                   6589: }
1.795     www      6590: 
1.602     albertel 6591: div.LC_edit_problem_saves {
                   6592:   float: right;
                   6593:   padding-bottom: 5px;
1.600     albertel 6594: }
1.795     www      6595: 
1.1075.2.34  raeburn  6596: .LC_edit_opt {
                   6597:   padding-left: 1em;
                   6598:   white-space: nowrap;
                   6599: }
                   6600: 
1.1075.2.57  raeburn  6601: .LC_edit_problem_latexhelper{
                   6602:     text-align: right;
                   6603: }
                   6604: 
                   6605: #LC_edit_problem_colorful div{
                   6606:     margin-left: 40px;
                   6607: }
                   6608: 
1.911     bisitz   6609: img.stift {
1.803     bisitz   6610:   border-width: 0;
                   6611:   vertical-align: middle;
1.677     riegler  6612: }
1.680     riegler  6613: 
1.923     bisitz   6614: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6615:   vertical-align: top;
1.777     tempelho 6616: }
1.795     www      6617: 
1.716     raeburn  6618: div.LC_createcourse {
1.911     bisitz   6619:   margin: 10px 10px 10px 10px;
1.716     raeburn  6620: }
                   6621: 
1.917     raeburn  6622: .LC_dccid {
1.1075.2.38  raeburn  6623:   float: right;
1.917     raeburn  6624:   margin: 0.2em 0 0 0;
                   6625:   padding: 0;
                   6626:   font-size: 90%;
                   6627:   display:none;
                   6628: }
                   6629: 
1.897     wenzelju 6630: ol.LC_primary_menu a:hover,
1.721     harmsja  6631: ol#LC_MenuBreadcrumbs a:hover,
                   6632: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6633: ul#LC_secondary_menu a:hover,
1.721     harmsja  6634: .LC_FormSectionClearButton input:hover
1.795     www      6635: ul.LC_TabContent   li:hover a {
1.952     onken    6636:   color:$button_hover;
1.911     bisitz   6637:   text-decoration:none;
1.693     droeschl 6638: }
                   6639: 
1.779     bisitz   6640: h1 {
1.911     bisitz   6641:   padding: 0;
                   6642:   line-height:130%;
1.693     droeschl 6643: }
1.698     harmsja  6644: 
1.911     bisitz   6645: h2,
                   6646: h3,
                   6647: h4,
                   6648: h5,
                   6649: h6 {
                   6650:   margin: 5px 0 5px 0;
                   6651:   padding: 0;
                   6652:   line-height:130%;
1.693     droeschl 6653: }
1.795     www      6654: 
                   6655: .LC_hcell {
1.911     bisitz   6656:   padding:3px 15px 3px 15px;
                   6657:   margin: 0;
                   6658:   background-color:$tabbg;
                   6659:   color:$fontmenu;
                   6660:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6661: }
1.795     www      6662: 
1.840     bisitz   6663: .LC_Box > .LC_hcell {
1.911     bisitz   6664:   margin: 0 -10px 10px -10px;
1.835     bisitz   6665: }
                   6666: 
1.721     harmsja  6667: .LC_noBorder {
1.911     bisitz   6668:   border: 0;
1.698     harmsja  6669: }
1.693     droeschl 6670: 
1.721     harmsja  6671: .LC_FormSectionClearButton input {
1.911     bisitz   6672:   background-color:transparent;
                   6673:   border: none;
                   6674:   cursor:pointer;
                   6675:   text-decoration:underline;
1.693     droeschl 6676: }
1.763     bisitz   6677: 
                   6678: .LC_help_open_topic {
1.911     bisitz   6679:   color: #FFFFFF;
                   6680:   background-color: #EEEEFF;
                   6681:   margin: 1px;
                   6682:   padding: 4px;
                   6683:   border: 1px solid #000033;
                   6684:   white-space: nowrap;
                   6685:   /* vertical-align: middle; */
1.759     neumanie 6686: }
1.693     droeschl 6687: 
1.911     bisitz   6688: dl,
                   6689: ul,
                   6690: div,
                   6691: fieldset {
                   6692:   margin: 10px 10px 10px 0;
                   6693:   /* overflow: hidden; */
1.693     droeschl 6694: }
1.795     www      6695: 
1.1075.2.90  raeburn  6696: article.geogebraweb div {
                   6697:     margin: 0;
                   6698: }
                   6699: 
1.838     bisitz   6700: fieldset > legend {
1.911     bisitz   6701:   font-weight: bold;
                   6702:   padding: 0 5px 0 5px;
1.838     bisitz   6703: }
                   6704: 
1.813     bisitz   6705: #LC_nav_bar {
1.911     bisitz   6706:   float: left;
1.995     raeburn  6707:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6708:   margin: 0 0 2px 0;
1.807     droeschl 6709: }
                   6710: 
1.916     droeschl 6711: #LC_realm {
                   6712:   margin: 0.2em 0 0 0;
                   6713:   padding: 0;
                   6714:   font-weight: bold;
                   6715:   text-align: center;
1.995     raeburn  6716:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6717: }
                   6718: 
1.911     bisitz   6719: #LC_nav_bar em {
                   6720:   font-weight: bold;
                   6721:   font-style: normal;
1.807     droeschl 6722: }
                   6723: 
1.897     wenzelju 6724: ol.LC_primary_menu {
1.934     droeschl 6725:   margin: 0;
1.1075.2.2  raeburn  6726:   padding: 0;
1.995     raeburn  6727:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6728: }
                   6729: 
1.852     droeschl 6730: ol#LC_PathBreadcrumbs {
1.911     bisitz   6731:   margin: 0;
1.693     droeschl 6732: }
                   6733: 
1.897     wenzelju 6734: ol.LC_primary_menu li {
1.1075.2.2  raeburn  6735:   color: RGB(80, 80, 80);
                   6736:   vertical-align: middle;
                   6737:   text-align: left;
                   6738:   list-style: none;
                   6739:   float: left;
                   6740: }
                   6741: 
                   6742: ol.LC_primary_menu li a {
                   6743:   display: block;
                   6744:   margin: 0;
                   6745:   padding: 0 5px 0 10px;
                   6746:   text-decoration: none;
                   6747: }
                   6748: 
                   6749: ol.LC_primary_menu li ul {
                   6750:   display: none;
                   6751:   width: 10em;
                   6752:   background-color: $data_table_light;
                   6753: }
                   6754: 
                   6755: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6756:   display: block;
                   6757:   position: absolute;
                   6758:   margin: 0;
                   6759:   padding: 0;
1.1075.2.5  raeburn  6760:   z-index: 2;
1.1075.2.2  raeburn  6761: }
                   6762: 
                   6763: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6764:   font-size: 90%;
1.911     bisitz   6765:   vertical-align: top;
1.1075.2.2  raeburn  6766:   float: none;
1.1075.2.5  raeburn  6767:   border-left: 1px solid black;
                   6768:   border-right: 1px solid black;
1.1075.2.2  raeburn  6769: }
                   6770: 
                   6771: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1075.2.5  raeburn  6772:   background-color:$data_table_light;
1.1075.2.2  raeburn  6773: }
                   6774: 
                   6775: ol.LC_primary_menu li li a:hover {
                   6776:    color:$button_hover;
                   6777:    background-color:$data_table_dark;
1.693     droeschl 6778: }
                   6779: 
1.897     wenzelju 6780: ol.LC_primary_menu li img {
1.911     bisitz   6781:   vertical-align: bottom;
1.934     droeschl 6782:   height: 1.1em;
1.1075.2.3  raeburn  6783:   margin: 0.2em 0 0 0;
1.693     droeschl 6784: }
                   6785: 
1.897     wenzelju 6786: ol.LC_primary_menu a {
1.911     bisitz   6787:   color: RGB(80, 80, 80);
                   6788:   text-decoration: none;
1.693     droeschl 6789: }
1.795     www      6790: 
1.949     droeschl 6791: ol.LC_primary_menu a.LC_new_message {
                   6792:   font-weight:bold;
                   6793:   color: darkred;
                   6794: }
                   6795: 
1.975     raeburn  6796: ol.LC_docs_parameters {
                   6797:   margin-left: 0;
                   6798:   padding: 0;
                   6799:   list-style: none;
                   6800: }
                   6801: 
                   6802: ol.LC_docs_parameters li {
                   6803:   margin: 0;
                   6804:   padding-right: 20px;
                   6805:   display: inline;
                   6806: }
                   6807: 
1.976     raeburn  6808: ol.LC_docs_parameters li:before {
                   6809:   content: "\\002022 \\0020";
                   6810: }
                   6811: 
                   6812: li.LC_docs_parameters_title {
                   6813:   font-weight: bold;
                   6814: }
                   6815: 
                   6816: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6817:   content: "";
                   6818: }
                   6819: 
1.897     wenzelju 6820: ul#LC_secondary_menu {
1.1075.2.23  raeburn  6821:   clear: right;
1.911     bisitz   6822:   color: $fontmenu;
                   6823:   background: $tabbg;
                   6824:   list-style: none;
                   6825:   padding: 0;
                   6826:   margin: 0;
                   6827:   width: 100%;
1.995     raeburn  6828:   text-align: left;
1.1075.2.4  raeburn  6829:   float: left;
1.808     droeschl 6830: }
                   6831: 
1.897     wenzelju 6832: ul#LC_secondary_menu li {
1.911     bisitz   6833:   font-weight: bold;
                   6834:   line-height: 1.8em;
                   6835:   border-right: 1px solid black;
                   6836:   vertical-align: middle;
1.1075.2.4  raeburn  6837:   float: left;
                   6838: }
                   6839: 
                   6840: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6841:   background-color: $data_table_light;
                   6842: }
                   6843: 
                   6844: ul#LC_secondary_menu li a {
                   6845:   padding: 0 0.8em;
                   6846: }
                   6847: 
                   6848: ul#LC_secondary_menu li ul {
                   6849:   display: none;
                   6850: }
                   6851: 
                   6852: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6853:   display: block;
                   6854:   position: absolute;
                   6855:   margin: 0;
                   6856:   padding: 0;
                   6857:   list-style:none;
                   6858:   float: none;
                   6859:   background-color: $data_table_light;
1.1075.2.5  raeburn  6860:   z-index: 2;
1.1075.2.10  raeburn  6861:   margin-left: -1px;
1.1075.2.4  raeburn  6862: }
                   6863: 
                   6864: ul#LC_secondary_menu li ul li {
                   6865:   font-size: 90%;
                   6866:   vertical-align: top;
                   6867:   border-left: 1px solid black;
                   6868:   border-right: 1px solid black;
1.1075.2.33  raeburn  6869:   background-color: $data_table_light;
1.1075.2.4  raeburn  6870:   list-style:none;
                   6871:   float: none;
                   6872: }
                   6873: 
                   6874: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6875:   background-color: $data_table_dark;
1.807     droeschl 6876: }
                   6877: 
1.847     tempelho 6878: ul.LC_TabContent {
1.911     bisitz   6879:   display:block;
                   6880:   background: $sidebg;
                   6881:   border-bottom: solid 1px $lg_border_color;
                   6882:   list-style:none;
1.1020    raeburn  6883:   margin: -1px -10px 0 -10px;
1.911     bisitz   6884:   padding: 0;
1.693     droeschl 6885: }
                   6886: 
1.795     www      6887: ul.LC_TabContent li,
                   6888: ul.LC_TabContentBigger li {
1.911     bisitz   6889:   float:left;
1.741     harmsja  6890: }
1.795     www      6891: 
1.897     wenzelju 6892: ul#LC_secondary_menu li a {
1.911     bisitz   6893:   color: $fontmenu;
                   6894:   text-decoration: none;
1.693     droeschl 6895: }
1.795     www      6896: 
1.721     harmsja  6897: ul.LC_TabContent {
1.952     onken    6898:   min-height:20px;
1.721     harmsja  6899: }
1.795     www      6900: 
                   6901: ul.LC_TabContent li {
1.911     bisitz   6902:   vertical-align:middle;
1.959     onken    6903:   padding: 0 16px 0 10px;
1.911     bisitz   6904:   background-color:$tabbg;
                   6905:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6906:   border-left: solid 1px $font;
1.721     harmsja  6907: }
1.795     www      6908: 
1.847     tempelho 6909: ul.LC_TabContent .right {
1.911     bisitz   6910:   float:right;
1.847     tempelho 6911: }
                   6912: 
1.911     bisitz   6913: ul.LC_TabContent li a,
                   6914: ul.LC_TabContent li {
                   6915:   color:rgb(47,47,47);
                   6916:   text-decoration:none;
                   6917:   font-size:95%;
                   6918:   font-weight:bold;
1.952     onken    6919:   min-height:20px;
                   6920: }
                   6921: 
1.959     onken    6922: ul.LC_TabContent li a:hover,
                   6923: ul.LC_TabContent li a:focus {
1.952     onken    6924:   color: $button_hover;
1.959     onken    6925:   background:none;
                   6926:   outline:none;
1.952     onken    6927: }
                   6928: 
                   6929: ul.LC_TabContent li:hover {
                   6930:   color: $button_hover;
                   6931:   cursor:pointer;
1.721     harmsja  6932: }
1.795     www      6933: 
1.911     bisitz   6934: ul.LC_TabContent li.active {
1.952     onken    6935:   color: $font;
1.911     bisitz   6936:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6937:   border-bottom:solid 1px #FFFFFF;
                   6938:   cursor: default;
1.744     ehlerst  6939: }
1.795     www      6940: 
1.959     onken    6941: ul.LC_TabContent li.active a {
                   6942:   color:$font;
                   6943:   background:#FFFFFF;
                   6944:   outline: none;
                   6945: }
1.1047    raeburn  6946: 
                   6947: ul.LC_TabContent li.goback {
                   6948:   float: left;
                   6949:   border-left: none;
                   6950: }
                   6951: 
1.870     tempelho 6952: #maincoursedoc {
1.911     bisitz   6953:   clear:both;
1.870     tempelho 6954: }
                   6955: 
                   6956: ul.LC_TabContentBigger {
1.911     bisitz   6957:   display:block;
                   6958:   list-style:none;
                   6959:   padding: 0;
1.870     tempelho 6960: }
                   6961: 
1.795     www      6962: ul.LC_TabContentBigger li {
1.911     bisitz   6963:   vertical-align:bottom;
                   6964:   height: 30px;
                   6965:   font-size:110%;
                   6966:   font-weight:bold;
                   6967:   color: #737373;
1.841     tempelho 6968: }
                   6969: 
1.957     onken    6970: ul.LC_TabContentBigger li.active {
                   6971:   position: relative;
                   6972:   top: 1px;
                   6973: }
                   6974: 
1.870     tempelho 6975: ul.LC_TabContentBigger li a {
1.911     bisitz   6976:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6977:   height: 30px;
                   6978:   line-height: 30px;
                   6979:   text-align: center;
                   6980:   display: block;
                   6981:   text-decoration: none;
1.958     onken    6982:   outline: none;  
1.741     harmsja  6983: }
1.795     www      6984: 
1.870     tempelho 6985: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6986:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6987:   color:$font;
1.744     ehlerst  6988: }
1.795     www      6989: 
1.870     tempelho 6990: ul.LC_TabContentBigger li b {
1.911     bisitz   6991:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6992:   display: block;
                   6993:   float: left;
                   6994:   padding: 0 30px;
1.957     onken    6995:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6996: }
                   6997: 
1.956     onken    6998: ul.LC_TabContentBigger li:hover b {
                   6999:   color:$button_hover;
                   7000: }
                   7001: 
1.870     tempelho 7002: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7003:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7004:   color:$font;
1.957     onken    7005:   border: 0;
1.741     harmsja  7006: }
1.693     droeschl 7007: 
1.870     tempelho 7008: 
1.862     bisitz   7009: ul.LC_CourseBreadcrumbs {
                   7010:   background: $sidebg;
1.1020    raeburn  7011:   height: 2em;
1.862     bisitz   7012:   padding-left: 10px;
1.1020    raeburn  7013:   margin: 0;
1.862     bisitz   7014:   list-style-position: inside;
                   7015: }
                   7016: 
1.911     bisitz   7017: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7018: ol#LC_PathBreadcrumbs {
1.911     bisitz   7019:   padding-left: 10px;
                   7020:   margin: 0;
1.933     droeschl 7021:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7022: }
                   7023: 
1.911     bisitz   7024: ol#LC_MenuBreadcrumbs li,
                   7025: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7026: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7027:   display: inline;
1.933     droeschl 7028:   white-space: normal;  
1.693     droeschl 7029: }
                   7030: 
1.823     bisitz   7031: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7032: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7033:   text-decoration: none;
                   7034:   font-size:90%;
1.693     droeschl 7035: }
1.795     www      7036: 
1.969     droeschl 7037: ol#LC_MenuBreadcrumbs h1 {
                   7038:   display: inline;
                   7039:   font-size: 90%;
                   7040:   line-height: 2.5em;
                   7041:   margin: 0;
                   7042:   padding: 0;
                   7043: }
                   7044: 
1.795     www      7045: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7046:   text-decoration:none;
                   7047:   font-size:100%;
                   7048:   font-weight:bold;
1.693     droeschl 7049: }
1.795     www      7050: 
1.840     bisitz   7051: .LC_Box {
1.911     bisitz   7052:   border: solid 1px $lg_border_color;
                   7053:   padding: 0 10px 10px 10px;
1.746     neumanie 7054: }
1.795     www      7055: 
1.1020    raeburn  7056: .LC_DocsBox {
                   7057:   border: solid 1px $lg_border_color;
                   7058:   padding: 0 0 10px 10px;
                   7059: }
                   7060: 
1.795     www      7061: .LC_AboutMe_Image {
1.911     bisitz   7062:   float:left;
                   7063:   margin-right:10px;
1.747     neumanie 7064: }
1.795     www      7065: 
                   7066: .LC_Clear_AboutMe_Image {
1.911     bisitz   7067:   clear:left;
1.747     neumanie 7068: }
1.795     www      7069: 
1.721     harmsja  7070: dl.LC_ListStyleClean dt {
1.911     bisitz   7071:   padding-right: 5px;
                   7072:   display: table-header-group;
1.693     droeschl 7073: }
                   7074: 
1.721     harmsja  7075: dl.LC_ListStyleClean dd {
1.911     bisitz   7076:   display: table-row;
1.693     droeschl 7077: }
                   7078: 
1.721     harmsja  7079: .LC_ListStyleClean,
                   7080: .LC_ListStyleSimple,
                   7081: .LC_ListStyleNormal,
1.795     www      7082: .LC_ListStyleSpecial {
1.911     bisitz   7083:   /* display:block; */
                   7084:   list-style-position: inside;
                   7085:   list-style-type: none;
                   7086:   overflow: hidden;
                   7087:   padding: 0;
1.693     droeschl 7088: }
                   7089: 
1.721     harmsja  7090: .LC_ListStyleSimple li,
                   7091: .LC_ListStyleSimple dd,
                   7092: .LC_ListStyleNormal li,
                   7093: .LC_ListStyleNormal dd,
                   7094: .LC_ListStyleSpecial li,
1.795     www      7095: .LC_ListStyleSpecial dd {
1.911     bisitz   7096:   margin: 0;
                   7097:   padding: 5px 5px 5px 10px;
                   7098:   clear: both;
1.693     droeschl 7099: }
                   7100: 
1.721     harmsja  7101: .LC_ListStyleClean li,
                   7102: .LC_ListStyleClean dd {
1.911     bisitz   7103:   padding-top: 0;
                   7104:   padding-bottom: 0;
1.693     droeschl 7105: }
                   7106: 
1.721     harmsja  7107: .LC_ListStyleSimple dd,
1.795     www      7108: .LC_ListStyleSimple li {
1.911     bisitz   7109:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7110: }
                   7111: 
1.721     harmsja  7112: .LC_ListStyleSpecial li,
                   7113: .LC_ListStyleSpecial dd {
1.911     bisitz   7114:   list-style-type: none;
                   7115:   background-color: RGB(220, 220, 220);
                   7116:   margin-bottom: 4px;
1.693     droeschl 7117: }
                   7118: 
1.721     harmsja  7119: table.LC_SimpleTable {
1.911     bisitz   7120:   margin:5px;
                   7121:   border:solid 1px $lg_border_color;
1.795     www      7122: }
1.693     droeschl 7123: 
1.721     harmsja  7124: table.LC_SimpleTable tr {
1.911     bisitz   7125:   padding: 0;
                   7126:   border:solid 1px $lg_border_color;
1.693     droeschl 7127: }
1.795     www      7128: 
                   7129: table.LC_SimpleTable thead {
1.911     bisitz   7130:   background:rgb(220,220,220);
1.693     droeschl 7131: }
                   7132: 
1.721     harmsja  7133: div.LC_columnSection {
1.911     bisitz   7134:   display: block;
                   7135:   clear: both;
                   7136:   overflow: hidden;
                   7137:   margin: 0;
1.693     droeschl 7138: }
                   7139: 
1.721     harmsja  7140: div.LC_columnSection>* {
1.911     bisitz   7141:   float: left;
                   7142:   margin: 10px 20px 10px 0;
                   7143:   overflow:hidden;
1.693     droeschl 7144: }
1.721     harmsja  7145: 
1.795     www      7146: table em {
1.911     bisitz   7147:   font-weight: bold;
                   7148:   font-style: normal;
1.748     schulted 7149: }
1.795     www      7150: 
1.779     bisitz   7151: table.LC_tableBrowseRes,
1.795     www      7152: table.LC_tableOfContent {
1.911     bisitz   7153:   border:none;
                   7154:   border-spacing: 1px;
                   7155:   padding: 3px;
                   7156:   background-color: #FFFFFF;
                   7157:   font-size: 90%;
1.753     droeschl 7158: }
1.789     droeschl 7159: 
1.911     bisitz   7160: table.LC_tableOfContent {
                   7161:   border-collapse: collapse;
1.789     droeschl 7162: }
                   7163: 
1.771     droeschl 7164: table.LC_tableBrowseRes a,
1.768     schulted 7165: table.LC_tableOfContent a {
1.911     bisitz   7166:   background-color: transparent;
                   7167:   text-decoration: none;
1.753     droeschl 7168: }
                   7169: 
1.795     www      7170: table.LC_tableOfContent img {
1.911     bisitz   7171:   border: none;
                   7172:   height: 1.3em;
                   7173:   vertical-align: text-bottom;
                   7174:   margin-right: 0.3em;
1.753     droeschl 7175: }
1.757     schulted 7176: 
1.795     www      7177: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7178:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7179: }
                   7180: 
1.795     www      7181: a#LC_content_toolbar_everything {
1.911     bisitz   7182:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7183: }
                   7184: 
1.795     www      7185: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7186:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7187: }
                   7188: 
1.795     www      7189: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7190:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7191: }
                   7192: 
1.795     www      7193: a#LC_content_toolbar_changefolder {
1.911     bisitz   7194:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7195: }
                   7196: 
1.795     www      7197: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7198:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7199: }
                   7200: 
1.1043    raeburn  7201: a#LC_content_toolbar_edittoplevel {
                   7202:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7203: }
                   7204: 
1.795     www      7205: ul#LC_toolbar li a:hover {
1.911     bisitz   7206:   background-position: bottom center;
1.757     schulted 7207: }
                   7208: 
1.795     www      7209: ul#LC_toolbar {
1.911     bisitz   7210:   padding: 0;
                   7211:   margin: 2px;
                   7212:   list-style:none;
                   7213:   position:relative;
                   7214:   background-color:white;
1.1075.2.9  raeburn  7215:   overflow: auto;
1.757     schulted 7216: }
                   7217: 
1.795     www      7218: ul#LC_toolbar li {
1.911     bisitz   7219:   border:1px solid white;
                   7220:   padding: 0;
                   7221:   margin: 0;
                   7222:   float: left;
                   7223:   display:inline;
                   7224:   vertical-align:middle;
1.1075.2.9  raeburn  7225:   white-space: nowrap;
1.911     bisitz   7226: }
1.757     schulted 7227: 
1.783     amueller 7228: 
1.795     www      7229: a.LC_toolbarItem {
1.911     bisitz   7230:   display:block;
                   7231:   padding: 0;
                   7232:   margin: 0;
                   7233:   height: 32px;
                   7234:   width: 32px;
                   7235:   color:white;
                   7236:   border: none;
                   7237:   background-repeat:no-repeat;
                   7238:   background-color:transparent;
1.757     schulted 7239: }
                   7240: 
1.915     droeschl 7241: ul.LC_funclist {
                   7242:     margin: 0;
                   7243:     padding: 0.5em 1em 0.5em 0;
                   7244: }
                   7245: 
1.933     droeschl 7246: ul.LC_funclist > li:first-child {
                   7247:     font-weight:bold; 
                   7248:     margin-left:0.8em;
                   7249: }
                   7250: 
1.915     droeschl 7251: ul.LC_funclist + ul.LC_funclist {
                   7252:     /* 
                   7253:        left border as a seperator if we have more than
                   7254:        one list 
                   7255:     */
                   7256:     border-left: 1px solid $sidebg;
                   7257:     /* 
                   7258:        this hides the left border behind the border of the 
                   7259:        outer box if element is wrapped to the next 'line' 
                   7260:     */
                   7261:     margin-left: -1px;
                   7262: }
                   7263: 
1.843     bisitz   7264: ul.LC_funclist li {
1.915     droeschl 7265:   display: inline;
1.782     bisitz   7266:   white-space: nowrap;
1.915     droeschl 7267:   margin: 0 0 0 25px;
                   7268:   line-height: 150%;
1.782     bisitz   7269: }
                   7270: 
1.974     wenzelju 7271: .LC_hidden {
                   7272:   display: none;
                   7273: }
                   7274: 
1.1030    www      7275: .LCmodal-overlay {
                   7276: 		position:fixed;
                   7277: 		top:0;
                   7278: 		right:0;
                   7279: 		bottom:0;
                   7280: 		left:0;
                   7281: 		height:100%;
                   7282: 		width:100%;
                   7283: 		margin:0;
                   7284: 		padding:0;
                   7285: 		background:#999;
                   7286: 		opacity:.75;
                   7287: 		filter: alpha(opacity=75);
                   7288: 		-moz-opacity: 0.75;
                   7289: 		z-index:101;
                   7290: }
                   7291: 
                   7292: * html .LCmodal-overlay {   
                   7293: 		position: absolute;
                   7294: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7295: }
                   7296: 
                   7297: .LCmodal-window {
                   7298: 		position:fixed;
                   7299: 		top:50%;
                   7300: 		left:50%;
                   7301: 		margin:0;
                   7302: 		padding:0;
                   7303: 		z-index:102;
                   7304: 	}
                   7305: 
                   7306: * html .LCmodal-window {
                   7307: 		position:absolute;
                   7308: }
                   7309: 
                   7310: .LCclose-window {
                   7311: 		position:absolute;
                   7312: 		width:32px;
                   7313: 		height:32px;
                   7314: 		right:8px;
                   7315: 		top:8px;
                   7316: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7317: 		text-indent:-99999px;
                   7318: 		overflow:hidden;
                   7319: 		cursor:pointer;
                   7320: }
                   7321: 
1.1075.2.17  raeburn  7322: /*
                   7323:   styles used by TTH when "Default set of options to pass to tth/m
                   7324:   when converting TeX" in course settings has been set
                   7325: 
                   7326:   option passed: -t
                   7327: 
                   7328: */
                   7329: 
                   7330: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7331: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7332: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7333: td div.norm {line-height:normal;}
                   7334: 
                   7335: /*
                   7336:   option passed -y3
                   7337: */
                   7338: 
                   7339: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7340: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7341: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7342: 
1.343     albertel 7343: END
                   7344: }
                   7345: 
1.306     albertel 7346: =pod
                   7347: 
                   7348: =item * &headtag()
                   7349: 
                   7350: Returns a uniform footer for LON-CAPA web pages.
                   7351: 
1.307     albertel 7352: Inputs: $title - optional title for the head
                   7353:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7354:         $args - optional arguments
1.319     albertel 7355:             force_register - if is true call registerurl so the remote is 
                   7356:                              informed
1.415     albertel 7357:             redirect       -> array ref of
                   7358:                                    1- seconds before redirect occurs
                   7359:                                    2- url to redirect to
                   7360:                                    3- whether the side effect should occur
1.315     albertel 7361:                            (side effect of setting 
                   7362:                                $env{'internal.head.redirect'} to the url 
                   7363:                                redirected too)
1.352     albertel 7364:             domain         -> force to color decorate a page for a specific
                   7365:                                domain
                   7366:             function       -> force usage of a specific rolish color scheme
                   7367:             bgcolor        -> override the default page bgcolor
1.460     albertel 7368:             no_auto_mt_title
                   7369:                            -> prevent &mt()ing the title arg
1.464     albertel 7370: 
1.306     albertel 7371: =cut
                   7372: 
                   7373: sub headtag {
1.313     albertel 7374:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7375:     
1.363     albertel 7376:     my $function = $args->{'function'} || &get_users_function();
                   7377:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7378:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7379:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7380:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7381: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7382: 		   #time(),
1.418     albertel 7383: 		   $env{'environment.color.timestamp'},
1.363     albertel 7384: 		   $function,$domain,$bgcolor);
                   7385: 
1.369     www      7386:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7387: 
1.308     albertel 7388:     my $result =
                   7389: 	'<head>'.
1.1075.2.56  raeburn  7390: 	&font_settings($args);
1.319     albertel 7391: 
1.1075.2.72  raeburn  7392:     my $inhibitprint;
                   7393:     if ($args->{'print_suppress'}) {
                   7394:         $inhibitprint = &print_suppression();
                   7395:     }
1.1064    raeburn  7396: 
1.461     albertel 7397:     if (!$args->{'frameset'}) {
                   7398: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7399:     }
1.1075.2.12  raeburn  7400:     if ($args->{'force_register'}) {
                   7401:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7402:     }
1.436     albertel 7403:     if (!$args->{'no_nav_bar'} 
                   7404: 	&& !$args->{'only_body'}
                   7405: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7406: 	$result .= &help_menu_js($httphost);
1.1032    www      7407:         $result.=&modal_window();
1.1038    www      7408:         $result.=&togglebox_script();
1.1034    www      7409:         $result.=&wishlist_window();
1.1041    www      7410:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7411:     } else {
                   7412:         if ($args->{'add_modal'}) {
                   7413:            $result.=&modal_window();
                   7414:         }
                   7415:         if ($args->{'add_wishlist'}) {
                   7416:            $result.=&wishlist_window();
                   7417:         }
1.1038    www      7418:         if ($args->{'add_togglebox'}) {
                   7419:            $result.=&togglebox_script();
                   7420:         }
1.1041    www      7421:         if ($args->{'add_progressbar'}) {
                   7422:            $result.=&LCprogressbarUpdate_script();
                   7423:         }
1.436     albertel 7424:     }
1.314     albertel 7425:     if (ref($args->{'redirect'})) {
1.414     albertel 7426: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7427: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7428: 	if (!$inhibit_continue) {
                   7429: 	    $env{'internal.head.redirect'} = $url;
                   7430: 	}
1.313     albertel 7431: 	$result.=<<ADDMETA
                   7432: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7433: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7434: ADDMETA
1.1075.2.89  raeburn  7435:     } else {
                   7436:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7437:             my $requrl = $env{'request.uri'};
                   7438:             if ($requrl eq '') {
                   7439:                 $requrl = $ENV{'REQUEST_URI'};
                   7440:                 $requrl =~ s/\?.+$//;
                   7441:             }
                   7442:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7443:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7444:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7445:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7446:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7447:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7448:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7449:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7450:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7451:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7452:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7453:                                 my $numsec = 5;
                   7454:                                 my $timeout = $numsec * 1000;
                   7455:                                 my ($newurl,$locknum,%locks,$msg);
                   7456:                                 if ($env{'request.role.adv'}) {
                   7457:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7458:                                 }
                   7459:                                 my $disable_submit = 0;
                   7460:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7461:                                     $disable_submit = 1;
                   7462:                                 }
                   7463:                                 if ($locknum) {
                   7464:                                     my @lockinfo = sort(values(%locks));
                   7465:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7466:                                            join(", ",sort(values(%locks)))."\\n".
                   7467:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7468:                                 } else {
                   7469:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7470:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7471:                                     }
                   7472:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7473:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7474:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7475:                                         $newurl .= '&role='.$env{'request.role'};
                   7476:                                     }
                   7477:                                     if ($env{'request.symb'}) {
                   7478:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7479:                                     } else {
                   7480:                                         $newurl .= '&origurl='.$requrl;
                   7481:                                     }
                   7482:                                 }
                   7483:                                 $result.=<<OFFLOAD
                   7484: <meta http-equiv="pragma" content="no-cache" />
                   7485: <script type="text/javascript">
1.1075.2.92! raeburn  7486: // <![CDATA[
1.1075.2.89  raeburn  7487: function LC_Offload_Now() {
                   7488:     var dest = "$newurl";
                   7489:     if (dest != '') {
                   7490:         window.location.href="$newurl";
                   7491:     }
                   7492: }
1.1075.2.92! raeburn  7493: \$(document).ready(function () {
        !          7494:     window.alert('$msg');
        !          7495:     if ($disable_submit) {
1.1075.2.89  raeburn  7496:         \$(".LC_hwk_submit").prop("disabled", true);
                   7497:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92! raeburn  7498:     }
        !          7499:     setTimeout('LC_Offload_Now()', $timeout);
        !          7500: });
        !          7501: // ]]>
1.1075.2.89  raeburn  7502: </script>
                   7503: OFFLOAD
                   7504:                             }
                   7505:                         }
                   7506:                     }
                   7507:                 }
                   7508:             }
                   7509:         }
1.313     albertel 7510:     }
1.306     albertel 7511:     if (!defined($title)) {
                   7512: 	$title = 'The LearningOnline Network with CAPA';
                   7513:     }
1.460     albertel 7514:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7515:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7516: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7517:     if (!$args->{'frameset'}) {
                   7518:         $result .= ' /';
                   7519:     }
                   7520:     $result .= '>'
1.1064    raeburn  7521:         .$inhibitprint
1.414     albertel 7522: 	.$head_extra;
1.1075.2.42  raeburn  7523:     if ($env{'browser.mobile'}) {
                   7524:         $result .= '
                   7525: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7526: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7527:     }
1.962     droeschl 7528:     return $result.'</head>';
1.306     albertel 7529: }
                   7530: 
                   7531: =pod
                   7532: 
1.340     albertel 7533: =item * &font_settings()
                   7534: 
                   7535: Returns neccessary <meta> to set the proper encoding
                   7536: 
1.1075.2.56  raeburn  7537: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7538: 
                   7539: =cut
                   7540: 
                   7541: sub font_settings {
1.1075.2.56  raeburn  7542:     my ($args) = @_;
1.340     albertel 7543:     my $headerstring='';
1.1075.2.56  raeburn  7544:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7545:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7546: 	$headerstring.=
1.1075.2.61  raeburn  7547: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7548:         if (!$args->{'frameset'}) {
                   7549:             $headerstring.= ' /';
                   7550:         }
                   7551:         $headerstring .= '>'."\n";
1.340     albertel 7552:     }
                   7553:     return $headerstring;
                   7554: }
                   7555: 
1.341     albertel 7556: =pod
                   7557: 
1.1064    raeburn  7558: =item * &print_suppression()
                   7559: 
                   7560: In course context returns css which causes the body to be blank when media="print",
                   7561: if printout generation is unavailable for the current resource.
                   7562: 
                   7563: This could be because:
                   7564: 
                   7565: (a) printstartdate is in the future
                   7566: 
                   7567: (b) printenddate is in the past
                   7568: 
                   7569: (c) there is an active exam block with "printout"
                   7570: functionality blocked
                   7571: 
                   7572: Users with pav, pfo or evb privileges are exempt.
                   7573: 
                   7574: Inputs: none
                   7575: 
                   7576: =cut
                   7577: 
                   7578: 
                   7579: sub print_suppression {
                   7580:     my $noprint;
                   7581:     if ($env{'request.course.id'}) {
                   7582:         my $scope = $env{'request.course.id'};
                   7583:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7584:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7585:             return;
                   7586:         }
                   7587:         if ($env{'request.course.sec'} ne '') {
                   7588:             $scope .= "/$env{'request.course.sec'}";
                   7589:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7590:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7591:                 return;
1.1064    raeburn  7592:             }
                   7593:         }
                   7594:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7595:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7596:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7597:         if ($blocked) {
                   7598:             my $checkrole = "cm./$cdom/$cnum";
                   7599:             if ($env{'request.course.sec'} ne '') {
                   7600:                 $checkrole .= "/$env{'request.course.sec'}";
                   7601:             }
                   7602:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7603:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7604:                 $noprint = 1;
                   7605:             }
                   7606:         }
                   7607:         unless ($noprint) {
                   7608:             my $symb = &Apache::lonnet::symbread();
                   7609:             if ($symb ne '') {
                   7610:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7611:                 if (ref($navmap)) {
                   7612:                     my $res = $navmap->getBySymb($symb);
                   7613:                     if (ref($res)) {
                   7614:                         if (!$res->resprintable()) {
                   7615:                             $noprint = 1;
                   7616:                         }
                   7617:                     }
                   7618:                 }
                   7619:             }
                   7620:         }
                   7621:         if ($noprint) {
                   7622:             return <<"ENDSTYLE";
                   7623: <style type="text/css" media="print">
                   7624:     body { display:none }
                   7625: </style>
                   7626: ENDSTYLE
                   7627:         }
                   7628:     }
                   7629:     return;
                   7630: }
                   7631: 
                   7632: =pod
                   7633: 
1.341     albertel 7634: =item * &xml_begin()
                   7635: 
                   7636: Returns the needed doctype and <html>
                   7637: 
                   7638: Inputs: none
                   7639: 
                   7640: =cut
                   7641: 
                   7642: sub xml_begin {
1.1075.2.61  raeburn  7643:     my ($is_frameset) = @_;
1.341     albertel 7644:     my $output='';
                   7645: 
                   7646:     if ($env{'browser.mathml'}) {
                   7647: 	$output='<?xml version="1.0"?>'
                   7648:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7649: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7650:             
                   7651: #	    .'<!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">] >'
                   7652: 	    .'<!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">'
                   7653:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7654: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  7655:     } elsif ($is_frameset) {
                   7656:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7657:                 '<html>'."\n";
1.341     albertel 7658:     } else {
1.1075.2.61  raeburn  7659: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7660:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7661:     }
                   7662:     return $output;
                   7663: }
1.340     albertel 7664: 
                   7665: =pod
                   7666: 
1.306     albertel 7667: =item * &start_page()
                   7668: 
                   7669: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7670: 
1.648     raeburn  7671: Inputs:
                   7672: 
                   7673: =over 4
                   7674: 
                   7675: $title - optional title for the page
                   7676: 
                   7677: $head_extra - optional extra HTML to incude inside the <head>
                   7678: 
                   7679: $args - additional optional args supported are:
                   7680: 
                   7681: =over 8
                   7682: 
                   7683:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7684:                                     arg on
1.814     bisitz   7685:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7686:              add_entries    -> additional attributes to add to the  <body>
                   7687:              domain         -> force to color decorate a page for a 
1.317     albertel 7688:                                     specific domain
1.648     raeburn  7689:              function       -> force usage of a specific rolish color
1.317     albertel 7690:                                     scheme
1.648     raeburn  7691:              redirect       -> see &headtag()
                   7692:              bgcolor        -> override the default page bg color
                   7693:              js_ready       -> return a string ready for being used in 
1.317     albertel 7694:                                     a javascript writeln
1.648     raeburn  7695:              html_encode    -> return a string ready for being used in 
1.320     albertel 7696:                                     a html attribute
1.648     raeburn  7697:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7698:                                     $forcereg arg
1.648     raeburn  7699:              frameset       -> if true will start with a <frameset>
1.330     albertel 7700:                                     rather than <body>
1.648     raeburn  7701:              skip_phases    -> hash ref of 
1.338     albertel 7702:                                     head -> skip the <html><head> generation
                   7703:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  7704:              no_inline_link -> if true and in remote mode, don't show the
                   7705:                                     'Switch To Inline Menu' link
1.648     raeburn  7706:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7707:              inherit_jsmath -> when creating popup window in a page,
                   7708:                                     should it have jsmath forced on by the
                   7709:                                     current page
1.867     kalberla 7710:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7711:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  7712:              group          -> includes the current group, if page is for a
                   7713:                                specific group
1.361     albertel 7714: 
1.648     raeburn  7715: =back
1.460     albertel 7716: 
1.648     raeburn  7717: =back
1.562     albertel 7718: 
1.306     albertel 7719: =cut
                   7720: 
                   7721: sub start_page {
1.309     albertel 7722:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7723:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7724: 
1.315     albertel 7725:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  7726:     my ($result,@advtools);
1.964     droeschl 7727: 
1.338     albertel 7728:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  7729:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 7730:     }
                   7731:     
                   7732:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7733: 	if ($args->{'frameset'}) {
                   7734: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7735: 						$args->{'add_entries'});
                   7736: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7737:         } else {
                   7738:             $result .=
                   7739:                 &bodytag($title, 
                   7740:                          $args->{'function'},       $args->{'add_entries'},
                   7741:                          $args->{'only_body'},      $args->{'domain'},
                   7742:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  7743:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  7744:                          $args,                     \@advtools);
1.831     bisitz   7745:         }
1.330     albertel 7746:     }
1.338     albertel 7747: 
1.315     albertel 7748:     if ($args->{'js_ready'}) {
1.713     kaisler  7749: 		$result = &js_ready($result);
1.315     albertel 7750:     }
1.320     albertel 7751:     if ($args->{'html_encode'}) {
1.713     kaisler  7752: 		$result = &html_encode($result);
                   7753:     }
                   7754: 
1.813     bisitz   7755:     # Preparation for new and consistent functionlist at top of screen
                   7756:     # if ($args->{'functionlist'}) {
                   7757:     #            $result .= &build_functionlist();
                   7758:     #}
                   7759: 
1.964     droeschl 7760:     # Don't add anything more if only_body wanted or in const space
                   7761:     return $result if    $args->{'only_body'} 
                   7762:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7763: 
                   7764:     #Breadcrumbs
1.758     kaisler  7765:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7766: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7767: 		#if any br links exists, add them to the breadcrumbs
                   7768: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7769: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7770: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7771: 			}
                   7772: 		}
1.1075.2.19  raeburn  7773:                 # if @advtools array contains items add then to the breadcrumbs
                   7774:                 if (@advtools > 0) {
                   7775:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7776:                 }
1.758     kaisler  7777: 
                   7778: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7779: 		if(exists($args->{'bread_crumbs_component'})){
                   7780: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7781: 		}else{
                   7782: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7783: 		}
1.1075.2.24  raeburn  7784:     } elsif (($env{'environment.remote'} eq 'on') &&
                   7785:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   7786:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   7787:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  7788:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 7789:     }
1.315     albertel 7790:     return $result;
1.306     albertel 7791: }
                   7792: 
                   7793: sub end_page {
1.315     albertel 7794:     my ($args) = @_;
                   7795:     $env{'internal.end_page'}++;
1.330     albertel 7796:     my $result;
1.335     albertel 7797:     if ($args->{'discussion'}) {
                   7798: 	my ($target,$parser);
                   7799: 	if (ref($args->{'discussion'})) {
                   7800: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7801: 				$args->{'discussion'}{'parser'});
                   7802: 	}
                   7803: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7804:     }
1.330     albertel 7805:     if ($args->{'frameset'}) {
                   7806: 	$result .= '</frameset>';
                   7807:     } else {
1.635     raeburn  7808: 	$result .= &endbodytag($args);
1.330     albertel 7809:     }
1.1075.2.6  raeburn  7810:     unless ($args->{'notbody'}) {
                   7811:         $result .= "\n</html>";
                   7812:     }
1.330     albertel 7813: 
1.315     albertel 7814:     if ($args->{'js_ready'}) {
1.317     albertel 7815: 	$result = &js_ready($result);
1.315     albertel 7816:     }
1.335     albertel 7817: 
1.320     albertel 7818:     if ($args->{'html_encode'}) {
                   7819: 	$result = &html_encode($result);
                   7820:     }
1.335     albertel 7821: 
1.315     albertel 7822:     return $result;
                   7823: }
                   7824: 
1.1034    www      7825: sub wishlist_window {
                   7826:     return(<<'ENDWISHLIST');
1.1046    raeburn  7827: <script type="text/javascript">
1.1034    www      7828: // <![CDATA[
                   7829: // <!-- BEGIN LON-CAPA Internal
                   7830: function set_wishlistlink(title, path) {
                   7831:     if (!title) {
                   7832:         title = document.title;
                   7833:         title = title.replace(/^LON-CAPA /,'');
                   7834:     }
1.1075.2.65  raeburn  7835:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  7836:     title = title.replace("'","\\\'");
1.1034    www      7837:     if (!path) {
                   7838:         path = location.pathname;
                   7839:     }
1.1075.2.65  raeburn  7840:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  7841:     path = path.replace("'","\\\'");
1.1034    www      7842:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7843:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7844: }
                   7845: // END LON-CAPA Internal -->
                   7846: // ]]>
                   7847: </script>
                   7848: ENDWISHLIST
                   7849: }
                   7850: 
1.1030    www      7851: sub modal_window {
                   7852:     return(<<'ENDMODAL');
1.1046    raeburn  7853: <script type="text/javascript">
1.1030    www      7854: // <![CDATA[
                   7855: // <!-- BEGIN LON-CAPA Internal
                   7856: var modalWindow = {
                   7857: 	parent:"body",
                   7858: 	windowId:null,
                   7859: 	content:null,
                   7860: 	width:null,
                   7861: 	height:null,
                   7862: 	close:function()
                   7863: 	{
                   7864: 	        $(".LCmodal-window").remove();
                   7865: 	        $(".LCmodal-overlay").remove();
                   7866: 	},
                   7867: 	open:function()
                   7868: 	{
                   7869: 		var modal = "";
                   7870: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7871: 		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;\">";
                   7872: 		modal += this.content;
                   7873: 		modal += "</div>";	
                   7874: 
                   7875: 		$(this.parent).append(modal);
                   7876: 
                   7877: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7878: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7879: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7880: 	}
                   7881: };
1.1075.2.42  raeburn  7882: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      7883: 	{
1.1075.2.83  raeburn  7884:                 source = source.replace("'","&#39;");
1.1030    www      7885: 		modalWindow.windowId = "myModal";
                   7886: 		modalWindow.width = width;
                   7887: 		modalWindow.height = height;
1.1075.2.80  raeburn  7888: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      7889: 		modalWindow.open();
1.1075.2.87  raeburn  7890: 	};
1.1030    www      7891: // END LON-CAPA Internal -->
                   7892: // ]]>
                   7893: </script>
                   7894: ENDMODAL
                   7895: }
                   7896: 
                   7897: sub modal_link {
1.1075.2.42  raeburn  7898:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      7899:     unless ($width) { $width=480; }
                   7900:     unless ($height) { $height=400; }
1.1031    www      7901:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  7902:     unless ($transparency) { $transparency='true'; }
                   7903: 
1.1074    raeburn  7904:     my $target_attr;
                   7905:     if (defined($target)) {
                   7906:         $target_attr = 'target="'.$target.'"';
                   7907:     }
                   7908:     return <<"ENDLINK";
1.1075.2.42  raeburn  7909: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  7910:            $linktext</a>
                   7911: ENDLINK
1.1030    www      7912: }
                   7913: 
1.1032    www      7914: sub modal_adhoc_script {
                   7915:     my ($funcname,$width,$height,$content)=@_;
                   7916:     return (<<ENDADHOC);
1.1046    raeburn  7917: <script type="text/javascript">
1.1032    www      7918: // <![CDATA[
                   7919:         var $funcname = function()
                   7920:         {
                   7921:                 modalWindow.windowId = "myModal";
                   7922:                 modalWindow.width = $width;
                   7923:                 modalWindow.height = $height;
                   7924:                 modalWindow.content = '$content';
                   7925:                 modalWindow.open();
                   7926:         };  
                   7927: // ]]>
                   7928: </script>
                   7929: ENDADHOC
                   7930: }
                   7931: 
1.1041    www      7932: sub modal_adhoc_inner {
                   7933:     my ($funcname,$width,$height,$content)=@_;
                   7934:     my $innerwidth=$width-20;
                   7935:     $content=&js_ready(
1.1042    www      7936:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  7937:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   7938:                  $content.
1.1041    www      7939:                  &end_scrollbox().
1.1075.2.42  raeburn  7940:                  &end_page()
1.1041    www      7941:              );
                   7942:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7943: }
                   7944: 
                   7945: sub modal_adhoc_window {
                   7946:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7947:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7948:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7949: }
                   7950: 
                   7951: sub modal_adhoc_launch {
                   7952:     my ($funcname,$width,$height,$content)=@_;
                   7953:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7954: <script type="text/javascript">
                   7955: // <![CDATA[
                   7956: $funcname();
                   7957: // ]]>
                   7958: </script>
                   7959: ENDLAUNCH
                   7960: }
                   7961: 
                   7962: sub modal_adhoc_close {
                   7963:     return (<<ENDCLOSE);
                   7964: <script type="text/javascript">
                   7965: // <![CDATA[
                   7966: modalWindow.close();
                   7967: // ]]>
                   7968: </script>
                   7969: ENDCLOSE
                   7970: }
                   7971: 
1.1038    www      7972: sub togglebox_script {
                   7973:    return(<<ENDTOGGLE);
                   7974: <script type="text/javascript"> 
                   7975: // <![CDATA[
                   7976: function LCtoggleDisplay(id,hidetext,showtext) {
                   7977:    link = document.getElementById(id + "link").childNodes[0];
                   7978:    with (document.getElementById(id).style) {
                   7979:       if (display == "none" ) {
                   7980:           display = "inline";
                   7981:           link.nodeValue = hidetext;
                   7982:         } else {
                   7983:           display = "none";
                   7984:           link.nodeValue = showtext;
                   7985:        }
                   7986:    }
                   7987: }
                   7988: // ]]>
                   7989: </script>
                   7990: ENDTOGGLE
                   7991: }
                   7992: 
1.1039    www      7993: sub start_togglebox {
                   7994:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7995:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7996:     unless ($showtext) { $showtext=&mt('show'); }
                   7997:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7998:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7999:     return &start_data_table().
                   8000:            &start_data_table_header_row().
                   8001:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8002:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8003:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8004:            &end_data_table_header_row().
                   8005:            '<tr id="'.$id.'" style="display:none""><td>';
                   8006: }
                   8007: 
                   8008: sub end_togglebox {
                   8009:     return '</td></tr>'.&end_data_table();
                   8010: }
                   8011: 
1.1041    www      8012: sub LCprogressbar_script {
1.1045    www      8013:    my ($id)=@_;
1.1041    www      8014:    return(<<ENDPROGRESS);
                   8015: <script type="text/javascript">
                   8016: // <![CDATA[
1.1045    www      8017: \$('#progressbar$id').progressbar({
1.1041    www      8018:   value: 0,
                   8019:   change: function(event, ui) {
                   8020:     var newVal = \$(this).progressbar('option', 'value');
                   8021:     \$('.pblabel', this).text(LCprogressTxt);
                   8022:   }
                   8023: });
                   8024: // ]]>
                   8025: </script>
                   8026: ENDPROGRESS
                   8027: }
                   8028: 
                   8029: sub LCprogressbarUpdate_script {
                   8030:    return(<<ENDPROGRESSUPDATE);
                   8031: <style type="text/css">
                   8032: .ui-progressbar { position:relative; }
                   8033: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8034: </style>
                   8035: <script type="text/javascript">
                   8036: // <![CDATA[
1.1045    www      8037: var LCprogressTxt='---';
                   8038: 
                   8039: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8040:    LCprogressTxt=progresstext;
1.1045    www      8041:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8042: }
                   8043: // ]]>
                   8044: </script>
                   8045: ENDPROGRESSUPDATE
                   8046: }
                   8047: 
1.1042    www      8048: my $LClastpercent;
1.1045    www      8049: my $LCidcnt;
                   8050: my $LCcurrentid;
1.1042    www      8051: 
1.1041    www      8052: sub LCprogressbar {
1.1042    www      8053:     my ($r)=(@_);
                   8054:     $LClastpercent=0;
1.1045    www      8055:     $LCidcnt++;
                   8056:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8057:     my $starting=&mt('Starting');
                   8058:     my $content=(<<ENDPROGBAR);
1.1045    www      8059:   <div id="progressbar$LCcurrentid">
1.1041    www      8060:     <span class="pblabel">$starting</span>
                   8061:   </div>
                   8062: ENDPROGBAR
1.1045    www      8063:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8064: }
                   8065: 
                   8066: sub LCprogressbarUpdate {
1.1042    www      8067:     my ($r,$val,$text)=@_;
                   8068:     unless ($val) { 
                   8069:        if ($LClastpercent) {
                   8070:            $val=$LClastpercent;
                   8071:        } else {
                   8072:            $val=0;
                   8073:        }
                   8074:     }
1.1041    www      8075:     if ($val<0) { $val=0; }
                   8076:     if ($val>100) { $val=0; }
1.1042    www      8077:     $LClastpercent=$val;
1.1041    www      8078:     unless ($text) { $text=$val.'%'; }
                   8079:     $text=&js_ready($text);
1.1044    www      8080:     &r_print($r,<<ENDUPDATE);
1.1041    www      8081: <script type="text/javascript">
                   8082: // <![CDATA[
1.1045    www      8083: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8084: // ]]>
                   8085: </script>
                   8086: ENDUPDATE
1.1035    www      8087: }
                   8088: 
1.1042    www      8089: sub LCprogressbarClose {
                   8090:     my ($r)=@_;
                   8091:     $LClastpercent=0;
1.1044    www      8092:     &r_print($r,<<ENDCLOSE);
1.1042    www      8093: <script type="text/javascript">
                   8094: // <![CDATA[
1.1045    www      8095: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8096: // ]]>
                   8097: </script>
                   8098: ENDCLOSE
1.1044    www      8099: }
                   8100: 
                   8101: sub r_print {
                   8102:     my ($r,$to_print)=@_;
                   8103:     if ($r) {
                   8104:       $r->print($to_print);
                   8105:       $r->rflush();
                   8106:     } else {
                   8107:       print($to_print);
                   8108:     }
1.1042    www      8109: }
                   8110: 
1.320     albertel 8111: sub html_encode {
                   8112:     my ($result) = @_;
                   8113: 
1.322     albertel 8114:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8115:     
                   8116:     return $result;
                   8117: }
1.1044    www      8118: 
1.317     albertel 8119: sub js_ready {
                   8120:     my ($result) = @_;
                   8121: 
1.323     albertel 8122:     $result =~ s/[\n\r]/ /xmsg;
                   8123:     $result =~ s/\\/\\\\/xmsg;
                   8124:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8125:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8126:     
                   8127:     return $result;
                   8128: }
                   8129: 
1.315     albertel 8130: sub validate_page {
                   8131:     if (  exists($env{'internal.start_page'})
1.316     albertel 8132: 	  &&     $env{'internal.start_page'} > 1) {
                   8133: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8134: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8135: 				 $ENV{'request.filename'});
1.315     albertel 8136:     }
                   8137:     if (  exists($env{'internal.end_page'})
1.316     albertel 8138: 	  &&     $env{'internal.end_page'} > 1) {
                   8139: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8140: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8141: 				 $env{'request.filename'});
1.315     albertel 8142:     }
                   8143:     if (     exists($env{'internal.start_page'})
                   8144: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8145: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8146: 				 $env{'request.filename'});
1.315     albertel 8147:     }
                   8148:     if (   ! exists($env{'internal.start_page'})
                   8149: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8150: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8151: 				 $env{'request.filename'});
1.315     albertel 8152:     }
1.306     albertel 8153: }
1.315     albertel 8154: 
1.996     www      8155: 
                   8156: sub start_scrollbox {
1.1075.2.56  raeburn  8157:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8158:     unless ($outerwidth) { $outerwidth='520px'; }
                   8159:     unless ($width) { $width='500px'; }
                   8160:     unless ($height) { $height='200px'; }
1.1075    raeburn  8161:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8162:     if ($id ne '') {
1.1075.2.42  raeburn  8163:         $table_id = ' id="table_'.$id.'"';
                   8164:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8165:     }
1.1075    raeburn  8166:     if ($bgcolor ne '') {
                   8167:         $tdcol = "background-color: $bgcolor;";
                   8168:     }
1.1075.2.42  raeburn  8169:     my $nicescroll_js;
                   8170:     if ($env{'browser.mobile'}) {
                   8171:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8172:     }
1.1075    raeburn  8173:     return <<"END";
1.1075.2.42  raeburn  8174: $nicescroll_js
                   8175: 
                   8176: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8177: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8178: END
1.996     www      8179: }
                   8180: 
                   8181: sub end_scrollbox {
1.1036    www      8182:     return '</div></td></tr></table>';
1.996     www      8183: }
                   8184: 
1.1075.2.42  raeburn  8185: sub nicescroll_javascript {
                   8186:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8187:     my %options;
                   8188:     if (ref($cursor) eq 'HASH') {
                   8189:         %options = %{$cursor};
                   8190:     }
                   8191:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8192:         $options{'railalign'} = 'left';
                   8193:     }
                   8194:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8195:         my $function  = &get_users_function();
                   8196:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8197:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8198:             $options{'cursorcolor'} = '#00F';
                   8199:         }
                   8200:     }
                   8201:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8202:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8203:             $options{'cursoropacity'}='1.0';
                   8204:         }
                   8205:     } else {
                   8206:         $options{'cursoropacity'}='1.0';
                   8207:     }
                   8208:     if ($options{'cursorfixedheight'} eq 'none') {
                   8209:         delete($options{'cursorfixedheight'});
                   8210:     } else {
                   8211:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8212:     }
                   8213:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8214:         delete($options{'railoffset'});
                   8215:     }
                   8216:     my @niceoptions;
                   8217:     while (my($key,$value) = each(%options)) {
                   8218:         if ($value =~ /^\{.+\}$/) {
                   8219:             push(@niceoptions,$key.':'.$value);
                   8220:         } else {
                   8221:             push(@niceoptions,$key.':"'.$value.'"');
                   8222:         }
                   8223:     }
                   8224:     my $nicescroll_js = '
                   8225: $(document).ready(
                   8226:       function() {
                   8227:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8228:       }
                   8229: );
                   8230: ';
                   8231:     if ($framecheck) {
                   8232:         $nicescroll_js .= '
                   8233: function expand_div(caller) {
                   8234:     if (top === self) {
                   8235:         document.getElementById("'.$id.'").style.width = "auto";
                   8236:         document.getElementById("'.$id.'").style.height = "auto";
                   8237:     } else {
                   8238:         try {
                   8239:             if (parent.frames) {
                   8240:                 if (parent.frames.length > 1) {
                   8241:                     var framesrc = parent.frames[1].location.href;
                   8242:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8243:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8244:                         document.getElementById("'.$id.'").style.width = "auto";
                   8245:                         document.getElementById("'.$id.'").style.height = "auto";
                   8246:                     }
                   8247:                 }
                   8248:             }
                   8249:         } catch (e) {
                   8250:             return;
                   8251:         }
                   8252:     }
                   8253:     return;
                   8254: }
                   8255: ';
                   8256:     }
                   8257:     if ($needjsready) {
                   8258:         $nicescroll_js = '
                   8259: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8260:     } else {
                   8261:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8262:     }
                   8263:     return $nicescroll_js;
                   8264: }
                   8265: 
1.318     albertel 8266: sub simple_error_page {
1.1075.2.49  raeburn  8267:     my ($r,$title,$msg,$args) = @_;
                   8268:     if (ref($args) eq 'HASH') {
                   8269:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8270:     } else {
                   8271:         $msg = &mt($msg);
                   8272:     }
                   8273: 
1.318     albertel 8274:     my $page =
                   8275: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8276: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8277: 	&Apache::loncommon::end_page();
                   8278:     if (ref($r)) {
                   8279: 	$r->print($page);
1.327     albertel 8280: 	return;
1.318     albertel 8281:     }
                   8282:     return $page;
                   8283: }
1.347     albertel 8284: 
                   8285: {
1.610     albertel 8286:     my @row_count;
1.961     onken    8287: 
                   8288:     sub start_data_table_count {
                   8289:         unshift(@row_count, 0);
                   8290:         return;
                   8291:     }
                   8292: 
                   8293:     sub end_data_table_count {
                   8294:         shift(@row_count);
                   8295:         return;
                   8296:     }
                   8297: 
1.347     albertel 8298:     sub start_data_table {
1.1018    raeburn  8299: 	my ($add_class,$id) = @_;
1.422     albertel 8300: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8301:         my $table_id;
                   8302:         if (defined($id)) {
                   8303:             $table_id = ' id="'.$id.'"';
                   8304:         }
1.961     onken    8305: 	&start_data_table_count();
1.1018    raeburn  8306: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8307:     }
                   8308: 
                   8309:     sub end_data_table {
1.961     onken    8310: 	&end_data_table_count();
1.389     albertel 8311: 	return '</table>'."\n";;
1.347     albertel 8312:     }
                   8313: 
                   8314:     sub start_data_table_row {
1.974     wenzelju 8315: 	my ($add_class, $id) = @_;
1.610     albertel 8316: 	$row_count[0]++;
                   8317: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8318: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8319:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8320:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8321:     }
1.471     banghart 8322:     
                   8323:     sub continue_data_table_row {
1.974     wenzelju 8324: 	my ($add_class, $id) = @_;
1.610     albertel 8325: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8326: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8327:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8328:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8329:     }
1.347     albertel 8330: 
                   8331:     sub end_data_table_row {
1.389     albertel 8332: 	return '</tr>'."\n";;
1.347     albertel 8333:     }
1.367     www      8334: 
1.421     albertel 8335:     sub start_data_table_empty_row {
1.707     bisitz   8336: #	$row_count[0]++;
1.421     albertel 8337: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8338:     }
                   8339: 
                   8340:     sub end_data_table_empty_row {
                   8341: 	return '</tr>'."\n";;
                   8342:     }
                   8343: 
1.367     www      8344:     sub start_data_table_header_row {
1.389     albertel 8345: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8346:     }
                   8347: 
                   8348:     sub end_data_table_header_row {
1.389     albertel 8349: 	return '</tr>'."\n";;
1.367     www      8350:     }
1.890     droeschl 8351: 
                   8352:     sub data_table_caption {
                   8353:         my $caption = shift;
                   8354:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8355:     }
1.347     albertel 8356: }
                   8357: 
1.548     albertel 8358: =pod
                   8359: 
                   8360: =item * &inhibit_menu_check($arg)
                   8361: 
                   8362: Checks for a inhibitmenu state and generates output to preserve it
                   8363: 
                   8364: Inputs:         $arg - can be any of
                   8365:                      - undef - in which case the return value is a string 
                   8366:                                to add  into arguments list of a uri
                   8367:                      - 'input' - in which case the return value is a HTML
                   8368:                                  <form> <input> field of type hidden to
                   8369:                                  preserve the value
                   8370:                      - a url - in which case the return value is the url with
                   8371:                                the neccesary cgi args added to preserve the
                   8372:                                inhibitmenu state
                   8373:                      - a ref to a url - no return value, but the string is
                   8374:                                         updated to include the neccessary cgi
                   8375:                                         args to preserve the inhibitmenu state
                   8376: 
                   8377: =cut
                   8378: 
                   8379: sub inhibit_menu_check {
                   8380:     my ($arg) = @_;
                   8381:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8382:     if ($arg eq 'input') {
                   8383: 	if ($env{'form.inhibitmenu'}) {
                   8384: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8385: 	} else {
                   8386: 	    return
                   8387: 	}
                   8388:     }
                   8389:     if ($env{'form.inhibitmenu'}) {
                   8390: 	if (ref($arg)) {
                   8391: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8392: 	} elsif ($arg eq '') {
                   8393: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8394: 	} else {
                   8395: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8396: 	}
                   8397:     }
                   8398:     if (!ref($arg)) {
                   8399: 	return $arg;
                   8400:     }
                   8401: }
                   8402: 
1.251     albertel 8403: ###############################################
1.182     matthew  8404: 
                   8405: =pod
                   8406: 
1.549     albertel 8407: =back
                   8408: 
                   8409: =head1 User Information Routines
                   8410: 
                   8411: =over 4
                   8412: 
1.405     albertel 8413: =item * &get_users_function()
1.182     matthew  8414: 
                   8415: Used by &bodytag to determine the current users primary role.
                   8416: Returns either 'student','coordinator','admin', or 'author'.
                   8417: 
                   8418: =cut
                   8419: 
                   8420: ###############################################
                   8421: sub get_users_function {
1.815     tempelho 8422:     my $function = 'norole';
1.818     tempelho 8423:     if ($env{'request.role'}=~/^(st)/) {
                   8424:         $function='student';
                   8425:     }
1.907     raeburn  8426:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8427:         $function='coordinator';
                   8428:     }
1.258     albertel 8429:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8430:         $function='admin';
                   8431:     }
1.826     bisitz   8432:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8433:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8434:         $function='author';
                   8435:     }
                   8436:     return $function;
1.54      www      8437: }
1.99      www      8438: 
                   8439: ###############################################
                   8440: 
1.233     raeburn  8441: =pod
                   8442: 
1.821     raeburn  8443: =item * &show_course()
                   8444: 
                   8445: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8446: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8447: 
                   8448: Inputs:
                   8449: None
                   8450: 
                   8451: Outputs:
                   8452: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8453: 
                   8454: =cut
                   8455: 
                   8456: ###############################################
                   8457: sub show_course {
                   8458:     my $course = !$env{'user.adv'};
                   8459:     if (!$env{'user.adv'}) {
                   8460:         foreach my $env (keys(%env)) {
                   8461:             next if ($env !~ m/^user\.priv\./);
                   8462:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8463:                 $course = 0;
                   8464:                 last;
                   8465:             }
                   8466:         }
                   8467:     }
                   8468:     return $course;
                   8469: }
                   8470: 
                   8471: ###############################################
                   8472: 
                   8473: =pod
                   8474: 
1.542     raeburn  8475: =item * &check_user_status()
1.274     raeburn  8476: 
                   8477: Determines current status of supplied role for a
                   8478: specific user. Roles can be active, previous or future.
                   8479: 
                   8480: Inputs: 
                   8481: user's domain, user's username, course's domain,
1.375     raeburn  8482: course's number, optional section ID.
1.274     raeburn  8483: 
                   8484: Outputs:
                   8485: role status: active, previous or future. 
                   8486: 
                   8487: =cut
                   8488: 
                   8489: sub check_user_status {
1.412     raeburn  8490:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8491:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8492:     my @uroles = keys(%userinfo);
1.274     raeburn  8493:     my $srchstr;
                   8494:     my $active_chk = 'none';
1.412     raeburn  8495:     my $now = time;
1.274     raeburn  8496:     if (@uroles > 0) {
1.908     raeburn  8497:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8498:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8499:         } else {
1.412     raeburn  8500:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8501:         }
                   8502:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8503:             my $role_end = 0;
                   8504:             my $role_start = 0;
                   8505:             $active_chk = 'active';
1.412     raeburn  8506:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8507:                 $role_end = $1;
                   8508:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8509:                     $role_start = $1;
1.274     raeburn  8510:                 }
                   8511:             }
                   8512:             if ($role_start > 0) {
1.412     raeburn  8513:                 if ($now < $role_start) {
1.274     raeburn  8514:                     $active_chk = 'future';
                   8515:                 }
                   8516:             }
                   8517:             if ($role_end > 0) {
1.412     raeburn  8518:                 if ($now > $role_end) {
1.274     raeburn  8519:                     $active_chk = 'previous';
                   8520:                 }
                   8521:             }
                   8522:         }
                   8523:     }
                   8524:     return $active_chk;
                   8525: }
                   8526: 
                   8527: ###############################################
                   8528: 
                   8529: =pod
                   8530: 
1.405     albertel 8531: =item * &get_sections()
1.233     raeburn  8532: 
                   8533: Determines all the sections for a course including
                   8534: sections with students and sections containing other roles.
1.419     raeburn  8535: Incoming parameters: 
                   8536: 
                   8537: 1. domain
                   8538: 2. course number 
                   8539: 3. reference to array containing roles for which sections should 
                   8540: be gathered (optional).
                   8541: 4. reference to array containing status types for which sections 
                   8542: should be gathered (optional).
                   8543: 
                   8544: If the third argument is undefined, sections are gathered for any role. 
                   8545: If the fourth argument is undefined, sections are gathered for any status.
                   8546: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8547:  
1.374     raeburn  8548: Returns section hash (keys are section IDs, values are
                   8549: number of users in each section), subject to the
1.419     raeburn  8550: optional roles filter, optional status filter 
1.233     raeburn  8551: 
                   8552: =cut
                   8553: 
                   8554: ###############################################
                   8555: sub get_sections {
1.419     raeburn  8556:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8557:     if (!defined($cdom) || !defined($cnum)) {
                   8558:         my $cid =  $env{'request.course.id'};
                   8559: 
                   8560: 	return if (!defined($cid));
                   8561: 
                   8562:         $cdom = $env{'course.'.$cid.'.domain'};
                   8563:         $cnum = $env{'course.'.$cid.'.num'};
                   8564:     }
                   8565: 
                   8566:     my %sectioncount;
1.419     raeburn  8567:     my $now = time;
1.240     albertel 8568: 
1.1075.2.33  raeburn  8569:     my $check_students = 1;
                   8570:     my $only_students = 0;
                   8571:     if (ref($possible_roles) eq 'ARRAY') {
                   8572:         if (grep(/^st$/,@{$possible_roles})) {
                   8573:             if (@{$possible_roles} == 1) {
                   8574:                 $only_students = 1;
                   8575:             }
                   8576:         } else {
                   8577:             $check_students = 0;
                   8578:         }
                   8579:     }
                   8580: 
                   8581:     if ($check_students) {
1.276     albertel 8582: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8583: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8584: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8585:         my $start_index = &Apache::loncoursedata::CL_START();
                   8586:         my $end_index = &Apache::loncoursedata::CL_END();
                   8587:         my $status;
1.366     albertel 8588: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8589: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8590: 				                     $data->[$status_index],
                   8591:                                                      $data->[$start_index],
                   8592:                                                      $data->[$end_index]);
                   8593:             if ($stu_status eq 'Active') {
                   8594:                 $status = 'active';
                   8595:             } elsif ($end < $now) {
                   8596:                 $status = 'previous';
                   8597:             } elsif ($start > $now) {
                   8598:                 $status = 'future';
                   8599:             } 
                   8600: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8601:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8602:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8603: 		    $sectioncount{$section}++;
                   8604:                 }
1.240     albertel 8605: 	    }
                   8606: 	}
                   8607:     }
1.1075.2.33  raeburn  8608:     if ($only_students) {
                   8609:         return %sectioncount;
                   8610:     }
1.240     albertel 8611:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8612:     foreach my $user (sort(keys(%courseroles))) {
                   8613: 	if ($user !~ /^(\w{2})/) { next; }
                   8614: 	my ($role) = ($user =~ /^(\w{2})/);
                   8615: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8616: 	my ($section,$status);
1.240     albertel 8617: 	if ($role eq 'cr' &&
                   8618: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8619: 	    $section=$1;
                   8620: 	}
                   8621: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8622: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8623:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8624:         if ($end == -1 && $start == -1) {
                   8625:             next; #deleted role
                   8626:         }
                   8627:         if (!defined($possible_status)) { 
                   8628:             $sectioncount{$section}++;
                   8629:         } else {
                   8630:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8631:                 $status = 'active';
                   8632:             } elsif ($end < $now) {
                   8633:                 $status = 'future';
                   8634:             } elsif ($start > $now) {
                   8635:                 $status = 'previous';
                   8636:             }
                   8637:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8638:                 $sectioncount{$section}++;
                   8639:             }
                   8640:         }
1.233     raeburn  8641:     }
1.366     albertel 8642:     return %sectioncount;
1.233     raeburn  8643: }
                   8644: 
1.274     raeburn  8645: ###############################################
1.294     raeburn  8646: 
                   8647: =pod
1.405     albertel 8648: 
                   8649: =item * &get_course_users()
                   8650: 
1.275     raeburn  8651: Retrieves usernames:domains for users in the specified course
                   8652: with specific role(s), and access status. 
                   8653: 
                   8654: Incoming parameters:
1.277     albertel 8655: 1. course domain
                   8656: 2. course number
                   8657: 3. access status: users must have - either active, 
1.275     raeburn  8658: previous, future, or all.
1.277     albertel 8659: 4. reference to array of permissible roles
1.288     raeburn  8660: 5. reference to array of section restrictions (optional)
                   8661: 6. reference to results object (hash of hashes).
                   8662: 7. reference to optional userdata hash
1.609     raeburn  8663: 8. reference to optional statushash
1.630     raeburn  8664: 9. flag if privileged users (except those set to unhide in
                   8665:    course settings) should be excluded    
1.609     raeburn  8666: Keys of top level results hash are roles.
1.275     raeburn  8667: Keys of inner hashes are username:domain, with 
                   8668: values set to access type.
1.288     raeburn  8669: Optional userdata hash returns an array with arguments in the 
                   8670: same order as loncoursedata::get_classlist() for student data.
                   8671: 
1.609     raeburn  8672: Optional statushash returns
                   8673: 
1.288     raeburn  8674: Entries for end, start, section and status are blank because
                   8675: of the possibility of multiple values for non-student roles.
                   8676: 
1.275     raeburn  8677: =cut
1.405     albertel 8678: 
1.275     raeburn  8679: ###############################################
1.405     albertel 8680: 
1.275     raeburn  8681: sub get_course_users {
1.630     raeburn  8682:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8683:     my %idx = ();
1.419     raeburn  8684:     my %seclists;
1.288     raeburn  8685: 
                   8686:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8687:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8688:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8689:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8690:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8691:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8692:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8693:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8694: 
1.290     albertel 8695:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8696:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8697:         my $now = time;
1.277     albertel 8698:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8699:             my $match = 0;
1.412     raeburn  8700:             my $secmatch = 0;
1.419     raeburn  8701:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8702:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8703:             if ($section eq '') {
                   8704:                 $section = 'none';
                   8705:             }
1.291     albertel 8706:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8707:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8708:                     $secmatch = 1;
                   8709:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8710:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8711:                         $secmatch = 1;
                   8712:                     }
                   8713:                 } else {  
1.419     raeburn  8714: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8715: 		        $secmatch = 1;
                   8716:                     }
1.290     albertel 8717: 		}
1.412     raeburn  8718:                 if (!$secmatch) {
                   8719:                     next;
                   8720:                 }
1.419     raeburn  8721:             }
1.275     raeburn  8722:             if (defined($$types{'active'})) {
1.288     raeburn  8723:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8724:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8725:                     $match = 1;
1.275     raeburn  8726:                 }
                   8727:             }
                   8728:             if (defined($$types{'previous'})) {
1.609     raeburn  8729:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8730:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8731:                     $match = 1;
1.275     raeburn  8732:                 }
                   8733:             }
                   8734:             if (defined($$types{'future'})) {
1.609     raeburn  8735:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8736:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8737:                     $match = 1;
1.275     raeburn  8738:                 }
                   8739:             }
1.609     raeburn  8740:             if ($match) {
                   8741:                 push(@{$seclists{$student}},$section);
                   8742:                 if (ref($userdata) eq 'HASH') {
                   8743:                     $$userdata{$student} = $$classlist{$student};
                   8744:                 }
                   8745:                 if (ref($statushash) eq 'HASH') {
                   8746:                     $statushash->{$student}{'st'}{$section} = $status;
                   8747:                 }
1.288     raeburn  8748:             }
1.275     raeburn  8749:         }
                   8750:     }
1.412     raeburn  8751:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8752:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8753:         my $now = time;
1.609     raeburn  8754:         my %displaystatus = ( previous => 'Expired',
                   8755:                               active   => 'Active',
                   8756:                               future   => 'Future',
                   8757:                             );
1.1075.2.36  raeburn  8758:         my (%nothide,@possdoms);
1.630     raeburn  8759:         if ($hidepriv) {
                   8760:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8761:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8762:                 if ($user !~ /:/) {
                   8763:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8764:                 } else {
                   8765:                     $nothide{$user} = 1;
                   8766:                 }
                   8767:             }
1.1075.2.36  raeburn  8768:             my @possdoms = ($cdom);
                   8769:             if ($coursehash{'checkforpriv'}) {
                   8770:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8771:             }
1.630     raeburn  8772:         }
1.439     raeburn  8773:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8774:             my $match = 0;
1.412     raeburn  8775:             my $secmatch = 0;
1.439     raeburn  8776:             my $status;
1.412     raeburn  8777:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8778:             $user =~ s/:$//;
1.439     raeburn  8779:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8780:             if ($end == -1 || $start == -1) {
                   8781:                 next;
                   8782:             }
                   8783:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8784:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8785:                 my ($uname,$udom) = split(/:/,$user);
                   8786:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8787:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8788:                         $secmatch = 1;
                   8789:                     } elsif ($usec eq '') {
1.420     albertel 8790:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8791:                             $secmatch = 1;
                   8792:                         }
                   8793:                     } else {
                   8794:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8795:                             $secmatch = 1;
                   8796:                         }
                   8797:                     }
                   8798:                     if (!$secmatch) {
                   8799:                         next;
                   8800:                     }
1.288     raeburn  8801:                 }
1.419     raeburn  8802:                 if ($usec eq '') {
                   8803:                     $usec = 'none';
                   8804:                 }
1.275     raeburn  8805:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8806:                     if ($hidepriv) {
1.1075.2.36  raeburn  8807:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8808:                             (!$nothide{$uname.':'.$udom})) {
                   8809:                             next;
                   8810:                         }
                   8811:                     }
1.503     raeburn  8812:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8813:                         $status = 'previous';
                   8814:                     } elsif ($start > $now) {
                   8815:                         $status = 'future';
                   8816:                     } else {
                   8817:                         $status = 'active';
                   8818:                     }
1.277     albertel 8819:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8820:                         if ($status eq $type) {
1.420     albertel 8821:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8822:                                 push(@{$$users{$role}{$user}},$type);
                   8823:                             }
1.288     raeburn  8824:                             $match = 1;
                   8825:                         }
                   8826:                     }
1.419     raeburn  8827:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8828:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8829: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8830:                         }
1.420     albertel 8831:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8832:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8833:                         }
1.609     raeburn  8834:                         if (ref($statushash) eq 'HASH') {
                   8835:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8836:                         }
1.275     raeburn  8837:                     }
                   8838:                 }
                   8839:             }
                   8840:         }
1.290     albertel 8841:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8842:             if ((defined($cdom)) && (defined($cnum))) {
                   8843:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8844:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8845:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8846:                     next if ($owner eq '');
                   8847:                     my ($ownername,$ownerdom);
                   8848:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8849:                         $ownername = $1;
                   8850:                         $ownerdom = $2;
                   8851:                     } else {
                   8852:                         $ownername = $owner;
                   8853:                         $ownerdom = $cdom;
                   8854:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8855:                     }
                   8856:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8857:                     if (defined($userdata) && 
1.609     raeburn  8858: 			!exists($$userdata{$owner})) {
                   8859: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8860:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8861:                             push(@{$seclists{$owner}},'none');
                   8862:                         }
                   8863:                         if (ref($statushash) eq 'HASH') {
                   8864:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8865:                         }
1.290     albertel 8866: 		    }
1.279     raeburn  8867:                 }
                   8868:             }
                   8869:         }
1.419     raeburn  8870:         foreach my $user (keys(%seclists)) {
                   8871:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8872:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8873:         }
1.275     raeburn  8874:     }
                   8875:     return;
                   8876: }
                   8877: 
1.288     raeburn  8878: sub get_user_info {
                   8879:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8880:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8881: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8882:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8883:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8884:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8885:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8886:     return;
                   8887: }
1.275     raeburn  8888: 
1.472     raeburn  8889: ###############################################
                   8890: 
                   8891: =pod
                   8892: 
                   8893: =item * &get_user_quota()
                   8894: 
1.1075.2.41  raeburn  8895: Retrieves quota assigned for storage of user files.
                   8896: Default is to report quota for portfolio files.
1.472     raeburn  8897: 
                   8898: Incoming parameters:
                   8899: 1. user's username
                   8900: 2. user's domain
1.1075.2.41  raeburn  8901: 3. quota name - portfolio, author, or course
                   8902:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  8903: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  8904:    course
1.472     raeburn  8905: 
                   8906: Returns:
1.1075.2.58  raeburn  8907: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  8908: 2. (Optional) Type of setting: custom or default
                   8909:    (individually assigned or default for user's 
                   8910:    institutional status).
                   8911: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8912:    or student - types as defined in localenroll::inst_usertypes 
                   8913:    for user's domain, which determines default quota for user.
                   8914: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8915: 
                   8916: If a value has been stored in the user's environment, 
1.536     raeburn  8917: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  8918: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8919: 
                   8920: =cut
                   8921: 
                   8922: ###############################################
                   8923: 
                   8924: 
                   8925: sub get_user_quota {
1.1075.2.42  raeburn  8926:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  8927:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8928:     if (!defined($udom)) {
                   8929:         $udom = $env{'user.domain'};
                   8930:     }
                   8931:     if (!defined($uname)) {
                   8932:         $uname = $env{'user.name'};
                   8933:     }
                   8934:     if (($udom eq '' || $uname eq '') ||
                   8935:         ($udom eq 'public') && ($uname eq 'public')) {
                   8936:         $quota = 0;
1.536     raeburn  8937:         $quotatype = 'default';
                   8938:         $defquota = 0; 
1.472     raeburn  8939:     } else {
1.536     raeburn  8940:         my $inststatus;
1.1075.2.41  raeburn  8941:         if ($quotaname eq 'course') {
                   8942:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   8943:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   8944:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   8945:             } else {
                   8946:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   8947:                 $quota = $cenv{'internal.uploadquota'};
                   8948:             }
1.536     raeburn  8949:         } else {
1.1075.2.41  raeburn  8950:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8951:                 if ($quotaname eq 'author') {
                   8952:                     $quota = $env{'environment.authorquota'};
                   8953:                 } else {
                   8954:                     $quota = $env{'environment.portfolioquota'};
                   8955:                 }
                   8956:                 $inststatus = $env{'environment.inststatus'};
                   8957:             } else {
                   8958:                 my %userenv = 
                   8959:                     &Apache::lonnet::get('environment',['portfolioquota',
                   8960:                                          'authorquota','inststatus'],$udom,$uname);
                   8961:                 my ($tmp) = keys(%userenv);
                   8962:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8963:                     if ($quotaname eq 'author') {
                   8964:                         $quota = $userenv{'authorquota'};
                   8965:                     } else {
                   8966:                         $quota = $userenv{'portfolioquota'};
                   8967:                     }
                   8968:                     $inststatus = $userenv{'inststatus'};
                   8969:                 } else {
                   8970:                     undef(%userenv);
                   8971:                 }
                   8972:             }
                   8973:         }
                   8974:         if ($quota eq '' || wantarray) {
                   8975:             if ($quotaname eq 'course') {
                   8976:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  8977:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   8978:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  8979:                     $defquota = $domdefs{$crstype.'quota'};
                   8980:                 }
                   8981:                 if ($defquota eq '') {
                   8982:                     $defquota = 500;
                   8983:                 }
1.1075.2.41  raeburn  8984:             } else {
                   8985:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   8986:             }
                   8987:             if ($quota eq '') {
                   8988:                 $quota = $defquota;
                   8989:                 $quotatype = 'default';
                   8990:             } else {
                   8991:                 $quotatype = 'custom';
                   8992:             }
1.472     raeburn  8993:         }
                   8994:     }
1.536     raeburn  8995:     if (wantarray) {
                   8996:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8997:     } else {
                   8998:         return $quota;
                   8999:     }
1.472     raeburn  9000: }
                   9001: 
                   9002: ###############################################
                   9003: 
                   9004: =pod
                   9005: 
                   9006: =item * &default_quota()
                   9007: 
1.536     raeburn  9008: Retrieves default quota assigned for storage of user portfolio files,
                   9009: given an (optional) user's institutional status.
1.472     raeburn  9010: 
                   9011: Incoming parameters:
1.1075.2.42  raeburn  9012: 
1.472     raeburn  9013: 1. domain
1.536     raeburn  9014: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9015:    status types (e.g., faculty, staff, student etc.)
                   9016:    which apply to the user for whom the default is being retrieved.
                   9017:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9018:    default quota will be returned.
                   9019: 3.  quota name - portfolio, author, or course
                   9020:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9021: 
                   9022: Returns:
1.1075.2.42  raeburn  9023: 
1.1075.2.58  raeburn  9024: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9025: 2. (Optional) institutional type which determined the value of the
                   9026:    default quota.
1.472     raeburn  9027: 
                   9028: If a value has been stored in the domain's configuration db,
                   9029: it will return that, otherwise it returns 20 (for backwards 
                   9030: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9031: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9032: 
1.536     raeburn  9033: If the user's status includes multiple types (e.g., staff and student),
                   9034: the largest default quota which applies to the user determines the
                   9035: default quota returned.
                   9036: 
1.472     raeburn  9037: =cut
                   9038: 
                   9039: ###############################################
                   9040: 
                   9041: 
                   9042: sub default_quota {
1.1075.2.41  raeburn  9043:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9044:     my ($defquota,$settingstatus);
                   9045:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9046:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9047:     my $key = 'defaultquota';
                   9048:     if ($quotaname eq 'author') {
                   9049:         $key = 'authorquota';
                   9050:     }
1.622     raeburn  9051:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9052:         if ($inststatus ne '') {
1.765     raeburn  9053:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9054:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9055:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9056:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9057:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9058:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9059:                             $settingstatus = $item;
1.1075.2.41  raeburn  9060:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9061:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9062:                             $settingstatus = $item;
                   9063:                         }
                   9064:                     }
1.1075.2.41  raeburn  9065:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9066:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9067:                         if ($defquota eq '') {
                   9068:                             $defquota = $quotahash{'quotas'}{$item};
                   9069:                             $settingstatus = $item;
                   9070:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9071:                             $defquota = $quotahash{'quotas'}{$item};
                   9072:                             $settingstatus = $item;
                   9073:                         }
1.536     raeburn  9074:                     }
                   9075:                 }
                   9076:             }
                   9077:         }
                   9078:         if ($defquota eq '') {
1.1075.2.41  raeburn  9079:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9080:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9081:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9082:                 $defquota = $quotahash{'quotas'}{'default'};
                   9083:             }
1.536     raeburn  9084:             $settingstatus = 'default';
1.1075.2.42  raeburn  9085:             if ($defquota eq '') {
                   9086:                 if ($quotaname eq 'author') {
                   9087:                     $defquota = 500;
                   9088:                 }
                   9089:             }
1.536     raeburn  9090:         }
                   9091:     } else {
                   9092:         $settingstatus = 'default';
1.1075.2.41  raeburn  9093:         if ($quotaname eq 'author') {
                   9094:             $defquota = 500;
                   9095:         } else {
                   9096:             $defquota = 20;
                   9097:         }
1.536     raeburn  9098:     }
                   9099:     if (wantarray) {
                   9100:         return ($defquota,$settingstatus);
1.472     raeburn  9101:     } else {
1.536     raeburn  9102:         return $defquota;
1.472     raeburn  9103:     }
                   9104: }
                   9105: 
1.1075.2.41  raeburn  9106: ###############################################
                   9107: 
                   9108: =pod
                   9109: 
1.1075.2.42  raeburn  9110: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9111: 
                   9112: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9113: of existing file within authoring space will cause quota for the authoring
                   9114: space to be exceeded.
                   9115: 
                   9116: Same, if upload of a file directly to a course/community via Course Editor
                   9117: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9118: 
1.1075.2.61  raeburn  9119: Inputs: 7 
1.1075.2.42  raeburn  9120: 1. username or coursenum
1.1075.2.41  raeburn  9121: 2. domain
1.1075.2.42  raeburn  9122: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9123: 4. filename of file for which action is being requested
                   9124: 5. filesize (kB) of file
                   9125: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9126: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9127: 
                   9128: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9129:          otherwise return null.
                   9130: 
1.1075.2.42  raeburn  9131: =back
                   9132: 
1.1075.2.41  raeburn  9133: =cut
                   9134: 
1.1075.2.42  raeburn  9135: sub excess_filesize_warning {
1.1075.2.59  raeburn  9136:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9137:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9138:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9139:     if ($context eq 'author') {
                   9140:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9141:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9142:     } else {
                   9143:         foreach my $subdir ('docs','supplemental') {
                   9144:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9145:         }
                   9146:     }
1.1075.2.41  raeburn  9147:     $disk_quota = int($disk_quota * 1000);
                   9148:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9149:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9150:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9151:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9152:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9153:                             $disk_quota,$current_disk_usage).
                   9154:                '</p>';
                   9155:     }
                   9156:     return;
                   9157: }
                   9158: 
                   9159: ###############################################
                   9160: 
                   9161: 
1.384     raeburn  9162: sub get_secgrprole_info {
                   9163:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9164:     my %sections_count = &get_sections($cdom,$cnum);
                   9165:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9166:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9167:     my @groups = sort(keys(%curr_groups));
                   9168:     my $allroles = [];
                   9169:     my $rolehash;
                   9170:     my $accesshash = {
                   9171:                      active => 'Currently has access',
                   9172:                      future => 'Will have future access',
                   9173:                      previous => 'Previously had access',
                   9174:                   };
                   9175:     if ($needroles) {
                   9176:         $rolehash = {'all' => 'all'};
1.385     albertel 9177:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9178: 	if (&Apache::lonnet::error(%user_roles)) {
                   9179: 	    undef(%user_roles);
                   9180: 	}
                   9181:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9182:             my ($role)=split(/\:/,$item,2);
                   9183:             if ($role eq 'cr') { next; }
                   9184:             if ($role =~ /^cr/) {
                   9185:                 $$rolehash{$role} = (split('/',$role))[3];
                   9186:             } else {
                   9187:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9188:             }
                   9189:         }
                   9190:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9191:             push(@{$allroles},$key);
                   9192:         }
                   9193:         push (@{$allroles},'st');
                   9194:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9195:     }
                   9196:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9197: }
                   9198: 
1.555     raeburn  9199: sub user_picker {
1.994     raeburn  9200:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9201:     my $currdom = $dom;
                   9202:     my %curr_selected = (
                   9203:                         srchin => 'dom',
1.580     raeburn  9204:                         srchby => 'lastname',
1.555     raeburn  9205:                       );
                   9206:     my $srchterm;
1.625     raeburn  9207:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9208:         if ($srch->{'srchby'} ne '') {
                   9209:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9210:         }
                   9211:         if ($srch->{'srchin'} ne '') {
                   9212:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9213:         }
                   9214:         if ($srch->{'srchtype'} ne '') {
                   9215:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9216:         }
                   9217:         if ($srch->{'srchdomain'} ne '') {
                   9218:             $currdom = $srch->{'srchdomain'};
                   9219:         }
                   9220:         $srchterm = $srch->{'srchterm'};
                   9221:     }
                   9222:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9223:                     'usr'       => 'Search criteria',
1.563     raeburn  9224:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9225:                     'uname'     => 'username',
                   9226:                     'lastname'  => 'last name',
1.555     raeburn  9227:                     'lastfirst' => 'last name, first name',
1.558     albertel 9228:                     'crs'       => 'in this course',
1.576     raeburn  9229:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9230:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9231:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9232:                     'exact'     => 'is',
                   9233:                     'contains'  => 'contains',
1.569     raeburn  9234:                     'begins'    => 'begins with',
1.571     raeburn  9235:                     'youm'      => "You must include some text to search for.",
                   9236:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9237:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9238:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9239:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9240:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9241:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9242:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9243:                                        );
1.563     raeburn  9244:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9245:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9246: 
                   9247:     my @srchins = ('crs','dom','alc','instd');
                   9248: 
                   9249:     foreach my $option (@srchins) {
                   9250:         # FIXME 'alc' option unavailable until 
                   9251:         #       loncreateuser::print_user_query_page()
                   9252:         #       has been completed.
                   9253:         next if ($option eq 'alc');
1.880     raeburn  9254:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9255:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9256:         if ($curr_selected{'srchin'} eq $option) {
                   9257:             $srchinsel .= ' 
                   9258:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9259:         } else {
                   9260:             $srchinsel .= '
                   9261:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9262:         }
1.555     raeburn  9263:     }
1.563     raeburn  9264:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9265: 
                   9266:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9267:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9268:         if ($curr_selected{'srchby'} eq $option) {
                   9269:             $srchbysel .= '
                   9270:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9271:         } else {
                   9272:             $srchbysel .= '
                   9273:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9274:          }
                   9275:     }
                   9276:     $srchbysel .= "\n  </select>\n";
                   9277: 
                   9278:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9279:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9280:         if ($curr_selected{'srchtype'} eq $option) {
                   9281:             $srchtypesel .= '
                   9282:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9283:         } else {
                   9284:             $srchtypesel .= '
                   9285:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9286:         }
                   9287:     }
                   9288:     $srchtypesel .= "\n  </select>\n";
                   9289: 
1.558     albertel 9290:     my ($newuserscript,$new_user_create);
1.994     raeburn  9291:     my $context_dom = $env{'request.role.domain'};
                   9292:     if ($context eq 'requestcrs') {
                   9293:         if ($env{'form.coursedom'} ne '') { 
                   9294:             $context_dom = $env{'form.coursedom'};
                   9295:         }
                   9296:     }
1.556     raeburn  9297:     if ($forcenewuser) {
1.576     raeburn  9298:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9299:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9300:                 if ($cancreate) {
                   9301:                     $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>';
                   9302:                 } else {
1.799     bisitz   9303:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9304:                     my %usertypetext = (
                   9305:                         official   => 'institutional',
                   9306:                         unofficial => 'non-institutional',
                   9307:                     );
1.799     bisitz   9308:                     $new_user_create = '<p class="LC_warning">'
                   9309:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9310:                                       .' '
                   9311:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9312:                                           ,'<a href="'.$helplink.'">','</a>')
                   9313:                                       .'</p><br />';
1.627     raeburn  9314:                 }
1.576     raeburn  9315:             }
                   9316:         }
                   9317: 
1.556     raeburn  9318:         $newuserscript = <<"ENDSCRIPT";
                   9319: 
1.570     raeburn  9320: function setSearch(createnew,callingForm) {
1.556     raeburn  9321:     if (createnew == 1) {
1.570     raeburn  9322:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9323:             if (callingForm.srchby.options[i].value == 'uname') {
                   9324:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9325:             }
                   9326:         }
1.570     raeburn  9327:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9328:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9329: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9330:             }
                   9331:         }
1.570     raeburn  9332:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9333:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9334:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9335:             }
                   9336:         }
1.570     raeburn  9337:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9338:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9339:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9340:             }
                   9341:         }
                   9342:     }
                   9343: }
                   9344: ENDSCRIPT
1.558     albertel 9345: 
1.556     raeburn  9346:     }
                   9347: 
1.555     raeburn  9348:     my $output = <<"END_BLOCK";
1.556     raeburn  9349: <script type="text/javascript">
1.824     bisitz   9350: // <![CDATA[
1.570     raeburn  9351: function validateEntry(callingForm) {
1.558     albertel 9352: 
1.556     raeburn  9353:     var checkok = 1;
1.558     albertel 9354:     var srchin;
1.570     raeburn  9355:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9356: 	if ( callingForm.srchin[i].checked ) {
                   9357: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9358: 	}
                   9359:     }
                   9360: 
1.570     raeburn  9361:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9362:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9363:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9364:     var srchterm =  callingForm.srchterm.value;
                   9365:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9366:     var msg = "";
                   9367: 
                   9368:     if (srchterm == "") {
                   9369:         checkok = 0;
1.571     raeburn  9370:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9371:     }
                   9372: 
1.569     raeburn  9373:     if (srchtype== 'begins') {
                   9374:         if (srchterm.length < 2) {
                   9375:             checkok = 0;
1.571     raeburn  9376:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9377:         }
                   9378:     }
                   9379: 
1.556     raeburn  9380:     if (srchtype== 'contains') {
                   9381:         if (srchterm.length < 3) {
                   9382:             checkok = 0;
1.571     raeburn  9383:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9384:         }
                   9385:     }
                   9386:     if (srchin == 'instd') {
                   9387:         if (srchdomain == '') {
                   9388:             checkok = 0;
1.571     raeburn  9389:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9390:         }
                   9391:     }
                   9392:     if (srchin == 'dom') {
                   9393:         if (srchdomain == '') {
                   9394:             checkok = 0;
1.571     raeburn  9395:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9396:         }
                   9397:     }
                   9398:     if (srchby == 'lastfirst') {
                   9399:         if (srchterm.indexOf(",") == -1) {
                   9400:             checkok = 0;
1.571     raeburn  9401:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9402:         }
                   9403:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9404:             checkok = 0;
1.571     raeburn  9405:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9406:         }
                   9407:     }
                   9408:     if (checkok == 0) {
1.571     raeburn  9409:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9410:         return;
                   9411:     }
                   9412:     if (checkok == 1) {
1.570     raeburn  9413:         callingForm.submit();
1.556     raeburn  9414:     }
                   9415: }
                   9416: 
                   9417: $newuserscript
                   9418: 
1.824     bisitz   9419: // ]]>
1.556     raeburn  9420: </script>
1.558     albertel 9421: 
                   9422: $new_user_create
                   9423: 
1.555     raeburn  9424: END_BLOCK
1.558     albertel 9425: 
1.876     raeburn  9426:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9427:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9428:                $domform.
                   9429:                &Apache::lonhtmlcommon::row_closure().
                   9430:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9431:                $srchbysel.
                   9432:                $srchtypesel. 
                   9433:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9434:                $srchinsel.
                   9435:                &Apache::lonhtmlcommon::row_closure(1). 
                   9436:                &Apache::lonhtmlcommon::end_pick_box().
                   9437:                '<br />';
1.555     raeburn  9438:     return $output;
                   9439: }
                   9440: 
1.612     raeburn  9441: sub user_rule_check {
1.615     raeburn  9442:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9443:     my $response;
                   9444:     if (ref($usershash) eq 'HASH') {
                   9445:         foreach my $user (keys(%{$usershash})) {
                   9446:             my ($uname,$udom) = split(/:/,$user);
                   9447:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9448:             my ($id,$newuser);
1.612     raeburn  9449:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9450:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9451:                 $id = $usershash->{$user}->{'id'};
                   9452:             }
                   9453:             my $inst_response;
                   9454:             if (ref($checks) eq 'HASH') {
                   9455:                 if (defined($checks->{'username'})) {
1.615     raeburn  9456:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9457:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9458:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9459:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9460:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9461:                 }
1.615     raeburn  9462:             } else {
                   9463:                 ($inst_response,%{$inst_results->{$user}}) =
                   9464:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9465:                 return;
1.612     raeburn  9466:             }
1.615     raeburn  9467:             if (!$got_rules->{$udom}) {
1.612     raeburn  9468:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9469:                                                   ['usercreation'],$udom);
                   9470:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9471:                     foreach my $item ('username','id') {
1.612     raeburn  9472:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9473:                             $$curr_rules{$udom}{$item} = 
                   9474:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9475:                         }
                   9476:                     }
                   9477:                 }
1.615     raeburn  9478:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9479:             }
1.612     raeburn  9480:             foreach my $item (keys(%{$checks})) {
                   9481:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9482:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9483:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9484:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9485:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9486:                                 if ($rule_check{$rule}) {
                   9487:                                     $$rulematch{$user}{$item} = $rule;
                   9488:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9489:                                         if (ref($inst_results) eq 'HASH') {
                   9490:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9491:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9492:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9493:                                                 }
1.612     raeburn  9494:                                             }
                   9495:                                         }
1.615     raeburn  9496:                                     }
                   9497:                                     last;
1.585     raeburn  9498:                                 }
                   9499:                             }
                   9500:                         }
                   9501:                     }
                   9502:                 }
                   9503:             }
                   9504:         }
                   9505:     }
1.612     raeburn  9506:     return;
                   9507: }
                   9508: 
                   9509: sub user_rule_formats {
                   9510:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9511:     my %text = ( 
                   9512:                  'username' => 'Usernames',
                   9513:                  'id'       => 'IDs',
                   9514:                );
                   9515:     my $output;
                   9516:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9517:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9518:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9519:             $output = '<br />'.
                   9520:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9521:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9522:                       ' <ul>';
1.612     raeburn  9523:             foreach my $rule (@{$ruleorder}) {
                   9524:                 if (ref($curr_rules) eq 'ARRAY') {
                   9525:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9526:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9527:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9528:                                         $rules->{$rule}{'desc'}.'</li>';
                   9529:                         }
                   9530:                     }
                   9531:                 }
                   9532:             }
                   9533:             $output .= '</ul>';
                   9534:         }
                   9535:     }
                   9536:     return $output;
                   9537: }
                   9538: 
                   9539: sub instrule_disallow_msg {
1.615     raeburn  9540:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9541:     my $response;
                   9542:     my %text = (
                   9543:                   item   => 'username',
                   9544:                   items  => 'usernames',
                   9545:                   match  => 'matches',
                   9546:                   do     => 'does',
                   9547:                   action => 'a username',
                   9548:                   one    => 'one',
                   9549:                );
                   9550:     if ($count > 1) {
                   9551:         $text{'item'} = 'usernames';
                   9552:         $text{'match'} ='match';
                   9553:         $text{'do'} = 'do';
                   9554:         $text{'action'} = 'usernames',
                   9555:         $text{'one'} = 'ones';
                   9556:     }
                   9557:     if ($checkitem eq 'id') {
                   9558:         $text{'items'} = 'IDs';
                   9559:         $text{'item'} = 'ID';
                   9560:         $text{'action'} = 'an ID';
1.615     raeburn  9561:         if ($count > 1) {
                   9562:             $text{'item'} = 'IDs';
                   9563:             $text{'action'} = 'IDs';
                   9564:         }
1.612     raeburn  9565:     }
1.674     bisitz   9566:     $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  9567:     if ($mode eq 'upload') {
                   9568:         if ($checkitem eq 'username') {
                   9569:             $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'}.");
                   9570:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9571:             $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  9572:         }
1.669     raeburn  9573:     } elsif ($mode eq 'selfcreate') {
                   9574:         if ($checkitem eq 'id') {
                   9575:             $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.");
                   9576:         }
1.615     raeburn  9577:     } else {
                   9578:         if ($checkitem eq 'username') {
                   9579:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9580:         } elsif ($checkitem eq 'id') {
                   9581:             $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.");
                   9582:         }
1.612     raeburn  9583:     }
                   9584:     return $response;
1.585     raeburn  9585: }
                   9586: 
1.624     raeburn  9587: sub personal_data_fieldtitles {
                   9588:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9589:                         id => 'Student/Employee ID',
                   9590:                         permanentemail => 'E-mail address',
                   9591:                         lastname => 'Last Name',
                   9592:                         firstname => 'First Name',
                   9593:                         middlename => 'Middle Name',
                   9594:                         generation => 'Generation',
                   9595:                         gen => 'Generation',
1.765     raeburn  9596:                         inststatus => 'Affiliation',
1.624     raeburn  9597:                    );
                   9598:     return %fieldtitles;
                   9599: }
                   9600: 
1.642     raeburn  9601: sub sorted_inst_types {
                   9602:     my ($dom) = @_;
1.1075.2.70  raeburn  9603:     my ($usertypes,$order);
                   9604:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9605:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9606:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9607:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9608:     } else {
                   9609:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9610:     }
1.642     raeburn  9611:     my $othertitle = &mt('All users');
                   9612:     if ($env{'request.course.id'}) {
1.668     raeburn  9613:         $othertitle  = &mt('Any users');
1.642     raeburn  9614:     }
                   9615:     my @types;
                   9616:     if (ref($order) eq 'ARRAY') {
                   9617:         @types = @{$order};
                   9618:     }
                   9619:     if (@types == 0) {
                   9620:         if (ref($usertypes) eq 'HASH') {
                   9621:             @types = sort(keys(%{$usertypes}));
                   9622:         }
                   9623:     }
                   9624:     if (keys(%{$usertypes}) > 0) {
                   9625:         $othertitle = &mt('Other users');
                   9626:     }
                   9627:     return ($othertitle,$usertypes,\@types);
                   9628: }
                   9629: 
1.645     raeburn  9630: sub get_institutional_codes {
                   9631:     my ($settings,$allcourses,$LC_code) = @_;
                   9632: # Get complete list of course sections to update
                   9633:     my @currsections = ();
                   9634:     my @currxlists = ();
                   9635:     my $coursecode = $$settings{'internal.coursecode'};
                   9636: 
                   9637:     if ($$settings{'internal.sectionnums'} ne '') {
                   9638:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9639:     }
                   9640: 
                   9641:     if ($$settings{'internal.crosslistings'} ne '') {
                   9642:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9643:     }
                   9644: 
                   9645:     if (@currxlists > 0) {
                   9646:         foreach (@currxlists) {
                   9647:             if (m/^([^:]+):(\w*)$/) {
                   9648:                 unless (grep/^$1$/,@{$allcourses}) {
                   9649:                     push @{$allcourses},$1;
                   9650:                     $$LC_code{$1} = $2;
                   9651:                 }
                   9652:             }
                   9653:         }
                   9654:     }
                   9655:  
                   9656:     if (@currsections > 0) {
                   9657:         foreach (@currsections) {
                   9658:             if (m/^(\w+):(\w*)$/) {
                   9659:                 my $sec = $coursecode.$1;
                   9660:                 my $lc_sec = $2;
                   9661:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9662:                     push @{$allcourses},$sec;
                   9663:                     $$LC_code{$sec} = $lc_sec;
                   9664:                 }
                   9665:             }
                   9666:         }
                   9667:     }
                   9668:     return;
                   9669: }
                   9670: 
1.971     raeburn  9671: sub get_standard_codeitems {
                   9672:     return ('Year','Semester','Department','Number','Section');
                   9673: }
                   9674: 
1.112     bowersj2 9675: =pod
                   9676: 
1.780     raeburn  9677: =head1 Slot Helpers
                   9678: 
                   9679: =over 4
                   9680: 
                   9681: =item * sorted_slots()
                   9682: 
1.1040    raeburn  9683: Sorts an array of slot names in order of an optional sort key,
                   9684: default sort is by slot start time (earliest first). 
1.780     raeburn  9685: 
                   9686: Inputs:
                   9687: 
                   9688: =over 4
                   9689: 
                   9690: slotsarr  - Reference to array of unsorted slot names.
                   9691: 
                   9692: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9693: 
1.1040    raeburn  9694: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9695: 
1.549     albertel 9696: =back
                   9697: 
1.780     raeburn  9698: Returns:
                   9699: 
                   9700: =over 4
                   9701: 
1.1040    raeburn  9702: sorted   - An array of slot names sorted by a specified sort key 
                   9703:            (default sort key is start time of the slot).
1.780     raeburn  9704: 
                   9705: =back
                   9706: 
                   9707: =cut
                   9708: 
                   9709: 
                   9710: sub sorted_slots {
1.1040    raeburn  9711:     my ($slotsarr,$slots,$sortkey) = @_;
                   9712:     if ($sortkey eq '') {
                   9713:         $sortkey = 'starttime';
                   9714:     }
1.780     raeburn  9715:     my @sorted;
                   9716:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9717:         @sorted =
                   9718:             sort {
                   9719:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9720:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9721:                      }
                   9722:                      if (ref($slots->{$a})) { return -1;}
                   9723:                      if (ref($slots->{$b})) { return 1;}
                   9724:                      return 0;
                   9725:                  } @{$slotsarr};
                   9726:     }
                   9727:     return @sorted;
                   9728: }
                   9729: 
1.1040    raeburn  9730: =pod
                   9731: 
                   9732: =item * get_future_slots()
                   9733: 
                   9734: Inputs:
                   9735: 
                   9736: =over 4
                   9737: 
                   9738: cnum - course number
                   9739: 
                   9740: cdom - course domain
                   9741: 
                   9742: now - current UNIX time
                   9743: 
                   9744: symb - optional symb
                   9745: 
                   9746: =back
                   9747: 
                   9748: Returns:
                   9749: 
                   9750: =over 4
                   9751: 
                   9752: sorted_reservable - ref to array of student_schedulable slots currently 
                   9753:                     reservable, ordered by end date of reservation period.
                   9754: 
                   9755: reservable_now - ref to hash of student_schedulable slots currently
                   9756:                  reservable.
                   9757: 
                   9758:     Keys in inner hash are:
                   9759:     (a) symb: either blank or symb to which slot use is restricted.
                   9760:     (b) endreserve: end date of reservation period. 
                   9761: 
                   9762: sorted_future - ref to array of student_schedulable slots reservable in
                   9763:                 the future, ordered by start date of reservation period.
                   9764: 
                   9765: future_reservable - ref to hash of student_schedulable slots reservable
                   9766:                     in the future.
                   9767: 
                   9768:     Keys in inner hash are:
                   9769:     (a) symb: either blank or symb to which slot use is restricted.
                   9770:     (b) startreserve:  start date of reservation period.
                   9771: 
                   9772: =back
                   9773: 
                   9774: =cut
                   9775: 
                   9776: sub get_future_slots {
                   9777:     my ($cnum,$cdom,$now,$symb) = @_;
                   9778:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9779:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9780:     foreach my $slot (keys(%slots)) {
                   9781:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9782:         if ($symb) {
                   9783:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9784:                      ($slots{$slot}->{'symb'} ne $symb));
                   9785:         }
                   9786:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9787:             ($slots{$slot}->{'endtime'} > $now)) {
                   9788:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9789:                 my $userallowed = 0;
                   9790:                 if ($slots{$slot}->{'allowedsections'}) {
                   9791:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9792:                     if (!defined($env{'request.role.sec'})
                   9793:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9794:                         $userallowed=1;
                   9795:                     } else {
                   9796:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9797:                             $userallowed=1;
                   9798:                         }
                   9799:                     }
                   9800:                     unless ($userallowed) {
                   9801:                         if (defined($env{'request.course.groups'})) {
                   9802:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9803:                             foreach my $group (@groups) {
                   9804:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9805:                                     $userallowed=1;
                   9806:                                     last;
                   9807:                                 }
                   9808:                             }
                   9809:                         }
                   9810:                     }
                   9811:                 }
                   9812:                 if ($slots{$slot}->{'allowedusers'}) {
                   9813:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9814:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9815:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9816:                         $userallowed = 1;
                   9817:                     }
                   9818:                 }
                   9819:                 next unless($userallowed);
                   9820:             }
                   9821:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9822:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9823:             my $symb = $slots{$slot}->{'symb'};
                   9824:             if (($startreserve < $now) &&
                   9825:                 (!$endreserve || $endreserve > $now)) {
                   9826:                 my $lastres = $endreserve;
                   9827:                 if (!$lastres) {
                   9828:                     $lastres = $slots{$slot}->{'starttime'};
                   9829:                 }
                   9830:                 $reservable_now{$slot} = {
                   9831:                                            symb       => $symb,
                   9832:                                            endreserve => $lastres
                   9833:                                          };
                   9834:             } elsif (($startreserve > $now) &&
                   9835:                      (!$endreserve || $endreserve > $startreserve)) {
                   9836:                 $future_reservable{$slot} = {
                   9837:                                               symb         => $symb,
                   9838:                                               startreserve => $startreserve
                   9839:                                             };
                   9840:             }
                   9841:         }
                   9842:     }
                   9843:     my @unsorted_reservable = keys(%reservable_now);
                   9844:     if (@unsorted_reservable > 0) {
                   9845:         @sorted_reservable = 
                   9846:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9847:     }
                   9848:     my @unsorted_future = keys(%future_reservable);
                   9849:     if (@unsorted_future > 0) {
                   9850:         @sorted_future =
                   9851:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9852:     }
                   9853:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9854: }
1.780     raeburn  9855: 
                   9856: =pod
                   9857: 
1.1057    foxr     9858: =back
                   9859: 
1.549     albertel 9860: =head1 HTTP Helpers
                   9861: 
                   9862: =over 4
                   9863: 
1.648     raeburn  9864: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9865: 
1.258     albertel 9866: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9867: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9868: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9869: 
                   9870: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9871: $possible_names is an ref to an array of form element names.  As an example:
                   9872: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9873: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9874: 
                   9875: =cut
1.1       albertel 9876: 
1.6       albertel 9877: sub get_unprocessed_cgi {
1.25      albertel 9878:   my ($query,$possible_names)= @_;
1.26      matthew  9879:   # $Apache::lonxml::debug=1;
1.356     albertel 9880:   foreach my $pair (split(/&/,$query)) {
                   9881:     my ($name, $value) = split(/=/,$pair);
1.369     www      9882:     $name = &unescape($name);
1.25      albertel 9883:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9884:       $value =~ tr/+/ /;
                   9885:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9886:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9887:     }
1.16      harris41 9888:   }
1.6       albertel 9889: }
                   9890: 
1.112     bowersj2 9891: =pod
                   9892: 
1.648     raeburn  9893: =item * &cacheheader() 
1.112     bowersj2 9894: 
                   9895: returns cache-controlling header code
                   9896: 
                   9897: =cut
                   9898: 
1.7       albertel 9899: sub cacheheader {
1.258     albertel 9900:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9901:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9902:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9903:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9904:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9905:     return $output;
1.7       albertel 9906: }
                   9907: 
1.112     bowersj2 9908: =pod
                   9909: 
1.648     raeburn  9910: =item * &no_cache($r) 
1.112     bowersj2 9911: 
                   9912: specifies header code to not have cache
                   9913: 
                   9914: =cut
                   9915: 
1.9       albertel 9916: sub no_cache {
1.216     albertel 9917:     my ($r) = @_;
                   9918:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9919: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9920:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9921:     $r->no_cache(1);
                   9922:     $r->header_out("Expires" => $date);
                   9923:     $r->header_out("Pragma" => "no-cache");
1.123     www      9924: }
                   9925: 
                   9926: sub content_type {
1.181     albertel 9927:     my ($r,$type,$charset) = @_;
1.299     foxr     9928:     if ($r) {
                   9929: 	#  Note that printout.pl calls this with undef for $r.
                   9930: 	&no_cache($r);
                   9931:     }
1.258     albertel 9932:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9933:     unless ($charset) {
                   9934: 	$charset=&Apache::lonlocal::current_encoding;
                   9935:     }
                   9936:     if ($charset) { $type.='; charset='.$charset; }
                   9937:     if ($r) {
                   9938: 	$r->content_type($type);
                   9939:     } else {
                   9940: 	print("Content-type: $type\n\n");
                   9941:     }
1.9       albertel 9942: }
1.25      albertel 9943: 
1.112     bowersj2 9944: =pod
                   9945: 
1.648     raeburn  9946: =item * &add_to_env($name,$value) 
1.112     bowersj2 9947: 
1.258     albertel 9948: adds $name to the %env hash with value
1.112     bowersj2 9949: $value, if $name already exists, the entry is converted to an array
                   9950: reference and $value is added to the array.
                   9951: 
                   9952: =cut
                   9953: 
1.25      albertel 9954: sub add_to_env {
                   9955:   my ($name,$value)=@_;
1.258     albertel 9956:   if (defined($env{$name})) {
                   9957:     if (ref($env{$name})) {
1.25      albertel 9958:       #already have multiple values
1.258     albertel 9959:       push(@{ $env{$name} },$value);
1.25      albertel 9960:     } else {
                   9961:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9962:       my $first=$env{$name};
                   9963:       undef($env{$name});
                   9964:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9965:     }
                   9966:   } else {
1.258     albertel 9967:     $env{$name}=$value;
1.25      albertel 9968:   }
1.31      albertel 9969: }
1.149     albertel 9970: 
                   9971: =pod
                   9972: 
1.648     raeburn  9973: =item * &get_env_multiple($name) 
1.149     albertel 9974: 
1.258     albertel 9975: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9976: values may be defined and end up as an array ref.
                   9977: 
                   9978: returns an array of values
                   9979: 
                   9980: =cut
                   9981: 
                   9982: sub get_env_multiple {
                   9983:     my ($name) = @_;
                   9984:     my @values;
1.258     albertel 9985:     if (defined($env{$name})) {
1.149     albertel 9986:         # exists is it an array
1.258     albertel 9987:         if (ref($env{$name})) {
                   9988:             @values=@{ $env{$name} };
1.149     albertel 9989:         } else {
1.258     albertel 9990:             $values[0]=$env{$name};
1.149     albertel 9991:         }
                   9992:     }
                   9993:     return(@values);
                   9994: }
                   9995: 
1.660     raeburn  9996: sub ask_for_embedded_content {
                   9997:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9998:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  9999:         %currsubfile,%unused,$rem);
1.1071    raeburn  10000:     my $counter = 0;
                   10001:     my $numnew = 0;
1.987     raeburn  10002:     my $numremref = 0;
                   10003:     my $numinvalid = 0;
                   10004:     my $numpathchg = 0;
                   10005:     my $numexisting = 0;
1.1071    raeburn  10006:     my $numunused = 0;
                   10007:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10008:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10009:     my $heading = &mt('Upload embedded files');
                   10010:     my $buttontext = &mt('Upload');
                   10011: 
1.1075.2.11  raeburn  10012:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10013:         if ($actionurl eq '/adm/dependencies') {
                   10014:             $navmap = Apache::lonnavmaps::navmap->new();
                   10015:         }
                   10016:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10017:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10018:     }
1.1075.2.35  raeburn  10019:     if (($actionurl eq '/adm/portfolio') ||
                   10020:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10021:         my $current_path='/';
                   10022:         if ($env{'form.currentpath'}) {
                   10023:             $current_path = $env{'form.currentpath'};
                   10024:         }
                   10025:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10026:             $udom = $cdom;
                   10027:             $uname = $cnum;
1.984     raeburn  10028:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10029:         } else {
                   10030:             $udom = $env{'user.domain'};
                   10031:             $uname = $env{'user.name'};
                   10032:             $url = '/userfiles/portfolio';
                   10033:         }
1.987     raeburn  10034:         $toplevel = $url.'/';
1.984     raeburn  10035:         $url .= $current_path;
                   10036:         $getpropath = 1;
1.987     raeburn  10037:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10038:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10039:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10040:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10041:         $toplevel = $url;
1.984     raeburn  10042:         if ($rest ne '') {
1.987     raeburn  10043:             $url .= $rest;
                   10044:         }
                   10045:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10046:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10047:             $url = $args->{'docs_url'};
                   10048:             $toplevel = $url;
1.1075.2.11  raeburn  10049:             if ($args->{'context'} eq 'paste') {
                   10050:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10051:                 ($path) =
                   10052:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10053:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10054:                 $fileloc =~ s{^/}{};
                   10055:             }
1.1071    raeburn  10056:         }
                   10057:     } elsif ($actionurl eq '/adm/dependencies') {
                   10058:         if ($env{'request.course.id'} ne '') {
                   10059:             if (ref($args) eq 'HASH') {
                   10060:                 $url = $args->{'docs_url'};
                   10061:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10062:                 $toplevel = $url;
                   10063:                 unless ($toplevel =~ m{^/}) {
                   10064:                     $toplevel = "/$url";
                   10065:                 }
1.1075.2.11  raeburn  10066:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10067:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10068:                     $path = $1;
                   10069:                 } else {
                   10070:                     ($path) =
                   10071:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10072:                 }
1.1075.2.79  raeburn  10073:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10074:                     $fileloc = $toplevel;
                   10075:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10076:                     my ($udom,$uname,$fname) =
                   10077:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10078:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10079:                 } else {
                   10080:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10081:                 }
1.1071    raeburn  10082:                 $fileloc =~ s{^/}{};
                   10083:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10084:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10085:             }
1.987     raeburn  10086:         }
1.1075.2.35  raeburn  10087:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10088:         $udom = $cdom;
                   10089:         $uname = $cnum;
                   10090:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10091:         $toplevel = $url;
                   10092:         $path = $url;
                   10093:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10094:         $fileloc =~ s{^/}{};
                   10095:     }
                   10096:     foreach my $file (keys(%{$allfiles})) {
                   10097:         my $embed_file;
                   10098:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10099:             $embed_file = $1;
                   10100:         } else {
                   10101:             $embed_file = $file;
                   10102:         }
1.1075.2.55  raeburn  10103:         my ($absolutepath,$cleaned_file);
                   10104:         if ($embed_file =~ m{^\w+://}) {
                   10105:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10106:             $newfiles{$cleaned_file} = 1;
                   10107:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10108:         } else {
1.1075.2.55  raeburn  10109:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10110:             if ($embed_file =~ m{^/}) {
                   10111:                 $absolutepath = $embed_file;
                   10112:             }
1.1075.2.47  raeburn  10113:             if ($cleaned_file =~ m{/}) {
                   10114:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10115:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10116:                 my $item = $fname;
                   10117:                 if ($path ne '') {
                   10118:                     $item = $path.'/'.$fname;
                   10119:                     $subdependencies{$path}{$fname} = 1;
                   10120:                 } else {
                   10121:                     $dependencies{$item} = 1;
                   10122:                 }
                   10123:                 if ($absolutepath) {
                   10124:                     $mapping{$item} = $absolutepath;
                   10125:                 } else {
                   10126:                     $mapping{$item} = $embed_file;
                   10127:                 }
                   10128:             } else {
                   10129:                 $dependencies{$embed_file} = 1;
                   10130:                 if ($absolutepath) {
1.1075.2.47  raeburn  10131:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10132:                 } else {
1.1075.2.47  raeburn  10133:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10134:                 }
                   10135:             }
1.984     raeburn  10136:         }
                   10137:     }
1.1071    raeburn  10138:     my $dirptr = 16384;
1.984     raeburn  10139:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10140:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10141:         if (($actionurl eq '/adm/portfolio') ||
                   10142:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10143:             my ($sublistref,$listerror) =
                   10144:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10145:             if (ref($sublistref) eq 'ARRAY') {
                   10146:                 foreach my $line (@{$sublistref}) {
                   10147:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10148:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10149:                 }
1.984     raeburn  10150:             }
1.987     raeburn  10151:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10152:             if (opendir(my $dir,$url.'/'.$path)) {
                   10153:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10154:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10155:             }
1.1075.2.11  raeburn  10156:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10157:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10158:                   ($args->{'context'} eq 'paste')) ||
                   10159:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10160:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10161:                 my $dir;
                   10162:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10163:                     $dir = $fileloc;
                   10164:                 } else {
                   10165:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10166:                 }
1.1071    raeburn  10167:                 if ($dir ne '') {
                   10168:                     my ($sublistref,$listerror) =
                   10169:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10170:                     if (ref($sublistref) eq 'ARRAY') {
                   10171:                         foreach my $line (@{$sublistref}) {
                   10172:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10173:                                 undef,$mtime)=split(/\&/,$line,12);
                   10174:                             unless (($testdir&$dirptr) ||
                   10175:                                     ($file_name =~ /^\.\.?$/)) {
                   10176:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10177:                             }
                   10178:                         }
                   10179:                     }
                   10180:                 }
1.984     raeburn  10181:             }
                   10182:         }
                   10183:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10184:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10185:                 my $item = $path.'/'.$file;
                   10186:                 unless ($mapping{$item} eq $item) {
                   10187:                     $pathchanges{$item} = 1;
                   10188:                 }
                   10189:                 $existing{$item} = 1;
                   10190:                 $numexisting ++;
                   10191:             } else {
                   10192:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10193:             }
                   10194:         }
1.1071    raeburn  10195:         if ($actionurl eq '/adm/dependencies') {
                   10196:             foreach my $path (keys(%currsubfile)) {
                   10197:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10198:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10199:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10200:                              next if (($rem ne '') &&
                   10201:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10202:                                        (ref($navmap) &&
                   10203:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10204:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10205:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10206:                              $unused{$path.'/'.$file} = 1; 
                   10207:                          }
                   10208:                     }
                   10209:                 }
                   10210:             }
                   10211:         }
1.984     raeburn  10212:     }
1.987     raeburn  10213:     my %currfile;
1.1075.2.35  raeburn  10214:     if (($actionurl eq '/adm/portfolio') ||
                   10215:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10216:         my ($dirlistref,$listerror) =
                   10217:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10218:         if (ref($dirlistref) eq 'ARRAY') {
                   10219:             foreach my $line (@{$dirlistref}) {
                   10220:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10221:                 $currfile{$file_name} = 1;
                   10222:             }
1.984     raeburn  10223:         }
1.987     raeburn  10224:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10225:         if (opendir(my $dir,$url)) {
1.987     raeburn  10226:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10227:             map {$currfile{$_} = 1;} @dir_list;
                   10228:         }
1.1075.2.11  raeburn  10229:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10230:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10231:               ($args->{'context'} eq 'paste')) ||
                   10232:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10233:         if ($env{'request.course.id'} ne '') {
                   10234:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10235:             if ($dir ne '') {
                   10236:                 my ($dirlistref,$listerror) =
                   10237:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10238:                 if (ref($dirlistref) eq 'ARRAY') {
                   10239:                     foreach my $line (@{$dirlistref}) {
                   10240:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10241:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10242:                         unless (($testdir&$dirptr) ||
                   10243:                                 ($file_name =~ /^\.\.?$/)) {
                   10244:                             $currfile{$file_name} = [$size,$mtime];
                   10245:                         }
                   10246:                     }
                   10247:                 }
                   10248:             }
                   10249:         }
1.984     raeburn  10250:     }
                   10251:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10252:         if (exists($currfile{$file})) {
1.987     raeburn  10253:             unless ($mapping{$file} eq $file) {
                   10254:                 $pathchanges{$file} = 1;
                   10255:             }
                   10256:             $existing{$file} = 1;
                   10257:             $numexisting ++;
                   10258:         } else {
1.984     raeburn  10259:             $newfiles{$file} = 1;
                   10260:         }
                   10261:     }
1.1071    raeburn  10262:     foreach my $file (keys(%currfile)) {
                   10263:         unless (($file eq $filename) ||
                   10264:                 ($file eq $filename.'.bak') ||
                   10265:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10266:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10267:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10268:                     next if (($rem ne '') &&
                   10269:                              (($env{"httpref.$rem".$file} ne '') ||
                   10270:                               (ref($navmap) &&
                   10271:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10272:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10273:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10274:                 }
1.1075.2.11  raeburn  10275:             }
1.1071    raeburn  10276:             $unused{$file} = 1;
                   10277:         }
                   10278:     }
1.1075.2.11  raeburn  10279:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10280:         ($args->{'context'} eq 'paste')) {
                   10281:         $counter = scalar(keys(%existing));
                   10282:         $numpathchg = scalar(keys(%pathchanges));
                   10283:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10284:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10285:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10286:         $counter = scalar(keys(%existing));
                   10287:         $numpathchg = scalar(keys(%pathchanges));
                   10288:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10289:     }
1.984     raeburn  10290:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10291:         if ($actionurl eq '/adm/dependencies') {
                   10292:             next if ($embed_file =~ m{^\w+://});
                   10293:         }
1.660     raeburn  10294:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10295:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10296:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10297:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10298:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10299:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10300:         }
1.1075.2.35  raeburn  10301:         $upload_output .= '</td>';
1.1071    raeburn  10302:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10303:             $upload_output.='<td align="right">'.
                   10304:                             '<span class="LC_info LC_fontsize_medium">'.
                   10305:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10306:             $numremref++;
1.660     raeburn  10307:         } elsif ($args->{'error_on_invalid_names'}
                   10308:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10309:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10310:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10311:             $numinvalid++;
1.660     raeburn  10312:         } else {
1.1075.2.35  raeburn  10313:             $upload_output .= '<td>'.
                   10314:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10315:                                                      $embed_file,\%mapping,
1.1071    raeburn  10316:                                                      $allfiles,$codebase,'upload');
                   10317:             $counter ++;
                   10318:             $numnew ++;
1.987     raeburn  10319:         }
                   10320:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10321:     }
                   10322:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10323:         if ($actionurl eq '/adm/dependencies') {
                   10324:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10325:             $modify_output .= &start_data_table_row().
                   10326:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10327:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10328:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10329:                               '<td>'.$size.'</td>'.
                   10330:                               '<td>'.$mtime.'</td>'.
                   10331:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10332:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10333:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10334:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10335:                               &embedded_file_element('upload_embedded',$counter,
                   10336:                                                      $embed_file,\%mapping,
                   10337:                                                      $allfiles,$codebase,'modify').
                   10338:                               '</div></td>'.
                   10339:                               &end_data_table_row()."\n";
                   10340:             $counter ++;
                   10341:         } else {
                   10342:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10343:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10344:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10345:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10346:                               &Apache::loncommon::end_data_table_row()."\n";
                   10347:         }
                   10348:     }
                   10349:     my $delidx = $counter;
                   10350:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10351:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10352:         $delete_output .= &start_data_table_row().
                   10353:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10354:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10355:                           '<td>'.$size.'</td>'.
                   10356:                           '<td>'.$mtime.'</td>'.
                   10357:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10358:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10359:                           &embedded_file_element('upload_embedded',$delidx,
                   10360:                                                  $oldfile,\%mapping,$allfiles,
                   10361:                                                  $codebase,'delete').'</td>'.
                   10362:                           &end_data_table_row()."\n"; 
                   10363:         $numunused ++;
                   10364:         $delidx ++;
1.987     raeburn  10365:     }
                   10366:     if ($upload_output) {
                   10367:         $upload_output = &start_data_table().
                   10368:                          $upload_output.
                   10369:                          &end_data_table()."\n";
                   10370:     }
1.1071    raeburn  10371:     if ($modify_output) {
                   10372:         $modify_output = &start_data_table().
                   10373:                          &start_data_table_header_row().
                   10374:                          '<th>'.&mt('File').'</th>'.
                   10375:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10376:                          '<th>'.&mt('Modified').'</th>'.
                   10377:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10378:                          &end_data_table_header_row().
                   10379:                          $modify_output.
                   10380:                          &end_data_table()."\n";
                   10381:     }
                   10382:     if ($delete_output) {
                   10383:         $delete_output = &start_data_table().
                   10384:                          &start_data_table_header_row().
                   10385:                          '<th>'.&mt('File').'</th>'.
                   10386:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10387:                          '<th>'.&mt('Modified').'</th>'.
                   10388:                          '<th>'.&mt('Delete?').'</th>'.
                   10389:                          &end_data_table_header_row().
                   10390:                          $delete_output.
                   10391:                          &end_data_table()."\n";
                   10392:     }
1.987     raeburn  10393:     my $applies = 0;
                   10394:     if ($numremref) {
                   10395:         $applies ++;
                   10396:     }
                   10397:     if ($numinvalid) {
                   10398:         $applies ++;
                   10399:     }
                   10400:     if ($numexisting) {
                   10401:         $applies ++;
                   10402:     }
1.1071    raeburn  10403:     if ($counter || $numunused) {
1.987     raeburn  10404:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10405:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10406:                   $state.'<h3>'.$heading.'</h3>'; 
                   10407:         if ($actionurl eq '/adm/dependencies') {
                   10408:             if ($numnew) {
                   10409:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10410:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10411:                            $upload_output.'<br />'."\n";
                   10412:             }
                   10413:             if ($numexisting) {
                   10414:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10415:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10416:                            $modify_output.'<br />'."\n";
                   10417:                            $buttontext = &mt('Save changes');
                   10418:             }
                   10419:             if ($numunused) {
                   10420:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10421:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10422:                            $delete_output.'<br />'."\n";
                   10423:                            $buttontext = &mt('Save changes');
                   10424:             }
                   10425:         } else {
                   10426:             $output .= $upload_output.'<br />'."\n";
                   10427:         }
                   10428:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10429:                    $counter.'" />'."\n";
                   10430:         if ($actionurl eq '/adm/dependencies') { 
                   10431:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10432:                        $numnew.'" />'."\n";
                   10433:         } elsif ($actionurl eq '') {
1.987     raeburn  10434:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10435:         }
                   10436:     } elsif ($applies) {
                   10437:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10438:         if ($applies > 1) {
                   10439:             $output .=  
1.1075.2.35  raeburn  10440:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10441:             if ($numremref) {
                   10442:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10443:             }
                   10444:             if ($numinvalid) {
                   10445:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10446:             }
                   10447:             if ($numexisting) {
                   10448:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10449:             }
                   10450:             $output .= '</ul><br />';
                   10451:         } elsif ($numremref) {
                   10452:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10453:         } elsif ($numinvalid) {
                   10454:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10455:         } elsif ($numexisting) {
                   10456:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10457:         }
                   10458:         $output .= $upload_output.'<br />';
                   10459:     }
                   10460:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10461:     $chgcount = $counter;
1.987     raeburn  10462:     if (keys(%pathchanges) > 0) {
                   10463:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10464:             if ($counter) {
1.987     raeburn  10465:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10466:                                                   $embed_file,\%mapping,
1.1071    raeburn  10467:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10468:             } else {
                   10469:                 $pathchange_output .= 
                   10470:                     &start_data_table_row().
                   10471:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10472:                     $chgcount.'" checked="checked" /></td>'.
                   10473:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10474:                     '<td>'.$embed_file.
                   10475:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10476:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10477:                     '</td>'.&end_data_table_row();
1.660     raeburn  10478:             }
1.987     raeburn  10479:             $numpathchg ++;
                   10480:             $chgcount ++;
1.660     raeburn  10481:         }
                   10482:     }
1.1075.2.35  raeburn  10483:     if (($counter) || ($numunused)) {
1.987     raeburn  10484:         if ($numpathchg) {
                   10485:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10486:                        $numpathchg.'" />'."\n";
                   10487:         }
                   10488:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10489:             ($actionurl eq '/adm/imsimport')) {
                   10490:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10491:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10492:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10493:         } elsif ($actionurl eq '/adm/dependencies') {
                   10494:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10495:         }
1.1075.2.35  raeburn  10496:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10497:     } elsif ($numpathchg) {
                   10498:         my %pathchange = ();
                   10499:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10500:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10501:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10502:         }
1.987     raeburn  10503:     }
1.1071    raeburn  10504:     return ($output,$counter,$numpathchg);
1.987     raeburn  10505: }
                   10506: 
1.1075.2.47  raeburn  10507: =pod
                   10508: 
                   10509: =item * clean_path($name)
                   10510: 
                   10511: Performs clean-up of directories, subdirectories and filename in an
                   10512: embedded object, referenced in an HTML file which is being uploaded
                   10513: to a course or portfolio, where
                   10514: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10515: checked.
                   10516: 
                   10517: Clean-up is similar to replacements in lonnet::clean_filename()
                   10518: except each / between sub-directory and next level is preserved.
                   10519: 
                   10520: =cut
                   10521: 
                   10522: sub clean_path {
                   10523:     my ($embed_file) = @_;
                   10524:     $embed_file =~s{^/+}{};
                   10525:     my @contents;
                   10526:     if ($embed_file =~ m{/}) {
                   10527:         @contents = split(/\//,$embed_file);
                   10528:     } else {
                   10529:         @contents = ($embed_file);
                   10530:     }
                   10531:     my $lastidx = scalar(@contents)-1;
                   10532:     for (my $i=0; $i<=$lastidx; $i++) {
                   10533:         $contents[$i]=~s{\\}{/}g;
                   10534:         $contents[$i]=~s/\s+/\_/g;
                   10535:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10536:         if ($i == $lastidx) {
                   10537:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10538:         }
                   10539:     }
                   10540:     if ($lastidx > 0) {
                   10541:         return join('/',@contents);
                   10542:     } else {
                   10543:         return $contents[0];
                   10544:     }
                   10545: }
                   10546: 
1.987     raeburn  10547: sub embedded_file_element {
1.1071    raeburn  10548:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10549:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10550:                    (ref($codebase) eq 'HASH'));
                   10551:     my $output;
1.1071    raeburn  10552:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10553:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10554:     }
                   10555:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10556:                &escape($embed_file).'" />';
                   10557:     unless (($context eq 'upload_embedded') && 
                   10558:             ($mapping->{$embed_file} eq $embed_file)) {
                   10559:         $output .='
                   10560:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10561:     }
                   10562:     my $attrib;
                   10563:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10564:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10565:     }
                   10566:     $output .=
                   10567:         "\n\t\t".
                   10568:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10569:         $attrib.'" />';
                   10570:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10571:         $output .=
                   10572:             "\n\t\t".
                   10573:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10574:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10575:     }
1.987     raeburn  10576:     return $output;
1.660     raeburn  10577: }
                   10578: 
1.1071    raeburn  10579: sub get_dependency_details {
                   10580:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10581:     my ($size,$mtime,$showsize,$showmtime);
                   10582:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10583:         if ($embed_file =~ m{/}) {
                   10584:             my ($path,$fname) = split(/\//,$embed_file);
                   10585:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10586:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10587:             }
                   10588:         } else {
                   10589:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10590:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10591:             }
                   10592:         }
                   10593:         $showsize = $size/1024.0;
                   10594:         $showsize = sprintf("%.1f",$showsize);
                   10595:         if ($mtime > 0) {
                   10596:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10597:         }
                   10598:     }
                   10599:     return ($showsize,$showmtime);
                   10600: }
                   10601: 
                   10602: sub ask_embedded_js {
                   10603:     return <<"END";
                   10604: <script type="text/javascript"">
                   10605: // <![CDATA[
                   10606: function toggleBrowse(counter) {
                   10607:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10608:     var fileid = document.getElementById('embedded_item_'+counter);
                   10609:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10610:     if (chkboxid.checked == true) {
                   10611:         uploaddivid.style.display='block';
                   10612:     } else {
                   10613:         uploaddivid.style.display='none';
                   10614:         fileid.value = '';
                   10615:     }
                   10616: }
                   10617: // ]]>
                   10618: </script>
                   10619: 
                   10620: END
                   10621: }
                   10622: 
1.661     raeburn  10623: sub upload_embedded {
                   10624:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10625:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10626:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10627:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10628:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10629:         my $orig_uploaded_filename =
                   10630:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10631:         foreach my $type ('orig','ref','attrib','codebase') {
                   10632:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10633:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10634:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10635:             }
                   10636:         }
1.661     raeburn  10637:         my ($path,$fname) =
                   10638:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10639:         # no path, whole string is fname
                   10640:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10641:         $fname = &Apache::lonnet::clean_filename($fname);
                   10642:         # See if there is anything left
                   10643:         next if ($fname eq '');
                   10644: 
                   10645:         # Check if file already exists as a file or directory.
                   10646:         my ($state,$msg);
                   10647:         if ($context eq 'portfolio') {
                   10648:             my $port_path = $dirpath;
                   10649:             if ($group ne '') {
                   10650:                 $port_path = "groups/$group/$port_path";
                   10651:             }
1.987     raeburn  10652:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10653:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10654:                                               $dir_root,$port_path,$disk_quota,
                   10655:                                               $current_disk_usage,$uname,$udom);
                   10656:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10657:                 || $state eq 'file_locked') {
1.661     raeburn  10658:                 $output .= $msg;
                   10659:                 next;
                   10660:             }
                   10661:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10662:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10663:             if ($state eq 'exists') {
                   10664:                 $output .= $msg;
                   10665:                 next;
                   10666:             }
                   10667:         }
                   10668:         # Check if extension is valid
                   10669:         if (($fname =~ /\.(\w+)$/) &&
                   10670:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  10671:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10672:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10673:             next;
                   10674:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10675:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10676:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10677:             next;
                   10678:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  10679:             $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  10680:             next;
                   10681:         }
                   10682:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  10683:         my $subdir = $path;
                   10684:         $subdir =~ s{/+$}{};
1.661     raeburn  10685:         if ($context eq 'portfolio') {
1.984     raeburn  10686:             my $result;
                   10687:             if ($state eq 'existingfile') {
                   10688:                 $result=
                   10689:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  10690:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10691:             } else {
1.984     raeburn  10692:                 $result=
                   10693:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10694:                                                     $dirpath.
1.1075.2.35  raeburn  10695:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10696:                 if ($result !~ m|^/uploaded/|) {
                   10697:                     $output .= '<span class="LC_error">'
                   10698:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10699:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10700:                                .'</span><br />';
                   10701:                     next;
                   10702:                 } else {
1.987     raeburn  10703:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10704:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10705:                 }
1.661     raeburn  10706:             }
1.1075.2.35  raeburn  10707:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   10708:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10709:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10710:             my $result =
1.1075.2.35  raeburn  10711:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10712:             if ($result !~ m|^/uploaded/|) {
                   10713:                 $output .= '<span class="LC_error">'
                   10714:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10715:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10716:                            .'</span><br />';
                   10717:                     next;
                   10718:             } else {
                   10719:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10720:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  10721:                 if ($context eq 'syllabus') {
                   10722:                     &Apache::lonnet::make_public_indefinitely($result);
                   10723:                 }
1.987     raeburn  10724:             }
1.661     raeburn  10725:         } else {
                   10726: # Save the file
                   10727:             my $target = $env{'form.embedded_item_'.$i};
                   10728:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10729:             my $dest = $fullpath.$fname;
                   10730:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10731:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10732:             my $count;
                   10733:             my $filepath = $dir_root;
1.1027    raeburn  10734:             foreach my $subdir (@parts) {
                   10735:                 $filepath .= "/$subdir";
                   10736:                 if (!-e $filepath) {
1.661     raeburn  10737:                     mkdir($filepath,0770);
                   10738:                 }
                   10739:             }
                   10740:             my $fh;
                   10741:             if (!open($fh,'>'.$dest)) {
                   10742:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10743:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10744:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10745:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10746:                            '</span><br />';
                   10747:             } else {
                   10748:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10749:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10750:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10751:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10752:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10753:                               '</span><br />';
                   10754:                 } else {
1.987     raeburn  10755:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10756:                                $url.'</span>').'<br />';
                   10757:                     unless ($context eq 'testbank') {
                   10758:                         $footer .= &mt('View embedded file: [_1]',
                   10759:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10760:                     }
                   10761:                 }
                   10762:                 close($fh);
                   10763:             }
                   10764:         }
                   10765:         if ($env{'form.embedded_ref_'.$i}) {
                   10766:             $pathchange{$i} = 1;
                   10767:         }
                   10768:     }
                   10769:     if ($output) {
                   10770:         $output = '<p>'.$output.'</p>';
                   10771:     }
                   10772:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10773:     $returnflag = 'ok';
1.1071    raeburn  10774:     my $numpathchgs = scalar(keys(%pathchange));
                   10775:     if ($numpathchgs > 0) {
1.987     raeburn  10776:         if ($context eq 'portfolio') {
                   10777:             $output .= '<p>'.&mt('or').'</p>';
                   10778:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10779:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10780:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10781:             $returnflag = 'modify_orightml';
                   10782:         }
                   10783:     }
1.1071    raeburn  10784:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10785: }
                   10786: 
                   10787: sub modify_html_form {
                   10788:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10789:     my $end = 0;
                   10790:     my $modifyform;
                   10791:     if ($context eq 'upload_embedded') {
                   10792:         return unless (ref($pathchange) eq 'HASH');
                   10793:         if ($env{'form.number_embedded_items'}) {
                   10794:             $end += $env{'form.number_embedded_items'};
                   10795:         }
                   10796:         if ($env{'form.number_pathchange_items'}) {
                   10797:             $end += $env{'form.number_pathchange_items'};
                   10798:         }
                   10799:         if ($end) {
                   10800:             for (my $i=0; $i<$end; $i++) {
                   10801:                 if ($i < $env{'form.number_embedded_items'}) {
                   10802:                     next unless($pathchange->{$i});
                   10803:                 }
                   10804:                 $modifyform .=
                   10805:                     &start_data_table_row().
                   10806:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10807:                     'checked="checked" /></td>'.
                   10808:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10809:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10810:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10811:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10812:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10813:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10814:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10815:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10816:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10817:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10818:                     &end_data_table_row();
1.1071    raeburn  10819:             }
1.987     raeburn  10820:         }
                   10821:     } else {
                   10822:         $modifyform = $pathchgtable;
                   10823:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10824:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10825:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10826:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10827:         }
                   10828:     }
                   10829:     if ($modifyform) {
1.1071    raeburn  10830:         if ($actionurl eq '/adm/dependencies') {
                   10831:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10832:         }
1.987     raeburn  10833:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10834:                '<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".
                   10835:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10836:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10837:                '</ol></p>'."\n".'<p>'.
                   10838:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10839:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10840:                &start_data_table()."\n".
                   10841:                &start_data_table_header_row().
                   10842:                '<th>'.&mt('Change?').'</th>'.
                   10843:                '<th>'.&mt('Current reference').'</th>'.
                   10844:                '<th>'.&mt('Required reference').'</th>'.
                   10845:                &end_data_table_header_row()."\n".
                   10846:                $modifyform.
                   10847:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10848:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10849:                '</form>'."\n";
                   10850:     }
                   10851:     return;
                   10852: }
                   10853: 
                   10854: sub modify_html_refs {
1.1075.2.35  raeburn  10855:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10856:     my $container;
                   10857:     if ($context eq 'portfolio') {
                   10858:         $container = $env{'form.container'};
                   10859:     } elsif ($context eq 'coursedoc') {
                   10860:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10861:     } elsif ($context eq 'manage_dependencies') {
                   10862:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10863:         $container = "/$container";
1.1075.2.35  raeburn  10864:     } elsif ($context eq 'syllabus') {
                   10865:         $container = $url;
1.987     raeburn  10866:     } else {
1.1027    raeburn  10867:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10868:     }
                   10869:     my (%allfiles,%codebase,$output,$content);
                   10870:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  10871:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  10872:         if (wantarray) {
                   10873:             return ('',0,0); 
                   10874:         } else {
                   10875:             return;
                   10876:         }
                   10877:     }
                   10878:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10879:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10880:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10881:             if (wantarray) {
                   10882:                 return ('',0,0);
                   10883:             } else {
                   10884:                 return;
                   10885:             }
                   10886:         } 
1.987     raeburn  10887:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10888:         if ($content eq '-1') {
                   10889:             if (wantarray) {
                   10890:                 return ('',0,0);
                   10891:             } else {
                   10892:                 return;
                   10893:             }
                   10894:         }
1.987     raeburn  10895:     } else {
1.1071    raeburn  10896:         unless ($container =~ /^\Q$dir_root\E/) {
                   10897:             if (wantarray) {
                   10898:                 return ('',0,0);
                   10899:             } else {
                   10900:                 return;
                   10901:             }
                   10902:         } 
1.987     raeburn  10903:         if (open(my $fh,"<$container")) {
                   10904:             $content = join('', <$fh>);
                   10905:             close($fh);
                   10906:         } else {
1.1071    raeburn  10907:             if (wantarray) {
                   10908:                 return ('',0,0);
                   10909:             } else {
                   10910:                 return;
                   10911:             }
1.987     raeburn  10912:         }
                   10913:     }
                   10914:     my ($count,$codebasecount) = (0,0);
                   10915:     my $mm = new File::MMagic;
                   10916:     my $mime_type = $mm->checktype_contents($content);
                   10917:     if ($mime_type eq 'text/html') {
                   10918:         my $parse_result = 
                   10919:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10920:                                                     \%codebase,\$content);
                   10921:         if ($parse_result eq 'ok') {
                   10922:             foreach my $i (@changes) {
                   10923:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10924:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10925:                 if ($allfiles{$ref}) {
                   10926:                     my $newname =  $orig;
                   10927:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10928:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10929:                     if ($attrib_regexp =~ /:/) {
                   10930:                         $attrib_regexp =~ s/\:/|/g;
                   10931:                     }
                   10932:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10933:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10934:                         $count += $numchg;
1.1075.2.35  raeburn  10935:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  10936:                         delete($allfiles{$ref});
1.987     raeburn  10937:                     }
                   10938:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10939:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10940:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10941:                         $codebasecount ++;
                   10942:                     }
                   10943:                 }
                   10944:             }
1.1075.2.35  raeburn  10945:             my $skiprewrites;
1.987     raeburn  10946:             if ($count || $codebasecount) {
                   10947:                 my $saveresult;
1.1071    raeburn  10948:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10949:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10950:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10951:                     if ($url eq $container) {
                   10952:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10953:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10954:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10955:                                             $fname.'</span>').'</p>';
1.987     raeburn  10956:                     } else {
                   10957:                          $output = '<p class="LC_error">'.
                   10958:                                    &mt('Error: update failed for: [_1].',
                   10959:                                    '<span class="LC_filename">'.
                   10960:                                    $container.'</span>').'</p>';
                   10961:                     }
1.1075.2.35  raeburn  10962:                     if ($context eq 'syllabus') {
                   10963:                         unless ($saveresult eq 'ok') {
                   10964:                             $skiprewrites = 1;
                   10965:                         }
                   10966:                     }
1.987     raeburn  10967:                 } else {
                   10968:                     if (open(my $fh,">$container")) {
                   10969:                         print $fh $content;
                   10970:                         close($fh);
                   10971:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10972:                                   $count,'<span class="LC_filename">'.
                   10973:                                   $container.'</span>').'</p>';
1.661     raeburn  10974:                     } else {
1.987     raeburn  10975:                          $output = '<p class="LC_error">'.
                   10976:                                    &mt('Error: could not update [_1].',
                   10977:                                    '<span class="LC_filename">'.
                   10978:                                    $container.'</span>').'</p>';
1.661     raeburn  10979:                     }
                   10980:                 }
                   10981:             }
1.1075.2.35  raeburn  10982:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10983:                 my ($actionurl,$state);
                   10984:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10985:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10986:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10987:                                               \%codebase,
                   10988:                                               {'context' => 'rewrites',
                   10989:                                                'ignore_remote_references' => 1,});
                   10990:                 if (ref($mapping) eq 'HASH') {
                   10991:                     my $rewrites = 0;
                   10992:                     foreach my $key (keys(%{$mapping})) {
                   10993:                         next if ($key =~ m{^https?://});
                   10994:                         my $ref = $mapping->{$key};
                   10995:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10996:                         my $attrib;
                   10997:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   10998:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   10999:                         }
                   11000:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11001:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11002:                             $rewrites += $numchg;
                   11003:                         }
                   11004:                     }
                   11005:                     if ($rewrites) {
                   11006:                         my $saveresult;
                   11007:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11008:                         if ($url eq $container) {
                   11009:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11010:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11011:                                             $count,'<span class="LC_filename">'.
                   11012:                                             $fname.'</span>').'</p>';
                   11013:                         } else {
                   11014:                             $output .= '<p class="LC_error">'.
                   11015:                                        &mt('Error: could not update links in [_1].',
                   11016:                                        '<span class="LC_filename">'.
                   11017:                                        $container.'</span>').'</p>';
                   11018: 
                   11019:                         }
                   11020:                     }
                   11021:                 }
                   11022:             }
1.987     raeburn  11023:         } else {
                   11024:             &logthis('Failed to parse '.$container.
                   11025:                      ' to modify references: '.$parse_result);
1.661     raeburn  11026:         }
                   11027:     }
1.1071    raeburn  11028:     if (wantarray) {
                   11029:         return ($output,$count,$codebasecount);
                   11030:     } else {
                   11031:         return $output;
                   11032:     }
1.661     raeburn  11033: }
                   11034: 
                   11035: sub check_for_existing {
                   11036:     my ($path,$fname,$element) = @_;
                   11037:     my ($state,$msg);
                   11038:     if (-d $path.'/'.$fname) {
                   11039:         $state = 'exists';
                   11040:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11041:     } elsif (-e $path.'/'.$fname) {
                   11042:         $state = 'exists';
                   11043:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11044:     }
                   11045:     if ($state eq 'exists') {
                   11046:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11047:     }
                   11048:     return ($state,$msg);
                   11049: }
                   11050: 
                   11051: sub check_for_upload {
                   11052:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11053:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11054:     my $filesize = length($env{'form.'.$element});
                   11055:     if (!$filesize) {
                   11056:         my $msg = '<span class="LC_error">'.
                   11057:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11058:                       '<span class="LC_filename">'.$fname.'</span>',
                   11059:                       $filesize).'<br />'.
1.1007    raeburn  11060:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11061:                   '</span>';
                   11062:         return ('zero_bytes',$msg);
                   11063:     }
                   11064:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11065:     my $getpropath = 1;
1.1021    raeburn  11066:     my ($dirlistref,$listerror) =
                   11067:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11068:     my $found_file = 0;
                   11069:     my $locked_file = 0;
1.991     raeburn  11070:     my @lockers;
                   11071:     my $navmap;
                   11072:     if ($env{'request.course.id'}) {
                   11073:         $navmap = Apache::lonnavmaps::navmap->new();
                   11074:     }
1.1021    raeburn  11075:     if (ref($dirlistref) eq 'ARRAY') {
                   11076:         foreach my $line (@{$dirlistref}) {
                   11077:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11078:             if ($file_name eq $fname){
                   11079:                 $file_name = $path.$file_name;
                   11080:                 if ($group ne '') {
                   11081:                     $file_name = $group.$file_name;
                   11082:                 }
                   11083:                 $found_file = 1;
                   11084:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11085:                     foreach my $lock (@lockers) {
                   11086:                         if (ref($lock) eq 'ARRAY') {
                   11087:                             my ($symb,$crsid) = @{$lock};
                   11088:                             if ($crsid eq $env{'request.course.id'}) {
                   11089:                                 if (ref($navmap)) {
                   11090:                                     my $res = $navmap->getBySymb($symb);
                   11091:                                     foreach my $part (@{$res->parts()}) { 
                   11092:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11093:                                         unless (($slot_status == $res->RESERVED) ||
                   11094:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11095:                                             $locked_file = 1;
                   11096:                                         }
1.991     raeburn  11097:                                     }
1.1021    raeburn  11098:                                 } else {
                   11099:                                     $locked_file = 1;
1.991     raeburn  11100:                                 }
                   11101:                             } else {
                   11102:                                 $locked_file = 1;
                   11103:                             }
                   11104:                         }
1.1021    raeburn  11105:                    }
                   11106:                 } else {
                   11107:                     my @info = split(/\&/,$rest);
                   11108:                     my $currsize = $info[6]/1000;
                   11109:                     if ($currsize < $filesize) {
                   11110:                         my $extra = $filesize - $currsize;
                   11111:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11112:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11113:                                       &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.',
1.1075.2.69  raeburn  11114:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11115:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11116:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11117:                             return ('will_exceed_quota',$msg);
                   11118:                         }
1.984     raeburn  11119:                     }
                   11120:                 }
1.661     raeburn  11121:             }
                   11122:         }
                   11123:     }
                   11124:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11125:         my $msg = '<p class="LC_warning">'.
                   11126:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11127:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11128:         return ('will_exceed_quota',$msg);
                   11129:     } elsif ($found_file) {
                   11130:         if ($locked_file) {
1.1075.2.69  raeburn  11131:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11132:             $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>');
1.1075.2.69  raeburn  11133:             $msg .= '</p>';
1.661     raeburn  11134:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11135:             return ('file_locked',$msg);
                   11136:         } else {
1.1075.2.69  raeburn  11137:             my $msg = '<p class="LC_error">';
1.984     raeburn  11138:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  11139:             $msg .= '</p>';
1.984     raeburn  11140:             return ('existingfile',$msg);
1.661     raeburn  11141:         }
                   11142:     }
                   11143: }
                   11144: 
1.987     raeburn  11145: sub check_for_traversal {
                   11146:     my ($path,$url,$toplevel) = @_;
                   11147:     my @parts=split(/\//,$path);
                   11148:     my $cleanpath;
                   11149:     my $fullpath = $url;
                   11150:     for (my $i=0;$i<@parts;$i++) {
                   11151:         next if ($parts[$i] eq '.');
                   11152:         if ($parts[$i] eq '..') {
                   11153:             $fullpath =~ s{([^/]+/)$}{};
                   11154:         } else {
                   11155:             $fullpath .= $parts[$i].'/';
                   11156:         }
                   11157:     }
                   11158:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11159:         $cleanpath = $1;
                   11160:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11161:         my $curr_toprel = $1;
                   11162:         my @parts = split(/\//,$curr_toprel);
                   11163:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11164:         my @urlparts = split(/\//,$url_toprel);
                   11165:         my $doubledots;
                   11166:         my $startdiff = -1;
                   11167:         for (my $i=0; $i<@urlparts; $i++) {
                   11168:             if ($startdiff == -1) {
                   11169:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11170:                     $startdiff = $i;
                   11171:                     $doubledots .= '../';
                   11172:                 }
                   11173:             } else {
                   11174:                 $doubledots .= '../';
                   11175:             }
                   11176:         }
                   11177:         if ($startdiff > -1) {
                   11178:             $cleanpath = $doubledots;
                   11179:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11180:                 $cleanpath .= $parts[$i].'/';
                   11181:             }
                   11182:         }
                   11183:     }
                   11184:     $cleanpath =~ s{(/)$}{};
                   11185:     return $cleanpath;
                   11186: }
1.31      albertel 11187: 
1.1053    raeburn  11188: sub is_archive_file {
                   11189:     my ($mimetype) = @_;
                   11190:     if (($mimetype eq 'application/octet-stream') ||
                   11191:         ($mimetype eq 'application/x-stuffit') ||
                   11192:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11193:         return 1;
                   11194:     }
                   11195:     return;
                   11196: }
                   11197: 
                   11198: sub decompress_form {
1.1065    raeburn  11199:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11200:     my %lt = &Apache::lonlocal::texthash (
                   11201:         this => 'This file is an archive file.',
1.1067    raeburn  11202:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11203:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11204:         youm => 'You may wish to extract its contents.',
                   11205:         extr => 'Extract contents',
1.1067    raeburn  11206:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11207:         proa => 'Process automatically?',
1.1053    raeburn  11208:         yes  => 'Yes',
                   11209:         no   => 'No',
1.1067    raeburn  11210:         fold => 'Title for folder containing movie',
                   11211:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11212:     );
1.1065    raeburn  11213:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11214:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11215:     my $info = &list_archive_contents($fileloc,\@paths);
                   11216:     if (@paths) {
                   11217:         foreach my $path (@paths) {
                   11218:             $path =~ s{^/}{};
1.1067    raeburn  11219:             if ($path =~ m{^([^/]+)/$}) {
                   11220:                 $topdir = $1;
                   11221:             }
1.1065    raeburn  11222:             if ($path =~ m{^([^/]+)/}) {
                   11223:                 $toplevel{$1} = $path;
                   11224:             } else {
                   11225:                 $toplevel{$path} = $path;
                   11226:             }
                   11227:         }
                   11228:     }
1.1067    raeburn  11229:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11230:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11231:                         "$topdir/media/",
                   11232:                         "$topdir/media/$topdir.mp4",
                   11233:                         "$topdir/media/FirstFrame.png",
                   11234:                         "$topdir/media/player.swf",
                   11235:                         "$topdir/media/swfobject.js",
                   11236:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11237:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11238:                          "$topdir/$topdir.mp4",
                   11239:                          "$topdir/$topdir\_config.xml",
                   11240:                          "$topdir/$topdir\_controller.swf",
                   11241:                          "$topdir/$topdir\_embed.css",
                   11242:                          "$topdir/$topdir\_First_Frame.png",
                   11243:                          "$topdir/$topdir\_player.html",
                   11244:                          "$topdir/$topdir\_Thumbnails.png",
                   11245:                          "$topdir/playerProductInstall.swf",
                   11246:                          "$topdir/scripts/",
                   11247:                          "$topdir/scripts/config_xml.js",
                   11248:                          "$topdir/scripts/handlebars.js",
                   11249:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11250:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11251:                          "$topdir/scripts/modernizr.js",
                   11252:                          "$topdir/scripts/player-min.js",
                   11253:                          "$topdir/scripts/swfobject.js",
                   11254:                          "$topdir/skins/",
                   11255:                          "$topdir/skins/configuration_express.xml",
                   11256:                          "$topdir/skins/express_show/",
                   11257:                          "$topdir/skins/express_show/player-min.css",
                   11258:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11259:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11260:                          "$topdir/$topdir.mp4",
                   11261:                          "$topdir/$topdir\_config.xml",
                   11262:                          "$topdir/$topdir\_controller.swf",
                   11263:                          "$topdir/$topdir\_embed.css",
                   11264:                          "$topdir/$topdir\_First_Frame.png",
                   11265:                          "$topdir/$topdir\_player.html",
                   11266:                          "$topdir/$topdir\_Thumbnails.png",
                   11267:                          "$topdir/playerProductInstall.swf",
                   11268:                          "$topdir/scripts/",
                   11269:                          "$topdir/scripts/config_xml.js",
                   11270:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11271:                          "$topdir/skins/",
                   11272:                          "$topdir/skins/configuration_express.xml",
                   11273:                          "$topdir/skins/express_show/",
                   11274:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11275:                          "$topdir/skins/express_show/spritesheet.png",
                   11276:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11277:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11278:         if (@diffs == 0) {
1.1075.2.59  raeburn  11279:             $is_camtasia = 6;
                   11280:         } else {
1.1075.2.81  raeburn  11281:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11282:             if (@diffs == 0) {
                   11283:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11284:             } else {
                   11285:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11286:                 if (@diffs == 0) {
                   11287:                     $is_camtasia = 8;
                   11288:                 }
1.1075.2.59  raeburn  11289:             }
1.1067    raeburn  11290:         }
                   11291:     }
                   11292:     my $output;
                   11293:     if ($is_camtasia) {
                   11294:         $output = <<"ENDCAM";
                   11295: <script type="text/javascript" language="Javascript">
                   11296: // <![CDATA[
                   11297: 
                   11298: function camtasiaToggle() {
                   11299:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11300:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11301:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11302:                 document.getElementById('camtasia_titles').style.display='block';
                   11303:             } else {
                   11304:                 document.getElementById('camtasia_titles').style.display='none';
                   11305:             }
                   11306:         }
                   11307:     }
                   11308:     return;
                   11309: }
                   11310: 
                   11311: // ]]>
                   11312: </script>
                   11313: <p>$lt{'camt'}</p>
                   11314: ENDCAM
1.1065    raeburn  11315:     } else {
1.1067    raeburn  11316:         $output = '<p>'.$lt{'this'};
                   11317:         if ($info eq '') {
                   11318:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11319:         } else {
                   11320:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11321:                        '<div><pre>'.$info.'</pre></div>';
                   11322:         }
1.1065    raeburn  11323:     }
1.1067    raeburn  11324:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11325:     my $duplicates;
                   11326:     my $num = 0;
                   11327:     if (ref($dirlist) eq 'ARRAY') {
                   11328:         foreach my $item (@{$dirlist}) {
                   11329:             if (ref($item) eq 'ARRAY') {
                   11330:                 if (exists($toplevel{$item->[0]})) {
                   11331:                     $duplicates .= 
                   11332:                         &start_data_table_row().
                   11333:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11334:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11335:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11336:                         'value="1" />'.&mt('Yes').'</label>'.
                   11337:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11338:                         '<td>'.$item->[0].'</td>';
                   11339:                     if ($item->[2]) {
                   11340:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11341:                     } else {
                   11342:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11343:                     }
                   11344:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11345:                                    '<td>'.
                   11346:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11347:                                    '</td>'.
                   11348:                                    &end_data_table_row();
                   11349:                     $num ++;
                   11350:                 }
                   11351:             }
                   11352:         }
                   11353:     }
                   11354:     my $itemcount;
                   11355:     if (@paths > 0) {
                   11356:         $itemcount = scalar(@paths);
                   11357:     } else {
                   11358:         $itemcount = 1;
                   11359:     }
1.1067    raeburn  11360:     if ($is_camtasia) {
                   11361:         $output .= $lt{'auto'}.'<br />'.
                   11362:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11363:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11364:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11365:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11366:                    $lt{'no'}.'</label></span><br />'.
                   11367:                    '<div id="camtasia_titles" style="display:block">'.
                   11368:                    &Apache::lonhtmlcommon::start_pick_box().
                   11369:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11370:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11371:                    &Apache::lonhtmlcommon::row_closure().
                   11372:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11373:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11374:                    &Apache::lonhtmlcommon::row_closure(1).
                   11375:                    &Apache::lonhtmlcommon::end_pick_box().
                   11376:                    '</div>';
                   11377:     }
1.1065    raeburn  11378:     $output .= 
                   11379:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11380:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11381:         "\n";
1.1065    raeburn  11382:     if ($duplicates ne '') {
                   11383:         $output .= '<p><span class="LC_warning">'.
                   11384:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11385:                    &start_data_table().
                   11386:                    &start_data_table_header_row().
                   11387:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11388:                    '<th>'.&mt('Name').'</th>'.
                   11389:                    '<th>'.&mt('Type').'</th>'.
                   11390:                    '<th>'.&mt('Size').'</th>'.
                   11391:                    '<th>'.&mt('Last modified').'</th>'.
                   11392:                    &end_data_table_header_row().
                   11393:                    $duplicates.
                   11394:                    &end_data_table().
                   11395:                    '</p>';
                   11396:     }
1.1067    raeburn  11397:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11398:     if (ref($hiddenelements) eq 'HASH') {
                   11399:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11400:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11401:         }
                   11402:     }
                   11403:     $output .= <<"END";
1.1067    raeburn  11404: <br />
1.1053    raeburn  11405: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11406: </form>
                   11407: $noextract
                   11408: END
                   11409:     return $output;
                   11410: }
                   11411: 
1.1065    raeburn  11412: sub decompression_utility {
                   11413:     my ($program) = @_;
                   11414:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11415:     my $location;
                   11416:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11417:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11418:                          '/usr/sbin/') {
                   11419:             if (-x $dir.$program) {
                   11420:                 $location = $dir.$program;
                   11421:                 last;
                   11422:             }
                   11423:         }
                   11424:     }
                   11425:     return $location;
                   11426: }
                   11427: 
                   11428: sub list_archive_contents {
                   11429:     my ($file,$pathsref) = @_;
                   11430:     my (@cmd,$output);
                   11431:     my $needsregexp;
                   11432:     if ($file =~ /\.zip$/) {
                   11433:         @cmd = (&decompression_utility('unzip'),"-l");
                   11434:         $needsregexp = 1;
                   11435:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11436:              ($file =~ /\.tgz$/)) {
                   11437:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11438:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11439:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11440:     } elsif ($file =~ m|\.tar$|) {
                   11441:         @cmd = (&decompression_utility('tar'),"-tf");
                   11442:     }
                   11443:     if (@cmd) {
                   11444:         undef($!);
                   11445:         undef($@);
                   11446:         if (open(my $fh,"-|", @cmd, $file)) {
                   11447:             while (my $line = <$fh>) {
                   11448:                 $output .= $line;
                   11449:                 chomp($line);
                   11450:                 my $item;
                   11451:                 if ($needsregexp) {
                   11452:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11453:                 } else {
                   11454:                     $item = $line;
                   11455:                 }
                   11456:                 if ($item ne '') {
                   11457:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11458:                         push(@{$pathsref},$item);
                   11459:                     } 
                   11460:                 }
                   11461:             }
                   11462:             close($fh);
                   11463:         }
                   11464:     }
                   11465:     return $output;
                   11466: }
                   11467: 
1.1053    raeburn  11468: sub decompress_uploaded_file {
                   11469:     my ($file,$dir) = @_;
                   11470:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11471:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11472:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11473:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11474:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11475:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11476:     my $decompressed = $env{'cgi.decompressed'};
                   11477:     &Apache::lonnet::delenv('cgi.file');
                   11478:     &Apache::lonnet::delenv('cgi.dir');
                   11479:     &Apache::lonnet::delenv('cgi.decompressed');
                   11480:     return ($decompressed,$result);
                   11481: }
                   11482: 
1.1055    raeburn  11483: sub process_decompression {
                   11484:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11485:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  11486:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  11487:         $error = &mt('Filename not a supported archive file type.').
                   11488:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11489:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11490:     } else {
                   11491:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11492:         if ($docuhome eq 'no_host') {
                   11493:             $error = &mt('Could not determine home server for course.');
                   11494:         } else {
                   11495:             my @ids=&Apache::lonnet::current_machine_ids();
                   11496:             my $currdir = "$dir_root/$destination";
                   11497:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11498:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11499:                        "$dir_root/$destination";
                   11500:             } else {
                   11501:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11502:                        "$dir_root/$docudom/$docuname/$destination";
                   11503:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11504:                     $error = &mt('Archive file not found.');
                   11505:                 }
                   11506:             }
1.1065    raeburn  11507:             my (@to_overwrite,@to_skip);
                   11508:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11509:                 my $total = $env{'form.archive_overwrite_total'};
                   11510:                 for (my $i=0; $i<$total; $i++) {
                   11511:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11512:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11513:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11514:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11515:                     }
                   11516:                 }
                   11517:             }
                   11518:             my $numskip = scalar(@to_skip);
                   11519:             if (($numskip > 0) && 
                   11520:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11521:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11522:             } elsif ($dir eq '') {
1.1055    raeburn  11523:                 $error = &mt('Directory containing archive file unavailable.');
                   11524:             } elsif (!$error) {
1.1065    raeburn  11525:                 my ($decompressed,$display);
                   11526:                 if ($numskip > 0) {
                   11527:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11528:                     mkdir("$dir/$tempdir",0755);
                   11529:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11530:                     ($decompressed,$display) = 
                   11531:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11532:                     foreach my $item (@to_skip) {
                   11533:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11534:                             if (-f "$dir/$tempdir/$item") { 
                   11535:                                 unlink("$dir/$tempdir/$item");
                   11536:                             } elsif (-d "$dir/$tempdir/$item") {
                   11537:                                 system("rm -rf $dir/$tempdir/$item");
                   11538:                             }
                   11539:                         }
                   11540:                     }
                   11541:                     system("mv $dir/$tempdir/* $dir");
                   11542:                     rmdir("$dir/$tempdir");   
                   11543:                 } else {
                   11544:                     ($decompressed,$display) = 
                   11545:                         &decompress_uploaded_file($file,$dir);
                   11546:                 }
1.1055    raeburn  11547:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11548:                     $output = '<p class="LC_info">'.
                   11549:                               &mt('Files extracted successfully from archive.').
                   11550:                               '</p>'."\n";
1.1055    raeburn  11551:                     my ($warning,$result,@contents);
                   11552:                     my ($newdirlistref,$newlisterror) =
                   11553:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11554:                                                  $docuname,1);
                   11555:                     my (%is_dir,%changes,@newitems);
                   11556:                     my $dirptr = 16384;
1.1065    raeburn  11557:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11558:                         foreach my $dir_line (@{$newdirlistref}) {
                   11559:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11560:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11561:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11562:                                 push(@newitems,$item);
                   11563:                                 if ($dirptr&$testdir) {
                   11564:                                     $is_dir{$item} = 1;
                   11565:                                 }
                   11566:                                 $changes{$item} = 1;
                   11567:                             }
                   11568:                         }
                   11569:                     }
                   11570:                     if (keys(%changes) > 0) {
                   11571:                         foreach my $item (sort(@newitems)) {
                   11572:                             if ($changes{$item}) {
                   11573:                                 push(@contents,$item);
                   11574:                             }
                   11575:                         }
                   11576:                     }
                   11577:                     if (@contents > 0) {
1.1067    raeburn  11578:                         my $wantform;
                   11579:                         unless ($env{'form.autoextract_camtasia'}) {
                   11580:                             $wantform = 1;
                   11581:                         }
1.1056    raeburn  11582:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11583:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11584:                                                                 $currdir,\%is_dir,
                   11585:                                                                 \%children,\%parent,
1.1056    raeburn  11586:                                                                 \@contents,\%dirorder,
                   11587:                                                                 \%titles,$wantform);
1.1055    raeburn  11588:                         if ($datatable ne '') {
                   11589:                             $output .= &archive_options_form('decompressed',$datatable,
                   11590:                                                              $count,$hiddenelem);
1.1065    raeburn  11591:                             my $startcount = 6;
1.1055    raeburn  11592:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11593:                                                            \%titles,\%children);
1.1055    raeburn  11594:                         }
1.1067    raeburn  11595:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  11596:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11597:                             my %displayed;
                   11598:                             my $total = 1;
                   11599:                             $env{'form.archive_directory'} = [];
                   11600:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11601:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11602:                                 $path =~ s{/$}{};
                   11603:                                 my $item;
                   11604:                                 if ($path ne '') {
                   11605:                                     $item = "$path/$titles{$i}";
                   11606:                                 } else {
                   11607:                                     $item = $titles{$i};
                   11608:                                 }
                   11609:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11610:                                 if ($item eq $contents[0]) {
                   11611:                                     push(@{$env{'form.archive_directory'}},$i);
                   11612:                                     $env{'form.archive_'.$i} = 'display';
                   11613:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11614:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  11615:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11616:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  11617:                                     $env{'form.archive_'.$i} = 'display';
                   11618:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11619:                                     $displayed{'web'} = $i;
                   11620:                                 } else {
1.1075.2.59  raeburn  11621:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11622:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11623:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11624:                                         push(@{$env{'form.archive_directory'}},$i);
                   11625:                                     }
                   11626:                                     $env{'form.archive_'.$i} = 'dependency';
                   11627:                                 }
                   11628:                                 $total ++;
                   11629:                             }
                   11630:                             for (my $i=1; $i<$total; $i++) {
                   11631:                                 next if ($i == $displayed{'web'});
                   11632:                                 next if ($i == $displayed{'folder'});
                   11633:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11634:                             }
                   11635:                             $env{'form.phase'} = 'decompress_cleanup';
                   11636:                             $env{'form.archivedelete'} = 1;
                   11637:                             $env{'form.archive_count'} = $total-1;
                   11638:                             $output .=
                   11639:                                 &process_extracted_files('coursedocs',$docudom,
                   11640:                                                          $docuname,$destination,
                   11641:                                                          $dir_root,$hiddenelem);
                   11642:                         }
1.1055    raeburn  11643:                     } else {
                   11644:                         $warning = &mt('No new items extracted from archive file.');
                   11645:                     }
                   11646:                 } else {
                   11647:                     $output = $display;
                   11648:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11649:                 }
                   11650:             }
                   11651:         }
                   11652:     }
                   11653:     if ($error) {
                   11654:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11655:                    $error.'</p>'."\n";
                   11656:     }
                   11657:     if ($warning) {
                   11658:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11659:     }
                   11660:     return $output;
                   11661: }
                   11662: 
                   11663: sub get_extracted {
1.1056    raeburn  11664:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11665:         $titles,$wantform) = @_;
1.1055    raeburn  11666:     my $count = 0;
                   11667:     my $depth = 0;
                   11668:     my $datatable;
1.1056    raeburn  11669:     my @hierarchy;
1.1055    raeburn  11670:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11671:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11672:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11673:     foreach my $item (@{$contents}) {
                   11674:         $count ++;
1.1056    raeburn  11675:         @{$dirorder->{$count}} = @hierarchy;
                   11676:         $titles->{$count} = $item;
1.1055    raeburn  11677:         &archive_hierarchy($depth,$count,$parent,$children);
                   11678:         if ($wantform) {
                   11679:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11680:                                        $currdir,$depth,$count);
                   11681:         }
                   11682:         if ($is_dir->{$item}) {
                   11683:             $depth ++;
1.1056    raeburn  11684:             push(@hierarchy,$count);
                   11685:             $parent->{$depth} = $count;
1.1055    raeburn  11686:             $datatable .=
                   11687:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11688:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11689:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11690:             $depth --;
1.1056    raeburn  11691:             pop(@hierarchy);
1.1055    raeburn  11692:         }
                   11693:     }
                   11694:     return ($count,$datatable);
                   11695: }
                   11696: 
                   11697: sub recurse_extracted_archive {
1.1056    raeburn  11698:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11699:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11700:     my $result='';
1.1056    raeburn  11701:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11702:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11703:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11704:         return $result;
                   11705:     }
                   11706:     my $dirptr = 16384;
                   11707:     my ($newdirlistref,$newlisterror) =
                   11708:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11709:     if (ref($newdirlistref) eq 'ARRAY') {
                   11710:         foreach my $dir_line (@{$newdirlistref}) {
                   11711:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11712:             unless ($item =~ /^\.+$/) {
                   11713:                 $$count ++;
1.1056    raeburn  11714:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11715:                 $titles->{$$count} = $item;
1.1055    raeburn  11716:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11717: 
1.1055    raeburn  11718:                 my $is_dir;
                   11719:                 if ($dirptr&$testdir) {
                   11720:                     $is_dir = 1;
                   11721:                 }
                   11722:                 if ($wantform) {
                   11723:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11724:                 }
                   11725:                 if ($is_dir) {
                   11726:                     $$depth ++;
1.1056    raeburn  11727:                     push(@{$hierarchy},$$count);
                   11728:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11729:                     $result .=
                   11730:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11731:                                                    $docuname,$depth,$count,
1.1056    raeburn  11732:                                                    $hierarchy,$dirorder,$children,
                   11733:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11734:                     $$depth --;
1.1056    raeburn  11735:                     pop(@{$hierarchy});
1.1055    raeburn  11736:                 }
                   11737:             }
                   11738:         }
                   11739:     }
                   11740:     return $result;
                   11741: }
                   11742: 
                   11743: sub archive_hierarchy {
                   11744:     my ($depth,$count,$parent,$children) =@_;
                   11745:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11746:         if (exists($parent->{$depth})) {
                   11747:              $children->{$parent->{$depth}} .= $count.':';
                   11748:         }
                   11749:     }
                   11750:     return;
                   11751: }
                   11752: 
                   11753: sub archive_row {
                   11754:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11755:     my ($name) = ($item =~ m{([^/]+)$});
                   11756:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11757:                                        'display'    => 'Add as file',
1.1055    raeburn  11758:                                        'dependency' => 'Include as dependency',
                   11759:                                        'discard'    => 'Discard',
                   11760:                                       );
                   11761:     if ($is_dir) {
1.1059    raeburn  11762:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11763:     }
1.1056    raeburn  11764:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11765:     my $offset = 0;
1.1055    raeburn  11766:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11767:         $offset ++;
1.1065    raeburn  11768:         if ($action ne 'display') {
                   11769:             $offset ++;
                   11770:         }  
1.1055    raeburn  11771:         $output .= '<td><span class="LC_nobreak">'.
                   11772:                    '<label><input type="radio" name="archive_'.$count.
                   11773:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11774:         my $text = $choices{$action};
                   11775:         if ($is_dir) {
                   11776:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11777:             if ($action eq 'display') {
1.1059    raeburn  11778:                 $text = &mt('Add as folder');
1.1055    raeburn  11779:             }
1.1056    raeburn  11780:         } else {
                   11781:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11782: 
                   11783:         }
                   11784:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11785:         if ($action eq 'dependency') {
                   11786:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11787:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11788:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11789:                        '<option value=""></option>'."\n".
                   11790:                        '</select>'."\n".
                   11791:                        '</div>';
1.1059    raeburn  11792:         } elsif ($action eq 'display') {
                   11793:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11794:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11795:                        '</div>';
1.1055    raeburn  11796:         }
1.1056    raeburn  11797:         $output .= '</td>';
1.1055    raeburn  11798:     }
                   11799:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11800:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11801:     for (my $i=0; $i<$depth; $i++) {
                   11802:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11803:     }
                   11804:     if ($is_dir) {
                   11805:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11806:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11807:     } else {
                   11808:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11809:     }
                   11810:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11811:                &end_data_table_row();
                   11812:     return $output;
                   11813: }
                   11814: 
                   11815: sub archive_options_form {
1.1065    raeburn  11816:     my ($form,$display,$count,$hiddenelem) = @_;
                   11817:     my %lt = &Apache::lonlocal::texthash(
                   11818:                perm => 'Permanently remove archive file?',
                   11819:                hows => 'How should each extracted item be incorporated in the course?',
                   11820:                cont => 'Content actions for all',
                   11821:                addf => 'Add as folder/file',
                   11822:                incd => 'Include as dependency for a displayed file',
                   11823:                disc => 'Discard',
                   11824:                no   => 'No',
                   11825:                yes  => 'Yes',
                   11826:                save => 'Save',
                   11827:     );
                   11828:     my $output = <<"END";
                   11829: <form name="$form" method="post" action="">
                   11830: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11831: <label>
                   11832:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11833: </label>
                   11834: &nbsp;
                   11835: <label>
                   11836:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11837: </span>
                   11838: </p>
                   11839: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11840: <br />$lt{'hows'}
                   11841: <div class="LC_columnSection">
                   11842:   <fieldset>
                   11843:     <legend>$lt{'cont'}</legend>
                   11844:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11845:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11846:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11847:   </fieldset>
                   11848: </div>
                   11849: END
                   11850:     return $output.
1.1055    raeburn  11851:            &start_data_table()."\n".
1.1065    raeburn  11852:            $display."\n".
1.1055    raeburn  11853:            &end_data_table()."\n".
                   11854:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11855:            $hiddenelem.
1.1065    raeburn  11856:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11857:            '</form>';
                   11858: }
                   11859: 
                   11860: sub archive_javascript {
1.1056    raeburn  11861:     my ($startcount,$numitems,$titles,$children) = @_;
                   11862:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11863:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11864:     my $scripttag = <<START;
                   11865: <script type="text/javascript">
                   11866: // <![CDATA[
                   11867: 
                   11868: function checkAll(form,prefix) {
                   11869:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11870:     for (var i=0; i < form.elements.length; i++) {
                   11871:         var id = form.elements[i].id;
                   11872:         if ((id != '') && (id != undefined)) {
                   11873:             if (idstr.test(id)) {
                   11874:                 if (form.elements[i].type == 'radio') {
                   11875:                     form.elements[i].checked = true;
1.1056    raeburn  11876:                     var nostart = i-$startcount;
1.1059    raeburn  11877:                     var offset = nostart%7;
                   11878:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11879:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11880:                 }
                   11881:             }
                   11882:         }
                   11883:     }
                   11884: }
                   11885: 
                   11886: function propagateCheck(form,count) {
                   11887:     if (count > 0) {
1.1059    raeburn  11888:         var startelement = $startcount + ((count-1) * 7);
                   11889:         for (var j=1; j<6; j++) {
                   11890:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11891:                 var item = startelement + j; 
                   11892:                 if (form.elements[item].type == 'radio') {
                   11893:                     if (form.elements[item].checked) {
                   11894:                         containerCheck(form,count,j);
                   11895:                         break;
                   11896:                     }
1.1055    raeburn  11897:                 }
                   11898:             }
                   11899:         }
                   11900:     }
                   11901: }
                   11902: 
                   11903: numitems = $numitems
1.1056    raeburn  11904: var titles = new Array(numitems);
                   11905: var parents = new Array(numitems);
1.1055    raeburn  11906: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11907:     parents[i] = new Array;
1.1055    raeburn  11908: }
1.1059    raeburn  11909: var maintitle = '$maintitle';
1.1055    raeburn  11910: 
                   11911: START
                   11912: 
1.1056    raeburn  11913:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11914:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11915:         for (my $i=0; $i<@contents; $i ++) {
                   11916:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11917:         }
                   11918:     }
                   11919: 
1.1056    raeburn  11920:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11921:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11922:     }
                   11923: 
1.1055    raeburn  11924:     $scripttag .= <<END;
                   11925: 
                   11926: function containerCheck(form,count,offset) {
                   11927:     if (count > 0) {
1.1056    raeburn  11928:         dependencyCheck(form,count,offset);
1.1059    raeburn  11929:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11930:         form.elements[item].checked = true;
                   11931:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11932:             if (parents[count].length > 0) {
                   11933:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11934:                     containerCheck(form,parents[count][j],offset);
                   11935:                 }
                   11936:             }
                   11937:         }
                   11938:     }
                   11939: }
                   11940: 
                   11941: function dependencyCheck(form,count,offset) {
                   11942:     if (count > 0) {
1.1059    raeburn  11943:         var chosen = (offset+$startcount)+7*(count-1);
                   11944:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11945:         var currtype = form.elements[depitem].type;
                   11946:         if (form.elements[chosen].value == 'dependency') {
                   11947:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11948:             form.elements[depitem].options.length = 0;
                   11949:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  11950:             for (var i=1; i<=numitems; i++) {
                   11951:                 if (i == count) {
                   11952:                     continue;
                   11953:                 }
1.1059    raeburn  11954:                 var startelement = $startcount + (i-1) * 7;
                   11955:                 for (var j=1; j<6; j++) {
                   11956:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11957:                         var item = startelement + j;
                   11958:                         if (form.elements[item].type == 'radio') {
                   11959:                             if (form.elements[item].checked) {
                   11960:                                 if (form.elements[item].value == 'display') {
                   11961:                                     var n = form.elements[depitem].options.length;
                   11962:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11963:                                 }
                   11964:                             }
                   11965:                         }
                   11966:                     }
                   11967:                 }
                   11968:             }
                   11969:         } else {
                   11970:             document.getElementById('arc_depon_'+count).style.display='none';
                   11971:             form.elements[depitem].options.length = 0;
                   11972:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11973:         }
1.1059    raeburn  11974:         titleCheck(form,count,offset);
1.1056    raeburn  11975:     }
                   11976: }
                   11977: 
                   11978: function propagateSelect(form,count,offset) {
                   11979:     if (count > 0) {
1.1065    raeburn  11980:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11981:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11982:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11983:             if (parents[count].length > 0) {
                   11984:                 for (var j=0; j<parents[count].length; j++) {
                   11985:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11986:                 }
                   11987:             }
                   11988:         }
                   11989:     }
                   11990: }
1.1056    raeburn  11991: 
                   11992: function containerSelect(form,count,offset,picked) {
                   11993:     if (count > 0) {
1.1065    raeburn  11994:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11995:         if (form.elements[item].type == 'radio') {
                   11996:             if (form.elements[item].value == 'dependency') {
                   11997:                 if (form.elements[item+1].type == 'select-one') {
                   11998:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11999:                         if (form.elements[item+1].options[i].value == picked) {
                   12000:                             form.elements[item+1].selectedIndex = i;
                   12001:                             break;
                   12002:                         }
                   12003:                     }
                   12004:                 }
                   12005:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12006:                     if (parents[count].length > 0) {
                   12007:                         for (var j=0; j<parents[count].length; j++) {
                   12008:                             containerSelect(form,parents[count][j],offset,picked);
                   12009:                         }
                   12010:                     }
                   12011:                 }
                   12012:             }
                   12013:         }
                   12014:     }
                   12015: }
                   12016: 
1.1059    raeburn  12017: function titleCheck(form,count,offset) {
                   12018:     if (count > 0) {
                   12019:         var chosen = (offset+$startcount)+7*(count-1);
                   12020:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12021:         var currtype = form.elements[depitem].type;
                   12022:         if (form.elements[chosen].value == 'display') {
                   12023:             document.getElementById('arc_title_'+count).style.display='block';
                   12024:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12025:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12026:             }
                   12027:         } else {
                   12028:             document.getElementById('arc_title_'+count).style.display='none';
                   12029:             if (currtype == 'text') { 
                   12030:                 document.getElementById('archive_title_'+count).value='';
                   12031:             }
                   12032:         }
                   12033:     }
                   12034:     return;
                   12035: }
                   12036: 
1.1055    raeburn  12037: // ]]>
                   12038: </script>
                   12039: END
                   12040:     return $scripttag;
                   12041: }
                   12042: 
                   12043: sub process_extracted_files {
1.1067    raeburn  12044:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12045:     my $numitems = $env{'form.archive_count'};
                   12046:     return unless ($numitems);
                   12047:     my @ids=&Apache::lonnet::current_machine_ids();
                   12048:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12049:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12050:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12051:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12052:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12053:         $pathtocheck = "$dir_root/$destination";
                   12054:         $dir = $dir_root;
                   12055:         $ishome = 1;
                   12056:     } else {
                   12057:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12058:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12059:         $dir = "$dir_root/$docudom/$docuname";    
                   12060:     }
                   12061:     my $currdir = "$dir_root/$destination";
                   12062:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12063:     if ($env{'form.folderpath'}) {
                   12064:         my @items = split('&',$env{'form.folderpath'});
                   12065:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12066:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12067:             $containers{'0'}='page';
                   12068:         } else {
                   12069:             $containers{'0'}='sequence';
                   12070:         }
1.1055    raeburn  12071:     }
                   12072:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12073:     if ($numitems) {
                   12074:         for (my $i=1; $i<=$numitems; $i++) {
                   12075:             my $path = $env{'form.archive_content_'.$i};
                   12076:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12077:                 my $item = $1;
                   12078:                 $toplevelitems{$item} = $i;
                   12079:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12080:                     $is_dir{$item} = 1;
                   12081:                 }
                   12082:             }
                   12083:         }
                   12084:     }
1.1067    raeburn  12085:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12086:     if (keys(%toplevelitems) > 0) {
                   12087:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12088:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12089:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12090:     }
1.1066    raeburn  12091:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12092:     if ($numitems) {
                   12093:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12094:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12095:             my $path = $env{'form.archive_content_'.$i};
                   12096:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12097:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12098:                     if ($prefix ne '' && $path ne '') {
                   12099:                         if (-e $prefix.$path) {
1.1066    raeburn  12100:                             if ((@archdirs > 0) && 
                   12101:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12102:                                 $todeletedir{$prefix.$path} = 1;
                   12103:                             } else {
                   12104:                                 $todelete{$prefix.$path} = 1;
                   12105:                             }
1.1055    raeburn  12106:                         }
                   12107:                     }
                   12108:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12109:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12110:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12111:                     $docstitle = $env{'form.archive_title_'.$i};
                   12112:                     if ($docstitle eq '') {
                   12113:                         $docstitle = $title;
                   12114:                     }
1.1055    raeburn  12115:                     $outer = 0;
1.1056    raeburn  12116:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12117:                         if (@{$dirorder{$i}} > 0) {
                   12118:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12119:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12120:                                     $outer = $item;
                   12121:                                     last;
                   12122:                                 }
                   12123:                             }
                   12124:                         }
                   12125:                     }
                   12126:                     my ($errtext,$fatal) = 
                   12127:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12128:                                                '/'.$folders{$outer}.'.'.
                   12129:                                                $containers{$outer});
                   12130:                     next if ($fatal);
                   12131:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12132:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12133:                             $mapinner{$i} = time;
1.1055    raeburn  12134:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12135:                             $containers{$i} = 'sequence';
                   12136:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12137:                                       $folders{$i}.'.'.$containers{$i};
                   12138:                             my $newidx = &LONCAPA::map::getresidx();
                   12139:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12140:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12141:                             push(@LONCAPA::map::order,$newidx);
                   12142:                             my ($outtext,$errtext) =
                   12143:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12144:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12145:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12146:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12147:                             unless ($errtext) {
                   12148:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12149:                             }
1.1055    raeburn  12150:                         }
                   12151:                     } else {
                   12152:                         if ($context eq 'coursedocs') {
                   12153:                             my $newidx=&LONCAPA::map::getresidx();
                   12154:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12155:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12156:                                       $title;
                   12157:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12158:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12159:                             }
                   12160:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12161:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12162:                             }
                   12163:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12164:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12165:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12166:                                 unless ($ishome) {
                   12167:                                     my $fetch = "$newdest{$i}/$title";
                   12168:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12169:                                     $prompttofetch{$fetch} = 1;
                   12170:                                 }
1.1055    raeburn  12171:                             }
                   12172:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12173:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12174:                             push(@LONCAPA::map::order, $newidx);
                   12175:                             my ($outtext,$errtext)=
                   12176:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12177:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12178:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12179:                             unless ($errtext) {
                   12180:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12181:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12182:                                 }
                   12183:                             }
1.1055    raeburn  12184:                         }
                   12185:                     }
1.1075.2.11  raeburn  12186:                 }
                   12187:             } else {
                   12188:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12189:             }
                   12190:         }
                   12191:         for (my $i=1; $i<=$numitems; $i++) {
                   12192:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12193:             my $path = $env{'form.archive_content_'.$i};
                   12194:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12195:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12196:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12197:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12198:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12199:                         my ($itemidx,$fullpath,$relpath);
                   12200:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12201:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12202:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12203:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12204:                                     $itemidx = $j;
1.1056    raeburn  12205:                                 }
                   12206:                             }
1.1075.2.11  raeburn  12207:                         }
                   12208:                         if ($itemidx eq '') {
                   12209:                             $itemidx =  0;
                   12210:                         }
                   12211:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12212:                             if ($mapinner{$referrer{$i}}) {
                   12213:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12214:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12215:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12216:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12217:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12218:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12219:                                             if (!-e $fullpath) {
                   12220:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12221:                                             }
                   12222:                                         }
1.1075.2.11  raeburn  12223:                                     } else {
                   12224:                                         last;
1.1056    raeburn  12225:                                     }
1.1075.2.11  raeburn  12226:                                 }
                   12227:                             }
                   12228:                         } elsif ($newdest{$referrer{$i}}) {
                   12229:                             $fullpath = $newdest{$referrer{$i}};
                   12230:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12231:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12232:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12233:                                     last;
                   12234:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12235:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12236:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12237:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12238:                                         if (!-e $fullpath) {
                   12239:                                             mkdir($fullpath,0755);
1.1056    raeburn  12240:                                         }
                   12241:                                     }
1.1075.2.11  raeburn  12242:                                 } else {
                   12243:                                     last;
1.1056    raeburn  12244:                                 }
1.1075.2.11  raeburn  12245:                             }
                   12246:                         }
                   12247:                         if ($fullpath ne '') {
                   12248:                             if (-e "$prefix$path") {
                   12249:                                 system("mv $prefix$path $fullpath/$title");
                   12250:                             }
                   12251:                             if (-e "$fullpath/$title") {
                   12252:                                 my $showpath;
                   12253:                                 if ($relpath ne '') {
                   12254:                                     $showpath = "$relpath/$title";
                   12255:                                 } else {
                   12256:                                     $showpath = "/$title";
1.1056    raeburn  12257:                                 }
1.1075.2.11  raeburn  12258:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12259:                             }
                   12260:                             unless ($ishome) {
                   12261:                                 my $fetch = "$fullpath/$title";
                   12262:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12263:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12264:                             }
                   12265:                         }
                   12266:                     }
1.1075.2.11  raeburn  12267:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12268:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12269:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12270:                 }
                   12271:             } else {
1.1075.2.11  raeburn  12272:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12273:             }
                   12274:         }
                   12275:         if (keys(%todelete)) {
                   12276:             foreach my $key (keys(%todelete)) {
                   12277:                 unlink($key);
1.1066    raeburn  12278:             }
                   12279:         }
                   12280:         if (keys(%todeletedir)) {
                   12281:             foreach my $key (keys(%todeletedir)) {
                   12282:                 rmdir($key);
                   12283:             }
                   12284:         }
                   12285:         foreach my $dir (sort(keys(%is_dir))) {
                   12286:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12287:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12288:             }
                   12289:         }
1.1067    raeburn  12290:         if ($result ne '') {
                   12291:             $output .= '<ul>'."\n".
                   12292:                        $result."\n".
                   12293:                        '</ul>';
                   12294:         }
                   12295:         unless ($ishome) {
                   12296:             my $replicationfail;
                   12297:             foreach my $item (keys(%prompttofetch)) {
                   12298:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12299:                 unless ($fetchresult eq 'ok') {
                   12300:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12301:                 }
                   12302:             }
                   12303:             if ($replicationfail) {
                   12304:                 $output .= '<p class="LC_error">'.
                   12305:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12306:                            $replicationfail.
                   12307:                            '</ul></p>';
                   12308:             }
                   12309:         }
1.1055    raeburn  12310:     } else {
                   12311:         $warning = &mt('No items found in archive.');
                   12312:     }
                   12313:     if ($error) {
                   12314:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12315:                    $error.'</p>'."\n";
                   12316:     }
                   12317:     if ($warning) {
                   12318:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12319:     }
                   12320:     return $output;
                   12321: }
                   12322: 
1.1066    raeburn  12323: sub cleanup_empty_dirs {
                   12324:     my ($path) = @_;
                   12325:     if (($path ne '') && (-d $path)) {
                   12326:         if (opendir(my $dirh,$path)) {
                   12327:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12328:             my $numitems = 0;
                   12329:             foreach my $item (@dircontents) {
                   12330:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12331:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12332:                     if (-e "$path/$item") {
                   12333:                         $numitems ++;
                   12334:                     }
                   12335:                 } else {
                   12336:                     $numitems ++;
                   12337:                 }
                   12338:             }
                   12339:             if ($numitems == 0) {
                   12340:                 rmdir($path);
                   12341:             }
                   12342:             closedir($dirh);
                   12343:         }
                   12344:     }
                   12345:     return;
                   12346: }
                   12347: 
1.41      ng       12348: =pod
1.45      matthew  12349: 
1.1075.2.56  raeburn  12350: =item * &get_folder_hierarchy()
1.1068    raeburn  12351: 
                   12352: Provides hierarchy of names of folders/sub-folders containing the current
                   12353: item,
                   12354: 
                   12355: Inputs: 3
                   12356:      - $navmap - navmaps object
                   12357: 
                   12358:      - $map - url for map (either the trigger itself, or map containing
                   12359:                            the resource, which is the trigger).
                   12360: 
                   12361:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12362: 
                   12363: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12364: 
                   12365: =cut
                   12366: 
                   12367: sub get_folder_hierarchy {
                   12368:     my ($navmap,$map,$showitem) = @_;
                   12369:     my @pathitems;
                   12370:     if (ref($navmap)) {
                   12371:         my $mapres = $navmap->getResourceByUrl($map);
                   12372:         if (ref($mapres)) {
                   12373:             my $pcslist = $mapres->map_hierarchy();
                   12374:             if ($pcslist ne '') {
                   12375:                 my @pcs = split(/,/,$pcslist);
                   12376:                 foreach my $pc (@pcs) {
                   12377:                     if ($pc == 1) {
1.1075.2.38  raeburn  12378:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12379:                     } else {
                   12380:                         my $res = $navmap->getByMapPc($pc);
                   12381:                         if (ref($res)) {
                   12382:                             my $title = $res->compTitle();
                   12383:                             $title =~ s/\W+/_/g;
                   12384:                             if ($title ne '') {
                   12385:                                 push(@pathitems,$title);
                   12386:                             }
                   12387:                         }
                   12388:                     }
                   12389:                 }
                   12390:             }
1.1071    raeburn  12391:             if ($showitem) {
                   12392:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12393:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12394:                 } else {
                   12395:                     my $maptitle = $mapres->compTitle();
                   12396:                     $maptitle =~ s/\W+/_/g;
                   12397:                     if ($maptitle ne '') {
                   12398:                         push(@pathitems,$maptitle);
                   12399:                     }
1.1068    raeburn  12400:                 }
                   12401:             }
                   12402:         }
                   12403:     }
                   12404:     return @pathitems;
                   12405: }
                   12406: 
                   12407: =pod
                   12408: 
1.1015    raeburn  12409: =item * &get_turnedin_filepath()
                   12410: 
                   12411: Determines path in a user's portfolio file for storage of files uploaded
                   12412: to a specific essayresponse or dropbox item.
                   12413: 
                   12414: Inputs: 3 required + 1 optional.
                   12415: $symb is symb for resource, $uname and $udom are for current user (required).
                   12416: $caller is optional (can be "submission", if routine is called when storing
                   12417: an upoaded file when "Submit Answer" button was pressed).
                   12418: 
                   12419: Returns array containing $path and $multiresp. 
                   12420: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12421: than one file upload item.  Callers of routine should append partid as a 
                   12422: subdirectory to $path in cases where $multiresp is 1.
                   12423: 
                   12424: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12425: 
                   12426: =cut
                   12427: 
                   12428: sub get_turnedin_filepath {
                   12429:     my ($symb,$uname,$udom,$caller) = @_;
                   12430:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12431:     my $turnindir;
                   12432:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12433:     $turnindir = $userhash{'turnindir'};
                   12434:     my ($path,$multiresp);
                   12435:     if ($turnindir eq '') {
                   12436:         if ($caller eq 'submission') {
                   12437:             $turnindir = &mt('turned in');
                   12438:             $turnindir =~ s/\W+/_/g;
                   12439:             my %newhash = (
                   12440:                             'turnindir' => $turnindir,
                   12441:                           );
                   12442:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12443:         }
                   12444:     }
                   12445:     if ($turnindir ne '') {
                   12446:         $path = '/'.$turnindir.'/';
                   12447:         my ($multipart,$turnin,@pathitems);
                   12448:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12449:         if (defined($navmap)) {
                   12450:             my $mapres = $navmap->getResourceByUrl($map);
                   12451:             if (ref($mapres)) {
                   12452:                 my $pcslist = $mapres->map_hierarchy();
                   12453:                 if ($pcslist ne '') {
                   12454:                     foreach my $pc (split(/,/,$pcslist)) {
                   12455:                         my $res = $navmap->getByMapPc($pc);
                   12456:                         if (ref($res)) {
                   12457:                             my $title = $res->compTitle();
                   12458:                             $title =~ s/\W+/_/g;
                   12459:                             if ($title ne '') {
1.1075.2.48  raeburn  12460:                                 if (($pc > 1) && (length($title) > 12)) {
                   12461:                                     $title = substr($title,0,12);
                   12462:                                 }
1.1015    raeburn  12463:                                 push(@pathitems,$title);
                   12464:                             }
                   12465:                         }
                   12466:                     }
                   12467:                 }
                   12468:                 my $maptitle = $mapres->compTitle();
                   12469:                 $maptitle =~ s/\W+/_/g;
                   12470:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12471:                     if (length($maptitle) > 12) {
                   12472:                         $maptitle = substr($maptitle,0,12);
                   12473:                     }
1.1015    raeburn  12474:                     push(@pathitems,$maptitle);
                   12475:                 }
                   12476:                 unless ($env{'request.state'} eq 'construct') {
                   12477:                     my $res = $navmap->getBySymb($symb);
                   12478:                     if (ref($res)) {
                   12479:                         my $partlist = $res->parts();
                   12480:                         my $totaluploads = 0;
                   12481:                         if (ref($partlist) eq 'ARRAY') {
                   12482:                             foreach my $part (@{$partlist}) {
                   12483:                                 my @types = $res->responseType($part);
                   12484:                                 my @ids = $res->responseIds($part);
                   12485:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12486:                                     if ($types[$i] eq 'essay') {
                   12487:                                         my $partid = $part.'_'.$ids[$i];
                   12488:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12489:                                             $totaluploads ++;
                   12490:                                         }
                   12491:                                     }
                   12492:                                 }
                   12493:                             }
                   12494:                             if ($totaluploads > 1) {
                   12495:                                 $multiresp = 1;
                   12496:                             }
                   12497:                         }
                   12498:                     }
                   12499:                 }
                   12500:             } else {
                   12501:                 return;
                   12502:             }
                   12503:         } else {
                   12504:             return;
                   12505:         }
                   12506:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12507:         $restitle =~ s/\W+/_/g;
                   12508:         if ($restitle eq '') {
                   12509:             $restitle = ($resurl =~ m{/[^/]+$});
                   12510:             if ($restitle eq '') {
                   12511:                 $restitle = time;
                   12512:             }
                   12513:         }
1.1075.2.48  raeburn  12514:         if (length($restitle) > 12) {
                   12515:             $restitle = substr($restitle,0,12);
                   12516:         }
1.1015    raeburn  12517:         push(@pathitems,$restitle);
                   12518:         $path .= join('/',@pathitems);
                   12519:     }
                   12520:     return ($path,$multiresp);
                   12521: }
                   12522: 
                   12523: =pod
                   12524: 
1.464     albertel 12525: =back
1.41      ng       12526: 
1.112     bowersj2 12527: =head1 CSV Upload/Handling functions
1.38      albertel 12528: 
1.41      ng       12529: =over 4
                   12530: 
1.648     raeburn  12531: =item * &upfile_store($r)
1.41      ng       12532: 
                   12533: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12534: needs $env{'form.upfile'}
1.41      ng       12535: returns $datatoken to be put into hidden field
                   12536: 
                   12537: =cut
1.31      albertel 12538: 
                   12539: sub upfile_store {
                   12540:     my $r=shift;
1.258     albertel 12541:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12542:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12543:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12544:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12545: 
1.258     albertel 12546:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12547: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12548:     {
1.158     raeburn  12549:         my $datafile = $r->dir_config('lonDaemons').
                   12550:                            '/tmp/'.$datatoken.'.tmp';
                   12551:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12552:             print $fh $env{'form.upfile'};
1.158     raeburn  12553:             close($fh);
                   12554:         }
1.31      albertel 12555:     }
                   12556:     return $datatoken;
                   12557: }
                   12558: 
1.56      matthew  12559: =pod
                   12560: 
1.648     raeburn  12561: =item * &load_tmp_file($r)
1.41      ng       12562: 
                   12563: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12564: needs $env{'form.datatoken'},
                   12565: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12566: 
                   12567: =cut
1.31      albertel 12568: 
                   12569: sub load_tmp_file {
                   12570:     my $r=shift;
                   12571:     my @studentdata=();
                   12572:     {
1.158     raeburn  12573:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12574:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12575:         if ( open(my $fh,"<$studentfile") ) {
                   12576:             @studentdata=<$fh>;
                   12577:             close($fh);
                   12578:         }
1.31      albertel 12579:     }
1.258     albertel 12580:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12581: }
                   12582: 
1.56      matthew  12583: =pod
                   12584: 
1.648     raeburn  12585: =item * &upfile_record_sep()
1.41      ng       12586: 
                   12587: Separate uploaded file into records
                   12588: returns array of records,
1.258     albertel 12589: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12590: 
                   12591: =cut
1.31      albertel 12592: 
                   12593: sub upfile_record_sep {
1.258     albertel 12594:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12595:     } else {
1.248     albertel 12596: 	my @records;
1.258     albertel 12597: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12598: 	    if ($line=~/^\s*$/) { next; }
                   12599: 	    push(@records,$line);
                   12600: 	}
                   12601: 	return @records;
1.31      albertel 12602:     }
                   12603: }
                   12604: 
1.56      matthew  12605: =pod
                   12606: 
1.648     raeburn  12607: =item * &record_sep($record)
1.41      ng       12608: 
1.258     albertel 12609: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12610: 
                   12611: =cut
                   12612: 
1.263     www      12613: sub takeleft {
                   12614:     my $index=shift;
                   12615:     return substr('0000'.$index,-4,4);
                   12616: }
                   12617: 
1.31      albertel 12618: sub record_sep {
                   12619:     my $record=shift;
                   12620:     my %components=();
1.258     albertel 12621:     if ($env{'form.upfiletype'} eq 'xml') {
                   12622:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12623:         my $i=0;
1.356     albertel 12624:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12625:             $field=~s/^(\"|\')//;
                   12626:             $field=~s/(\"|\')$//;
1.263     www      12627:             $components{&takeleft($i)}=$field;
1.31      albertel 12628:             $i++;
                   12629:         }
1.258     albertel 12630:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12631:         my $i=0;
1.356     albertel 12632:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12633:             $field=~s/^(\"|\')//;
                   12634:             $field=~s/(\"|\')$//;
1.263     www      12635:             $components{&takeleft($i)}=$field;
1.31      albertel 12636:             $i++;
                   12637:         }
                   12638:     } else {
1.561     www      12639:         my $separator=',';
1.480     banghart 12640:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12641:             $separator=';';
1.480     banghart 12642:         }
1.31      albertel 12643:         my $i=0;
1.561     www      12644: # the character we are looking for to indicate the end of a quote or a record 
                   12645:         my $looking_for=$separator;
                   12646: # do not add the characters to the fields
                   12647:         my $ignore=0;
                   12648: # we just encountered a separator (or the beginning of the record)
                   12649:         my $just_found_separator=1;
                   12650: # store the field we are working on here
                   12651:         my $field='';
                   12652: # work our way through all characters in record
                   12653:         foreach my $character ($record=~/(.)/g) {
                   12654:             if ($character eq $looking_for) {
                   12655:                if ($character ne $separator) {
                   12656: # Found the end of a quote, again looking for separator
                   12657:                   $looking_for=$separator;
                   12658:                   $ignore=1;
                   12659:                } else {
                   12660: # Found a separator, store away what we got
                   12661:                   $components{&takeleft($i)}=$field;
                   12662: 	          $i++;
                   12663:                   $just_found_separator=1;
                   12664:                   $ignore=0;
                   12665:                   $field='';
                   12666:                }
                   12667:                next;
                   12668:             }
                   12669: # single or double quotation marks after a separator indicate beginning of a quote
                   12670: # we are now looking for the end of the quote and need to ignore separators
                   12671:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12672:                $looking_for=$character;
                   12673:                next;
                   12674:             }
                   12675: # ignore would be true after we reached the end of a quote
                   12676:             if ($ignore) { next; }
                   12677:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12678:             $field.=$character;
                   12679:             $just_found_separator=0; 
1.31      albertel 12680:         }
1.561     www      12681: # catch the very last entry, since we never encountered the separator
                   12682:         $components{&takeleft($i)}=$field;
1.31      albertel 12683:     }
                   12684:     return %components;
                   12685: }
                   12686: 
1.144     matthew  12687: ######################################################
                   12688: ######################################################
                   12689: 
1.56      matthew  12690: =pod
                   12691: 
1.648     raeburn  12692: =item * &upfile_select_html()
1.41      ng       12693: 
1.144     matthew  12694: Return HTML code to select a file from the users machine and specify 
                   12695: the file type.
1.41      ng       12696: 
                   12697: =cut
                   12698: 
1.144     matthew  12699: ######################################################
                   12700: ######################################################
1.31      albertel 12701: sub upfile_select_html {
1.144     matthew  12702:     my %Types = (
                   12703:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12704:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12705:                  space => &mt('Space separated'),
                   12706:                  tab   => &mt('Tabulator separated'),
                   12707: #                 xml   => &mt('HTML/XML'),
                   12708:                  );
                   12709:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12710:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12711:     foreach my $type (sort(keys(%Types))) {
                   12712:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12713:     }
                   12714:     $Str .= "</select>\n";
                   12715:     return $Str;
1.31      albertel 12716: }
                   12717: 
1.301     albertel 12718: sub get_samples {
                   12719:     my ($records,$toget) = @_;
                   12720:     my @samples=({});
                   12721:     my $got=0;
                   12722:     foreach my $rec (@$records) {
                   12723: 	my %temp = &record_sep($rec);
                   12724: 	if (! grep(/\S/, values(%temp))) { next; }
                   12725: 	if (%temp) {
                   12726: 	    $samples[$got]=\%temp;
                   12727: 	    $got++;
                   12728: 	    if ($got == $toget) { last; }
                   12729: 	}
                   12730:     }
                   12731:     return \@samples;
                   12732: }
                   12733: 
1.144     matthew  12734: ######################################################
                   12735: ######################################################
                   12736: 
1.56      matthew  12737: =pod
                   12738: 
1.648     raeburn  12739: =item * &csv_print_samples($r,$records)
1.41      ng       12740: 
                   12741: Prints a table of sample values from each column uploaded $r is an
                   12742: Apache Request ref, $records is an arrayref from
                   12743: &Apache::loncommon::upfile_record_sep
                   12744: 
                   12745: =cut
                   12746: 
1.144     matthew  12747: ######################################################
                   12748: ######################################################
1.31      albertel 12749: sub csv_print_samples {
                   12750:     my ($r,$records) = @_;
1.662     bisitz   12751:     my $samples = &get_samples($records,5);
1.301     albertel 12752: 
1.594     raeburn  12753:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12754:               &start_data_table_header_row());
1.356     albertel 12755:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12756:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12757:     $r->print(&end_data_table_header_row());
1.301     albertel 12758:     foreach my $hash (@$samples) {
1.594     raeburn  12759: 	$r->print(&start_data_table_row());
1.356     albertel 12760: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12761: 	    $r->print('<td>');
1.356     albertel 12762: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12763: 	    $r->print('</td>');
                   12764: 	}
1.594     raeburn  12765: 	$r->print(&end_data_table_row());
1.31      albertel 12766:     }
1.594     raeburn  12767:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12768: }
                   12769: 
1.144     matthew  12770: ######################################################
                   12771: ######################################################
                   12772: 
1.56      matthew  12773: =pod
                   12774: 
1.648     raeburn  12775: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12776: 
                   12777: Prints a table to create associations between values and table columns.
1.144     matthew  12778: 
1.41      ng       12779: $r is an Apache Request ref,
                   12780: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12781: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12782: 
                   12783: =cut
                   12784: 
1.144     matthew  12785: ######################################################
                   12786: ######################################################
1.31      albertel 12787: sub csv_print_select_table {
                   12788:     my ($r,$records,$d) = @_;
1.301     albertel 12789:     my $i=0;
                   12790:     my $samples = &get_samples($records,1);
1.144     matthew  12791:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12792: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12793:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12794:               '<th>'.&mt('Column').'</th>'.
                   12795:               &end_data_table_header_row()."\n");
1.356     albertel 12796:     foreach my $array_ref (@$d) {
                   12797: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12798: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12799: 
1.875     bisitz   12800: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12801: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12802: 	$r->print('<option value="none"></option>');
1.356     albertel 12803: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12804: 	    $r->print('<option value="'.$sample.'"'.
                   12805:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12806:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12807: 	}
1.594     raeburn  12808: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12809: 	$i++;
                   12810:     }
1.594     raeburn  12811:     $r->print(&end_data_table());
1.31      albertel 12812:     $i--;
                   12813:     return $i;
                   12814: }
1.56      matthew  12815: 
1.144     matthew  12816: ######################################################
                   12817: ######################################################
                   12818: 
1.56      matthew  12819: =pod
1.31      albertel 12820: 
1.648     raeburn  12821: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12822: 
                   12823: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12824: 
                   12825: $r is an Apache Request ref,
                   12826: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12827: $d is an array of 2 element arrays (internal name, displayed name)
                   12828: 
                   12829: =cut
                   12830: 
1.144     matthew  12831: ######################################################
                   12832: ######################################################
1.31      albertel 12833: sub csv_samples_select_table {
                   12834:     my ($r,$records,$d) = @_;
                   12835:     my $i=0;
1.144     matthew  12836:     #
1.662     bisitz   12837:     my $max_samples = 5;
                   12838:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12839:     $r->print(&start_data_table().
                   12840:               &start_data_table_header_row().'<th>'.
                   12841:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12842:               &end_data_table_header_row());
1.301     albertel 12843: 
                   12844:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12845: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12846: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12847: 	foreach my $option (@$d) {
                   12848: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12849: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12850:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12851:                       $display.'</option>');
1.31      albertel 12852: 	}
                   12853: 	$r->print('</select></td><td>');
1.662     bisitz   12854: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12855: 	    if (defined($samples->[$line]{$key})) { 
                   12856: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12857: 	    }
                   12858: 	}
1.594     raeburn  12859: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12860: 	$i++;
                   12861:     }
1.594     raeburn  12862:     $r->print(&end_data_table());
1.31      albertel 12863:     $i--;
                   12864:     return($i);
1.115     matthew  12865: }
                   12866: 
1.144     matthew  12867: ######################################################
                   12868: ######################################################
                   12869: 
1.115     matthew  12870: =pod
                   12871: 
1.648     raeburn  12872: =item * &clean_excel_name($name)
1.115     matthew  12873: 
                   12874: Returns a replacement for $name which does not contain any illegal characters.
                   12875: 
                   12876: =cut
                   12877: 
1.144     matthew  12878: ######################################################
                   12879: ######################################################
1.115     matthew  12880: sub clean_excel_name {
                   12881:     my ($name) = @_;
                   12882:     $name =~ s/[:\*\?\/\\]//g;
                   12883:     if (length($name) > 31) {
                   12884:         $name = substr($name,0,31);
                   12885:     }
                   12886:     return $name;
1.25      albertel 12887: }
1.84      albertel 12888: 
1.85      albertel 12889: =pod
                   12890: 
1.648     raeburn  12891: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12892: 
                   12893: Returns either 1 or undef
                   12894: 
                   12895: 1 if the part is to be hidden, undef if it is to be shown
                   12896: 
                   12897: Arguments are:
                   12898: 
                   12899: $id the id of the part to be checked
                   12900: $symb, optional the symb of the resource to check
                   12901: $udom, optional the domain of the user to check for
                   12902: $uname, optional the username of the user to check for
                   12903: 
                   12904: =cut
1.84      albertel 12905: 
                   12906: sub check_if_partid_hidden {
                   12907:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12908:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12909: 					 $symb,$udom,$uname);
1.141     albertel 12910:     my $truth=1;
                   12911:     #if the string starts with !, then the list is the list to show not hide
                   12912:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12913:     my @hiddenlist=split(/,/,$hiddenparts);
                   12914:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12915: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12916:     }
1.141     albertel 12917:     return !$truth;
1.84      albertel 12918: }
1.127     matthew  12919: 
1.138     matthew  12920: 
                   12921: ############################################################
                   12922: ############################################################
                   12923: 
                   12924: =pod
                   12925: 
1.157     matthew  12926: =back 
                   12927: 
1.138     matthew  12928: =head1 cgi-bin script and graphing routines
                   12929: 
1.157     matthew  12930: =over 4
                   12931: 
1.648     raeburn  12932: =item * &get_cgi_id()
1.138     matthew  12933: 
                   12934: Inputs: none
                   12935: 
                   12936: Returns an id which can be used to pass environment variables
                   12937: to various cgi-bin scripts.  These environment variables will
                   12938: be removed from the users environment after a given time by
                   12939: the routine &Apache::lonnet::transfer_profile_to_env.
                   12940: 
                   12941: =cut
                   12942: 
                   12943: ############################################################
                   12944: ############################################################
1.152     albertel 12945: my $uniq=0;
1.136     matthew  12946: sub get_cgi_id {
1.154     albertel 12947:     $uniq=($uniq+1)%100000;
1.280     albertel 12948:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12949: }
                   12950: 
1.127     matthew  12951: ############################################################
                   12952: ############################################################
                   12953: 
                   12954: =pod
                   12955: 
1.648     raeburn  12956: =item * &DrawBarGraph()
1.127     matthew  12957: 
1.138     matthew  12958: Facilitates the plotting of data in a (stacked) bar graph.
                   12959: Puts plot definition data into the users environment in order for 
                   12960: graph.png to plot it.  Returns an <img> tag for the plot.
                   12961: The bars on the plot are labeled '1','2',...,'n'.
                   12962: 
                   12963: Inputs:
                   12964: 
                   12965: =over 4
                   12966: 
                   12967: =item $Title: string, the title of the plot
                   12968: 
                   12969: =item $xlabel: string, text describing the X-axis of the plot
                   12970: 
                   12971: =item $ylabel: string, text describing the Y-axis of the plot
                   12972: 
                   12973: =item $Max: scalar, the maximum Y value to use in the plot
                   12974: If $Max is < any data point, the graph will not be rendered.
                   12975: 
1.140     matthew  12976: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12977: they are plotted.  If undefined, default values will be used.
                   12978: 
1.178     matthew  12979: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12980: 
1.138     matthew  12981: =item @Values: An array of array references.  Each array reference holds data
                   12982: to be plotted in a stacked bar chart.
                   12983: 
1.239     matthew  12984: =item If the final element of @Values is a hash reference the key/value
                   12985: pairs will be added to the graph definition.
                   12986: 
1.138     matthew  12987: =back
                   12988: 
                   12989: Returns:
                   12990: 
                   12991: An <img> tag which references graph.png and the appropriate identifying
                   12992: information for the plot.
                   12993: 
1.127     matthew  12994: =cut
                   12995: 
                   12996: ############################################################
                   12997: ############################################################
1.134     matthew  12998: sub DrawBarGraph {
1.178     matthew  12999:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13000:     #
                   13001:     if (! defined($colors)) {
                   13002:         $colors = ['#33ff00', 
                   13003:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13004:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13005:                   ]; 
                   13006:     }
1.228     matthew  13007:     my $extra_settings = {};
                   13008:     if (ref($Values[-1]) eq 'HASH') {
                   13009:         $extra_settings = pop(@Values);
                   13010:     }
1.127     matthew  13011:     #
1.136     matthew  13012:     my $identifier = &get_cgi_id();
                   13013:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13014:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13015:         return '';
                   13016:     }
1.225     matthew  13017:     #
                   13018:     my @Labels;
                   13019:     if (defined($labels)) {
                   13020:         @Labels = @$labels;
                   13021:     } else {
                   13022:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13023:             push (@Labels,$i+1);
                   13024:         }
                   13025:     }
                   13026:     #
1.129     matthew  13027:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13028:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13029:     my %ValuesHash;
                   13030:     my $NumSets=1;
                   13031:     foreach my $array (@Values) {
                   13032:         next if (! ref($array));
1.136     matthew  13033:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13034:             join(',',@$array);
1.129     matthew  13035:     }
1.127     matthew  13036:     #
1.136     matthew  13037:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13038:     if ($NumBars < 3) {
                   13039:         $width = 120+$NumBars*32;
1.220     matthew  13040:         $xskip = 1;
1.225     matthew  13041:         $bar_width = 30;
                   13042:     } elsif ($NumBars < 5) {
                   13043:         $width = 120+$NumBars*20;
                   13044:         $xskip = 1;
                   13045:         $bar_width = 20;
1.220     matthew  13046:     } elsif ($NumBars < 10) {
1.136     matthew  13047:         $width = 120+$NumBars*15;
                   13048:         $xskip = 1;
                   13049:         $bar_width = 15;
                   13050:     } elsif ($NumBars <= 25) {
                   13051:         $width = 120+$NumBars*11;
                   13052:         $xskip = 5;
                   13053:         $bar_width = 8;
                   13054:     } elsif ($NumBars <= 50) {
                   13055:         $width = 120+$NumBars*8;
                   13056:         $xskip = 5;
                   13057:         $bar_width = 4;
                   13058:     } else {
                   13059:         $width = 120+$NumBars*8;
                   13060:         $xskip = 5;
                   13061:         $bar_width = 4;
                   13062:     }
                   13063:     #
1.137     matthew  13064:     $Max = 1 if ($Max < 1);
                   13065:     if ( int($Max) < $Max ) {
                   13066:         $Max++;
                   13067:         $Max = int($Max);
                   13068:     }
1.127     matthew  13069:     $Title  = '' if (! defined($Title));
                   13070:     $xlabel = '' if (! defined($xlabel));
                   13071:     $ylabel = '' if (! defined($ylabel));
1.369     www      13072:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13073:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13074:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13075:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13076:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13077:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13078:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13079:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13080:     $ValuesHash{$id.'.height'}   = $height;
                   13081:     $ValuesHash{$id.'.width'}    = $width;
                   13082:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13083:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13084:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13085:     #
1.228     matthew  13086:     # Deal with other parameters
                   13087:     while (my ($key,$value) = each(%$extra_settings)) {
                   13088:         $ValuesHash{$id.'.'.$key} = $value;
                   13089:     }
                   13090:     #
1.646     raeburn  13091:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13092:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13093: }
                   13094: 
                   13095: ############################################################
                   13096: ############################################################
                   13097: 
                   13098: =pod
                   13099: 
1.648     raeburn  13100: =item * &DrawXYGraph()
1.137     matthew  13101: 
1.138     matthew  13102: Facilitates the plotting of data in an XY graph.
                   13103: Puts plot definition data into the users environment in order for 
                   13104: graph.png to plot it.  Returns an <img> tag for the plot.
                   13105: 
                   13106: Inputs:
                   13107: 
                   13108: =over 4
                   13109: 
                   13110: =item $Title: string, the title of the plot
                   13111: 
                   13112: =item $xlabel: string, text describing the X-axis of the plot
                   13113: 
                   13114: =item $ylabel: string, text describing the Y-axis of the plot
                   13115: 
                   13116: =item $Max: scalar, the maximum Y value to use in the plot
                   13117: If $Max is < any data point, the graph will not be rendered.
                   13118: 
                   13119: =item $colors: Array ref containing the hex color codes for the data to be 
                   13120: plotted in.  If undefined, default values will be used.
                   13121: 
                   13122: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13123: 
                   13124: =item $Ydata: Array ref containing Array refs.  
1.185     www      13125: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13126: 
                   13127: =item %Values: hash indicating or overriding any default values which are 
                   13128: passed to graph.png.  
                   13129: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13130: 
                   13131: =back
                   13132: 
                   13133: Returns:
                   13134: 
                   13135: An <img> tag which references graph.png and the appropriate identifying
                   13136: information for the plot.
                   13137: 
1.137     matthew  13138: =cut
                   13139: 
                   13140: ############################################################
                   13141: ############################################################
                   13142: sub DrawXYGraph {
                   13143:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13144:     #
                   13145:     # Create the identifier for the graph
                   13146:     my $identifier = &get_cgi_id();
                   13147:     my $id = 'cgi.'.$identifier;
                   13148:     #
                   13149:     $Title  = '' if (! defined($Title));
                   13150:     $xlabel = '' if (! defined($xlabel));
                   13151:     $ylabel = '' if (! defined($ylabel));
                   13152:     my %ValuesHash = 
                   13153:         (
1.369     www      13154:          $id.'.title'  => &escape($Title),
                   13155:          $id.'.xlabel' => &escape($xlabel),
                   13156:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13157:          $id.'.y_max_value'=> $Max,
                   13158:          $id.'.labels'     => join(',',@$Xlabels),
                   13159:          $id.'.PlotType'   => 'XY',
                   13160:          );
                   13161:     #
                   13162:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13163:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13164:     }
                   13165:     #
                   13166:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13167:         return '';
                   13168:     }
                   13169:     my $NumSets=1;
1.138     matthew  13170:     foreach my $array (@{$Ydata}){
1.137     matthew  13171:         next if (! ref($array));
                   13172:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13173:     }
1.138     matthew  13174:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13175:     #
                   13176:     # Deal with other parameters
                   13177:     while (my ($key,$value) = each(%Values)) {
                   13178:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13179:     }
                   13180:     #
1.646     raeburn  13181:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13182:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13183: }
                   13184: 
                   13185: ############################################################
                   13186: ############################################################
                   13187: 
                   13188: =pod
                   13189: 
1.648     raeburn  13190: =item * &DrawXYYGraph()
1.138     matthew  13191: 
                   13192: Facilitates the plotting of data in an XY graph with two Y axes.
                   13193: Puts plot definition data into the users environment in order for 
                   13194: graph.png to plot it.  Returns an <img> tag for the plot.
                   13195: 
                   13196: Inputs:
                   13197: 
                   13198: =over 4
                   13199: 
                   13200: =item $Title: string, the title of the plot
                   13201: 
                   13202: =item $xlabel: string, text describing the X-axis of the plot
                   13203: 
                   13204: =item $ylabel: string, text describing the Y-axis of the plot
                   13205: 
                   13206: =item $colors: Array ref containing the hex color codes for the data to be 
                   13207: plotted in.  If undefined, default values will be used.
                   13208: 
                   13209: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13210: 
                   13211: =item $Ydata1: The first data set
                   13212: 
                   13213: =item $Min1: The minimum value of the left Y-axis
                   13214: 
                   13215: =item $Max1: The maximum value of the left Y-axis
                   13216: 
                   13217: =item $Ydata2: The second data set
                   13218: 
                   13219: =item $Min2: The minimum value of the right Y-axis
                   13220: 
                   13221: =item $Max2: The maximum value of the left Y-axis
                   13222: 
                   13223: =item %Values: hash indicating or overriding any default values which are 
                   13224: passed to graph.png.  
                   13225: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13226: 
                   13227: =back
                   13228: 
                   13229: Returns:
                   13230: 
                   13231: An <img> tag which references graph.png and the appropriate identifying
                   13232: information for the plot.
1.136     matthew  13233: 
                   13234: =cut
                   13235: 
                   13236: ############################################################
                   13237: ############################################################
1.137     matthew  13238: sub DrawXYYGraph {
                   13239:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13240:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13241:     #
                   13242:     # Create the identifier for the graph
                   13243:     my $identifier = &get_cgi_id();
                   13244:     my $id = 'cgi.'.$identifier;
                   13245:     #
                   13246:     $Title  = '' if (! defined($Title));
                   13247:     $xlabel = '' if (! defined($xlabel));
                   13248:     $ylabel = '' if (! defined($ylabel));
                   13249:     my %ValuesHash = 
                   13250:         (
1.369     www      13251:          $id.'.title'  => &escape($Title),
                   13252:          $id.'.xlabel' => &escape($xlabel),
                   13253:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13254:          $id.'.labels' => join(',',@$Xlabels),
                   13255:          $id.'.PlotType' => 'XY',
                   13256:          $id.'.NumSets' => 2,
1.137     matthew  13257:          $id.'.two_axes' => 1,
                   13258:          $id.'.y1_max_value' => $Max1,
                   13259:          $id.'.y1_min_value' => $Min1,
                   13260:          $id.'.y2_max_value' => $Max2,
                   13261:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13262:          );
                   13263:     #
1.137     matthew  13264:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13265:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13266:     }
                   13267:     #
                   13268:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13269:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13270:         return '';
                   13271:     }
                   13272:     my $NumSets=1;
1.137     matthew  13273:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13274:         next if (! ref($array));
                   13275:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13276:     }
                   13277:     #
                   13278:     # Deal with other parameters
                   13279:     while (my ($key,$value) = each(%Values)) {
                   13280:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13281:     }
                   13282:     #
1.646     raeburn  13283:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13284:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13285: }
                   13286: 
                   13287: ############################################################
                   13288: ############################################################
                   13289: 
                   13290: =pod
                   13291: 
1.157     matthew  13292: =back 
                   13293: 
1.139     matthew  13294: =head1 Statistics helper routines?  
                   13295: 
                   13296: Bad place for them but what the hell.
                   13297: 
1.157     matthew  13298: =over 4
                   13299: 
1.648     raeburn  13300: =item * &chartlink()
1.139     matthew  13301: 
                   13302: Returns a link to the chart for a specific student.  
                   13303: 
                   13304: Inputs:
                   13305: 
                   13306: =over 4
                   13307: 
                   13308: =item $linktext: The text of the link
                   13309: 
                   13310: =item $sname: The students username
                   13311: 
                   13312: =item $sdomain: The students domain
                   13313: 
                   13314: =back
                   13315: 
1.157     matthew  13316: =back
                   13317: 
1.139     matthew  13318: =cut
                   13319: 
                   13320: ############################################################
                   13321: ############################################################
                   13322: sub chartlink {
                   13323:     my ($linktext, $sname, $sdomain) = @_;
                   13324:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13325:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13326:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13327:        '">'.$linktext.'</a>';
1.153     matthew  13328: }
                   13329: 
                   13330: #######################################################
                   13331: #######################################################
                   13332: 
                   13333: =pod
                   13334: 
                   13335: =head1 Course Environment Routines
1.157     matthew  13336: 
                   13337: =over 4
1.153     matthew  13338: 
1.648     raeburn  13339: =item * &restore_course_settings()
1.153     matthew  13340: 
1.648     raeburn  13341: =item * &store_course_settings()
1.153     matthew  13342: 
                   13343: Restores/Store indicated form parameters from the course environment.
                   13344: Will not overwrite existing values of the form parameters.
                   13345: 
                   13346: Inputs: 
                   13347: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13348: 
                   13349: a hash ref describing the data to be stored.  For example:
                   13350:    
                   13351: %Save_Parameters = ('Status' => 'scalar',
                   13352:     'chartoutputmode' => 'scalar',
                   13353:     'chartoutputdata' => 'scalar',
                   13354:     'Section' => 'array',
1.373     raeburn  13355:     'Group' => 'array',
1.153     matthew  13356:     'StudentData' => 'array',
                   13357:     'Maps' => 'array');
                   13358: 
                   13359: Returns: both routines return nothing
                   13360: 
1.631     raeburn  13361: =back
                   13362: 
1.153     matthew  13363: =cut
                   13364: 
                   13365: #######################################################
                   13366: #######################################################
                   13367: sub store_course_settings {
1.496     albertel 13368:     return &store_settings($env{'request.course.id'},@_);
                   13369: }
                   13370: 
                   13371: sub store_settings {
1.153     matthew  13372:     # save to the environment
                   13373:     # appenv the same items, just to be safe
1.300     albertel 13374:     my $udom  = $env{'user.domain'};
                   13375:     my $uname = $env{'user.name'};
1.496     albertel 13376:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13377:     my %SaveHash;
                   13378:     my %AppHash;
                   13379:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13380:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13381:         my $envname = 'environment.'.$basename;
1.258     albertel 13382:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13383:             # Save this value away
                   13384:             if ($type eq 'scalar' &&
1.258     albertel 13385:                 (! exists($env{$envname}) || 
                   13386:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13387:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13388:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13389:             } elsif ($type eq 'array') {
                   13390:                 my $stored_form;
1.258     albertel 13391:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13392:                     $stored_form = join(',',
                   13393:                                         map {
1.369     www      13394:                                             &escape($_);
1.258     albertel 13395:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13396:                 } else {
                   13397:                     $stored_form = 
1.369     www      13398:                         &escape($env{'form.'.$setting});
1.153     matthew  13399:                 }
                   13400:                 # Determine if the array contents are the same.
1.258     albertel 13401:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13402:                     $SaveHash{$basename} = $stored_form;
                   13403:                     $AppHash{$envname}   = $stored_form;
                   13404:                 }
                   13405:             }
                   13406:         }
                   13407:     }
                   13408:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13409:                                           $udom,$uname);
1.153     matthew  13410:     if ($put_result !~ /^(ok|delayed)/) {
                   13411:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13412:                                  'got error:'.$put_result);
                   13413:     }
                   13414:     # Make sure these settings stick around in this session, too
1.646     raeburn  13415:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13416:     return;
                   13417: }
                   13418: 
                   13419: sub restore_course_settings {
1.499     albertel 13420:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13421: }
                   13422: 
                   13423: sub restore_settings {
                   13424:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13425:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13426:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13427:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13428:             '.'.$setting;
1.258     albertel 13429:         if (exists($env{$envname})) {
1.153     matthew  13430:             if ($type eq 'scalar') {
1.258     albertel 13431:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13432:             } elsif ($type eq 'array') {
1.258     albertel 13433:                 $env{'form.'.$setting} = [ 
1.153     matthew  13434:                                            map { 
1.369     www      13435:                                                &unescape($_); 
1.258     albertel 13436:                                            } split(',',$env{$envname})
1.153     matthew  13437:                                            ];
                   13438:             }
                   13439:         }
                   13440:     }
1.127     matthew  13441: }
                   13442: 
1.618     raeburn  13443: #######################################################
                   13444: #######################################################
                   13445: 
                   13446: =pod
                   13447: 
                   13448: =head1 Domain E-mail Routines  
                   13449: 
                   13450: =over 4
                   13451: 
1.648     raeburn  13452: =item * &build_recipient_list()
1.618     raeburn  13453: 
1.1075.2.44  raeburn  13454: Build recipient lists for following types of e-mail:
1.766     raeburn  13455: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13456: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13457: module change checking, student/employee ID conflict checks, as
                   13458: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13459: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13460: 
                   13461: Inputs:
1.1075.2.44  raeburn  13462: defmail (scalar - email address of default recipient),
                   13463: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13464: requestsmail, updatesmail, or idconflictsmail).
                   13465: 
1.619     raeburn  13466: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13467: 
                   13468: origmail (scalar - email address of recipient from loncapa.conf,
                   13469: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13470: 
1.655     raeburn  13471: Returns: comma separated list of addresses to which to send e-mail.
                   13472: 
                   13473: =back
1.618     raeburn  13474: 
                   13475: =cut
                   13476: 
                   13477: ############################################################
                   13478: ############################################################
                   13479: sub build_recipient_list {
1.619     raeburn  13480:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13481:     my @recipients;
                   13482:     my $otheremails;
                   13483:     my %domconfig =
                   13484:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13485:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13486:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13487:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13488:                 my @contacts = ('adminemail','supportemail');
                   13489:                 foreach my $item (@contacts) {
                   13490:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13491:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13492:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13493:                             push(@recipients,$addr);
                   13494:                         }
1.619     raeburn  13495:                     }
1.766     raeburn  13496:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13497:                 }
                   13498:             }
1.766     raeburn  13499:         } elsif ($origmail ne '') {
                   13500:             push(@recipients,$origmail);
1.618     raeburn  13501:         }
1.619     raeburn  13502:     } elsif ($origmail ne '') {
                   13503:         push(@recipients,$origmail);
1.618     raeburn  13504:     }
1.688     raeburn  13505:     if (defined($defmail)) {
                   13506:         if ($defmail ne '') {
                   13507:             push(@recipients,$defmail);
                   13508:         }
1.618     raeburn  13509:     }
                   13510:     if ($otheremails) {
1.619     raeburn  13511:         my @others;
                   13512:         if ($otheremails =~ /,/) {
                   13513:             @others = split(/,/,$otheremails);
1.618     raeburn  13514:         } else {
1.619     raeburn  13515:             push(@others,$otheremails);
                   13516:         }
                   13517:         foreach my $addr (@others) {
                   13518:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13519:                 push(@recipients,$addr);
                   13520:             }
1.618     raeburn  13521:         }
                   13522:     }
1.619     raeburn  13523:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13524:     return $recipientlist;
                   13525: }
                   13526: 
1.127     matthew  13527: ############################################################
                   13528: ############################################################
1.154     albertel 13529: 
1.655     raeburn  13530: =pod
                   13531: 
                   13532: =head1 Course Catalog Routines
                   13533: 
                   13534: =over 4
                   13535: 
                   13536: =item * &gather_categories()
                   13537: 
                   13538: Converts category definitions - keys of categories hash stored in  
                   13539: coursecategories in configuration.db on the primary library server in a 
                   13540: domain - to an array.  Also generates javascript and idx hash used to 
                   13541: generate Domain Coordinator interface for editing Course Categories.
                   13542: 
                   13543: Inputs:
1.663     raeburn  13544: 
1.655     raeburn  13545: categories (reference to hash of category definitions).
1.663     raeburn  13546: 
1.655     raeburn  13547: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13548:       categories and subcategories).
1.663     raeburn  13549: 
1.655     raeburn  13550: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13551:       editing Course Categories).
1.663     raeburn  13552: 
1.655     raeburn  13553: jsarray (reference to array of categories used to create Javascript arrays for
                   13554:          Domain Coordinator interface for editing Course Categories).
                   13555: 
                   13556: Returns: nothing
                   13557: 
                   13558: Side effects: populates cats, idx and jsarray. 
                   13559: 
                   13560: =cut
                   13561: 
                   13562: sub gather_categories {
                   13563:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13564:     my %counters;
                   13565:     my $num = 0;
                   13566:     foreach my $item (keys(%{$categories})) {
                   13567:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13568:         if ($container eq '' && $depth == 0) {
                   13569:             $cats->[$depth][$categories->{$item}] = $cat;
                   13570:         } else {
                   13571:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13572:         }
                   13573:         my ($escitem,$tail) = split(/:/,$item,2);
                   13574:         if ($counters{$tail} eq '') {
                   13575:             $counters{$tail} = $num;
                   13576:             $num ++;
                   13577:         }
                   13578:         if (ref($idx) eq 'HASH') {
                   13579:             $idx->{$item} = $counters{$tail};
                   13580:         }
                   13581:         if (ref($jsarray) eq 'ARRAY') {
                   13582:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13583:         }
                   13584:     }
                   13585:     return;
                   13586: }
                   13587: 
                   13588: =pod
                   13589: 
                   13590: =item * &extract_categories()
                   13591: 
                   13592: Used to generate breadcrumb trails for course categories.
                   13593: 
                   13594: Inputs:
1.663     raeburn  13595: 
1.655     raeburn  13596: categories (reference to hash of category definitions).
1.663     raeburn  13597: 
1.655     raeburn  13598: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13599:       categories and subcategories).
1.663     raeburn  13600: 
1.655     raeburn  13601: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13602: 
1.655     raeburn  13603: allitems (reference to hash - key is category key 
                   13604:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13605: 
1.655     raeburn  13606: idx (reference to hash of counters used in Domain Coordinator interface for
                   13607:       editing Course Categories).
1.663     raeburn  13608: 
1.655     raeburn  13609: jsarray (reference to array of categories used to create Javascript arrays for
                   13610:          Domain Coordinator interface for editing Course Categories).
                   13611: 
1.665     raeburn  13612: subcats (reference to hash of arrays containing all subcategories within each 
                   13613:          category, -recursive)
                   13614: 
1.655     raeburn  13615: Returns: nothing
                   13616: 
                   13617: Side effects: populates trails and allitems hash references.
                   13618: 
                   13619: =cut
                   13620: 
                   13621: sub extract_categories {
1.665     raeburn  13622:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13623:     if (ref($categories) eq 'HASH') {
                   13624:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13625:         if (ref($cats->[0]) eq 'ARRAY') {
                   13626:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13627:                 my $name = $cats->[0][$i];
                   13628:                 my $item = &escape($name).'::0';
                   13629:                 my $trailstr;
                   13630:                 if ($name eq 'instcode') {
                   13631:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13632:                 } elsif ($name eq 'communities') {
                   13633:                     $trailstr = &mt('Communities');
1.655     raeburn  13634:                 } else {
                   13635:                     $trailstr = $name;
                   13636:                 }
                   13637:                 if ($allitems->{$item} eq '') {
                   13638:                     push(@{$trails},$trailstr);
                   13639:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13640:                 }
                   13641:                 my @parents = ($name);
                   13642:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13643:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13644:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13645:                         if (ref($subcats) eq 'HASH') {
                   13646:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13647:                         }
                   13648:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13649:                     }
                   13650:                 } else {
                   13651:                     if (ref($subcats) eq 'HASH') {
                   13652:                         $subcats->{$item} = [];
1.655     raeburn  13653:                     }
                   13654:                 }
                   13655:             }
                   13656:         }
                   13657:     }
                   13658:     return;
                   13659: }
                   13660: 
                   13661: =pod
                   13662: 
1.1075.2.56  raeburn  13663: =item * &recurse_categories()
1.655     raeburn  13664: 
                   13665: Recursively used to generate breadcrumb trails for course categories.
                   13666: 
                   13667: Inputs:
1.663     raeburn  13668: 
1.655     raeburn  13669: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13670:       categories and subcategories).
1.663     raeburn  13671: 
1.655     raeburn  13672: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13673: 
                   13674: category (current course category, for which breadcrumb trail is being generated).
                   13675: 
                   13676: trails (reference to array of breadcrumb trails for each category).
                   13677: 
1.655     raeburn  13678: allitems (reference to hash - key is category key
                   13679:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13680: 
1.655     raeburn  13681: parents (array containing containers directories for current category, 
                   13682:          back to top level). 
                   13683: 
                   13684: Returns: nothing
                   13685: 
                   13686: Side effects: populates trails and allitems hash references
                   13687: 
                   13688: =cut
                   13689: 
                   13690: sub recurse_categories {
1.665     raeburn  13691:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13692:     my $shallower = $depth - 1;
                   13693:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13694:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13695:             my $name = $cats->[$depth]{$category}[$k];
                   13696:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13697:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13698:             if ($allitems->{$item} eq '') {
                   13699:                 push(@{$trails},$trailstr);
                   13700:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13701:             }
                   13702:             my $deeper = $depth+1;
                   13703:             push(@{$parents},$category);
1.665     raeburn  13704:             if (ref($subcats) eq 'HASH') {
                   13705:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13706:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13707:                     my $higher;
                   13708:                     if ($j > 0) {
                   13709:                         $higher = &escape($parents->[$j]).':'.
                   13710:                                   &escape($parents->[$j-1]).':'.$j;
                   13711:                     } else {
                   13712:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13713:                     }
                   13714:                     push(@{$subcats->{$higher}},$subcat);
                   13715:                 }
                   13716:             }
                   13717:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13718:                                 $subcats);
1.655     raeburn  13719:             pop(@{$parents});
                   13720:         }
                   13721:     } else {
                   13722:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13723:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13724:         if ($allitems->{$item} eq '') {
                   13725:             push(@{$trails},$trailstr);
                   13726:             $allitems->{$item} = scalar(@{$trails})-1;
                   13727:         }
                   13728:     }
                   13729:     return;
                   13730: }
                   13731: 
1.663     raeburn  13732: =pod
                   13733: 
1.1075.2.56  raeburn  13734: =item * &assign_categories_table()
1.663     raeburn  13735: 
                   13736: Create a datatable for display of hierarchical categories in a domain,
                   13737: with checkboxes to allow a course to be categorized. 
                   13738: 
                   13739: Inputs:
                   13740: 
                   13741: cathash - reference to hash of categories defined for the domain (from
                   13742:           configuration.db)
                   13743: 
                   13744: currcat - scalar with an & separated list of categories assigned to a course. 
                   13745: 
1.919     raeburn  13746: type    - scalar contains course type (Course or Community).
                   13747: 
1.663     raeburn  13748: Returns: $output (markup to be displayed) 
                   13749: 
                   13750: =cut
                   13751: 
                   13752: sub assign_categories_table {
1.919     raeburn  13753:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13754:     my $output;
                   13755:     if (ref($cathash) eq 'HASH') {
                   13756:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13757:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13758:         $maxdepth = scalar(@cats);
                   13759:         if (@cats > 0) {
                   13760:             my $itemcount = 0;
                   13761:             if (ref($cats[0]) eq 'ARRAY') {
                   13762:                 my @currcategories;
                   13763:                 if ($currcat ne '') {
                   13764:                     @currcategories = split('&',$currcat);
                   13765:                 }
1.919     raeburn  13766:                 my $table;
1.663     raeburn  13767:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13768:                     my $parent = $cats[0][$i];
1.919     raeburn  13769:                     next if ($parent eq 'instcode');
                   13770:                     if ($type eq 'Community') {
                   13771:                         next unless ($parent eq 'communities');
                   13772:                     } else {
                   13773:                         next if ($parent eq 'communities');
                   13774:                     }
1.663     raeburn  13775:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13776:                     my $item = &escape($parent).'::0';
                   13777:                     my $checked = '';
                   13778:                     if (@currcategories > 0) {
                   13779:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13780:                             $checked = ' checked="checked"';
1.663     raeburn  13781:                         }
                   13782:                     }
1.919     raeburn  13783:                     my $parent_title = $parent;
                   13784:                     if ($parent eq 'communities') {
                   13785:                         $parent_title = &mt('Communities');
                   13786:                     }
                   13787:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13788:                               '<input type="checkbox" name="usecategory" value="'.
                   13789:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13790:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13791:                     my $depth = 1;
                   13792:                     push(@path,$parent);
1.919     raeburn  13793:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13794:                     pop(@path);
1.919     raeburn  13795:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13796:                     $itemcount ++;
                   13797:                 }
1.919     raeburn  13798:                 if ($itemcount) {
                   13799:                     $output = &Apache::loncommon::start_data_table().
                   13800:                               $table.
                   13801:                               &Apache::loncommon::end_data_table();
                   13802:                 }
1.663     raeburn  13803:             }
                   13804:         }
                   13805:     }
                   13806:     return $output;
                   13807: }
                   13808: 
                   13809: =pod
                   13810: 
1.1075.2.56  raeburn  13811: =item * &assign_category_rows()
1.663     raeburn  13812: 
                   13813: Create a datatable row for display of nested categories in a domain,
                   13814: with checkboxes to allow a course to be categorized,called recursively.
                   13815: 
                   13816: Inputs:
                   13817: 
                   13818: itemcount - track row number for alternating colors
                   13819: 
                   13820: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13821:       categories and subcategories.
                   13822: 
                   13823: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13824: 
                   13825: parent - parent of current category item
                   13826: 
                   13827: path - Array containing all categories back up through the hierarchy from the
                   13828:        current category to the top level.
                   13829: 
                   13830: currcategories - reference to array of current categories assigned to the course
                   13831: 
                   13832: Returns: $output (markup to be displayed).
                   13833: 
                   13834: =cut
                   13835: 
                   13836: sub assign_category_rows {
                   13837:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13838:     my ($text,$name,$item,$chgstr);
                   13839:     if (ref($cats) eq 'ARRAY') {
                   13840:         my $maxdepth = scalar(@{$cats});
                   13841:         if (ref($cats->[$depth]) eq 'HASH') {
                   13842:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13843:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13844:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  13845:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  13846:                 for (my $j=0; $j<$numchildren; $j++) {
                   13847:                     $name = $cats->[$depth]{$parent}[$j];
                   13848:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13849:                     my $deeper = $depth+1;
                   13850:                     my $checked = '';
                   13851:                     if (ref($currcategories) eq 'ARRAY') {
                   13852:                         if (@{$currcategories} > 0) {
                   13853:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13854:                                 $checked = ' checked="checked"';
1.663     raeburn  13855:                             }
                   13856:                         }
                   13857:                     }
1.664     raeburn  13858:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13859:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13860:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13861:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13862:                              '</td><td>';
1.663     raeburn  13863:                     if (ref($path) eq 'ARRAY') {
                   13864:                         push(@{$path},$name);
                   13865:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13866:                         pop(@{$path});
                   13867:                     }
                   13868:                     $text .= '</td></tr>';
                   13869:                 }
                   13870:                 $text .= '</table></td>';
                   13871:             }
                   13872:         }
                   13873:     }
                   13874:     return $text;
                   13875: }
                   13876: 
1.1075.2.69  raeburn  13877: =pod
                   13878: 
                   13879: =back
                   13880: 
                   13881: =cut
                   13882: 
1.655     raeburn  13883: ############################################################
                   13884: ############################################################
                   13885: 
                   13886: 
1.443     albertel 13887: sub commit_customrole {
1.664     raeburn  13888:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13889:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13890:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13891:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13892:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13893:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13894:                  '</b><br />';
                   13895:     return $output;
                   13896: }
                   13897: 
                   13898: sub commit_standardrole {
1.1075.2.31  raeburn  13899:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13900:     my ($output,$logmsg,$linefeed);
                   13901:     if ($context eq 'auto') {
                   13902:         $linefeed = "\n";
                   13903:     } else {
                   13904:         $linefeed = "<br />\n";
                   13905:     }  
1.443     albertel 13906:     if ($three eq 'st') {
1.541     raeburn  13907:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  13908:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13909:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13910:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13911:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13912:         } else {
1.541     raeburn  13913:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13914:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13915:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13916:             if ($context eq 'auto') {
                   13917:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13918:             } else {
                   13919:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13920:                &mt('Add to classlist').': <b>ok</b>';
                   13921:             }
                   13922:             $output .= $linefeed;
1.443     albertel 13923:         }
                   13924:     } else {
                   13925:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13926:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13927:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13928:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13929:         if ($context eq 'auto') {
                   13930:             $output .= $result.$linefeed;
                   13931:         } else {
                   13932:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13933:         }
1.443     albertel 13934:     }
                   13935:     return $output;
                   13936: }
                   13937: 
                   13938: sub commit_studentrole {
1.1075.2.31  raeburn  13939:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13940:         $credits) = @_;
1.626     raeburn  13941:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13942:     if ($context eq 'auto') {
                   13943:         $linefeed = "\n";
                   13944:     } else {
                   13945:         $linefeed = '<br />'."\n";
                   13946:     }
1.443     albertel 13947:     if (defined($one) && defined($two)) {
                   13948:         my $cid=$one.'_'.$two;
                   13949:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13950:         my $secchange = 0;
                   13951:         my $expire_role_result;
                   13952:         my $modify_section_result;
1.628     raeburn  13953:         if ($oldsec ne '-1') { 
                   13954:             if ($oldsec ne $sec) {
1.443     albertel 13955:                 $secchange = 1;
1.628     raeburn  13956:                 my $now = time;
1.443     albertel 13957:                 my $uurl='/'.$cid;
                   13958:                 $uurl=~s/\_/\//g;
                   13959:                 if ($oldsec) {
                   13960:                     $uurl.='/'.$oldsec;
                   13961:                 }
1.626     raeburn  13962:                 $oldsecurl = $uurl;
1.628     raeburn  13963:                 $expire_role_result = 
1.652     raeburn  13964:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13965:                 if ($env{'request.course.sec'} ne '') { 
                   13966:                     if ($expire_role_result eq 'refused') {
                   13967:                         my @roles = ('st');
                   13968:                         my @statuses = ('previous');
                   13969:                         my @roledoms = ($one);
                   13970:                         my $withsec = 1;
                   13971:                         my %roleshash = 
                   13972:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13973:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13974:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13975:                             my ($oldstart,$oldend) = 
                   13976:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13977:                             if ($oldend > 0 && $oldend <= $now) {
                   13978:                                 $expire_role_result = 'ok';
                   13979:                             }
                   13980:                         }
                   13981:                     }
                   13982:                 }
1.443     albertel 13983:                 $result = $expire_role_result;
                   13984:             }
                   13985:         }
                   13986:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  13987:             $modify_section_result = 
                   13988:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13989:                                                            undef,undef,undef,$sec,
                   13990:                                                            $end,$start,'','',$cid,
                   13991:                                                            '',$context,$credits);
1.443     albertel 13992:             if ($modify_section_result =~ /^ok/) {
                   13993:                 if ($secchange == 1) {
1.628     raeburn  13994:                     if ($sec eq '') {
                   13995:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13996:                     } else {
                   13997:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13998:                     }
1.443     albertel 13999:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14000:                     if ($sec eq '') {
                   14001:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14002:                     } else {
                   14003:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14004:                     }
1.443     albertel 14005:                 } else {
1.628     raeburn  14006:                     if ($sec eq '') {
                   14007:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14008:                     } else {
                   14009:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14010:                     }
1.443     albertel 14011:                 }
                   14012:             } else {
1.628     raeburn  14013:                 if ($secchange) {       
                   14014:                     $$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;
                   14015:                 } else {
                   14016:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14017:                 }
1.443     albertel 14018:             }
                   14019:             $result = $modify_section_result;
                   14020:         } elsif ($secchange == 1) {
1.628     raeburn  14021:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14022:                 $$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  14023:             } else {
                   14024:                 $$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;
                   14025:             }
1.626     raeburn  14026:             if ($expire_role_result eq 'refused') {
                   14027:                 my $newsecurl = '/'.$cid;
                   14028:                 $newsecurl =~ s/\_/\//g;
                   14029:                 if ($sec ne '') {
                   14030:                     $newsecurl.='/'.$sec;
                   14031:                 }
                   14032:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14033:                     if ($sec eq '') {
                   14034:                         $$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;
                   14035:                     } else {
                   14036:                         $$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;
                   14037:                     }
                   14038:                 }
                   14039:             }
1.443     albertel 14040:         }
                   14041:     } else {
1.626     raeburn  14042:         $$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 14043:         $result = "error: incomplete course id\n";
                   14044:     }
                   14045:     return $result;
                   14046: }
                   14047: 
1.1075.2.25  raeburn  14048: sub show_role_extent {
                   14049:     my ($scope,$context,$role) = @_;
                   14050:     $scope =~ s{^/}{};
                   14051:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14052:     push(@courseroles,'co');
                   14053:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14054:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14055:         $scope =~ s{/}{_};
                   14056:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14057:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14058:         my ($audom,$auname) = split(/\//,$scope);
                   14059:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14060:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14061:     } else {
                   14062:         $scope =~ s{/$}{};
                   14063:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14064:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14065:     }
                   14066: }
                   14067: 
1.443     albertel 14068: ############################################################
                   14069: ############################################################
                   14070: 
1.566     albertel 14071: sub check_clone {
1.578     raeburn  14072:     my ($args,$linefeed) = @_;
1.566     albertel 14073:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14074:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14075:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14076:     my $clonemsg;
                   14077:     my $can_clone = 0;
1.944     raeburn  14078:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14079:     if ($lctype ne 'community') {
                   14080:         $lctype = 'course';
                   14081:     }
1.566     albertel 14082:     if ($clonehome eq 'no_host') {
1.944     raeburn  14083:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14084:             $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'});
                   14085:         } else {
                   14086:             $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'});
                   14087:         }     
1.566     albertel 14088:     } else {
                   14089: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14090:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14091:             if ($clonedesc{'type'} ne 'Community') {
                   14092:                  $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'});
                   14093:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14094:             }
                   14095:         }
1.882     raeburn  14096: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14097:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14098: 	    $can_clone = 1;
                   14099: 	} else {
                   14100: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   14101: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   14102: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  14103:             if (grep(/^\*$/,@cloners)) {
                   14104:                 $can_clone = 1;
                   14105:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14106:                 $can_clone = 1;
                   14107:             } else {
1.908     raeburn  14108:                 my $ccrole = 'cc';
1.944     raeburn  14109:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14110:                     $ccrole = 'co';
                   14111:                 }
1.578     raeburn  14112: 	        my %roleshash =
                   14113: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14114: 					 $args->{'ccdomain'},
1.908     raeburn  14115:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  14116: 					 [$args->{'clonedomain'}]);
1.908     raeburn  14117: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  14118:                     $can_clone = 1;
                   14119:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   14120:                     $can_clone = 1;
                   14121:                 } else {
1.944     raeburn  14122:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14123:                         $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'});
                   14124:                     } else {
                   14125:                         $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'});
                   14126:                     }
1.578     raeburn  14127: 	        }
1.566     albertel 14128: 	    }
1.578     raeburn  14129:         }
1.566     albertel 14130:     }
                   14131:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14132: }
                   14133: 
1.444     albertel 14134: sub construct_course {
1.1075.2.59  raeburn  14135:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14136:     my $outcome;
1.541     raeburn  14137:     my $linefeed =  '<br />'."\n";
                   14138:     if ($context eq 'auto') {
                   14139:         $linefeed = "\n";
                   14140:     }
1.566     albertel 14141: 
                   14142: #
                   14143: # Are we cloning?
                   14144: #
                   14145:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14146:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14147: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14148: 	if ($context ne 'auto') {
1.578     raeburn  14149:             if ($clonemsg ne '') {
                   14150: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14151:             }
1.566     albertel 14152: 	}
                   14153: 	$outcome .= $clonemsg.$linefeed;
                   14154: 
                   14155:         if (!$can_clone) {
                   14156: 	    return (0,$outcome);
                   14157: 	}
                   14158:     }
                   14159: 
1.444     albertel 14160: #
                   14161: # Open course
                   14162: #
                   14163:     my $crstype = lc($args->{'crstype'});
                   14164:     my %cenv=();
                   14165:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14166:                                              $args->{'cdescr'},
                   14167:                                              $args->{'curl'},
                   14168:                                              $args->{'course_home'},
                   14169:                                              $args->{'nonstandard'},
                   14170:                                              $args->{'crscode'},
                   14171:                                              $args->{'ccuname'}.':'.
                   14172:                                              $args->{'ccdomain'},
1.882     raeburn  14173:                                              $args->{'crstype'},
1.885     raeburn  14174:                                              $cnum,$context,$category);
1.444     albertel 14175: 
                   14176:     # Note: The testing routines depend on this being output; see 
                   14177:     # Utils::Course. This needs to at least be output as a comment
                   14178:     # if anyone ever decides to not show this, and Utils::Course::new
                   14179:     # will need to be suitably modified.
1.541     raeburn  14180:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14181:     if ($$courseid =~ /^error:/) {
                   14182:         return (0,$outcome);
                   14183:     }
                   14184: 
1.444     albertel 14185: #
                   14186: # Check if created correctly
                   14187: #
1.479     albertel 14188:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14189:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14190:     if ($crsuhome eq 'no_host') {
                   14191:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14192:         return (0,$outcome);
                   14193:     }
1.541     raeburn  14194:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14195: 
1.444     albertel 14196: #
1.566     albertel 14197: # Do the cloning
                   14198: #   
                   14199:     if ($can_clone && $cloneid) {
                   14200: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14201: 	if ($context ne 'auto') {
                   14202: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14203: 	}
                   14204: 	$outcome .= $clonemsg.$linefeed;
                   14205: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14206: # Copy all files
1.637     www      14207: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14208: # Restore URL
1.566     albertel 14209: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14210: # Restore title
1.566     albertel 14211: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14212: # Restore creation date, creator and creation context.
                   14213:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14214:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14215:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14216: # Mark as cloned
1.566     albertel 14217: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14218: # Need to clone grading mode
                   14219:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14220:         $cenv{'grading'}=$newenv{'grading'};
                   14221: # Do not clone these environment entries
                   14222:         &Apache::lonnet::del('environment',
                   14223:                   ['default_enrollment_start_date',
                   14224:                    'default_enrollment_end_date',
                   14225:                    'question.email',
                   14226:                    'policy.email',
                   14227:                    'comment.email',
                   14228:                    'pch.users.denied',
1.725     raeburn  14229:                    'plc.users.denied',
                   14230:                    'hidefromcat',
1.1075.2.36  raeburn  14231:                    'checkforpriv',
1.1075.2.59  raeburn  14232:                    'categories',
                   14233:                    'internal.uniquecode'],
1.638     www      14234:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14235:         if ($args->{'textbook'}) {
                   14236:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14237:         }
1.444     albertel 14238:     }
1.566     albertel 14239: 
1.444     albertel 14240: #
                   14241: # Set environment (will override cloned, if existing)
                   14242: #
                   14243:     my @sections = ();
                   14244:     my @xlists = ();
                   14245:     if ($args->{'crstype'}) {
                   14246:         $cenv{'type'}=$args->{'crstype'};
                   14247:     }
                   14248:     if ($args->{'crsid'}) {
                   14249:         $cenv{'courseid'}=$args->{'crsid'};
                   14250:     }
                   14251:     if ($args->{'crscode'}) {
                   14252:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14253:     }
                   14254:     if ($args->{'crsquota'} ne '') {
                   14255:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14256:     } else {
                   14257:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14258:     }
                   14259:     if ($args->{'ccuname'}) {
                   14260:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14261:                                         ':'.$args->{'ccdomain'};
                   14262:     } else {
                   14263:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14264:     }
1.1075.2.31  raeburn  14265:     if ($args->{'defaultcredits'}) {
                   14266:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14267:     }
1.444     albertel 14268:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14269:     if ($args->{'crssections'}) {
                   14270:         $cenv{'internal.sectionnums'} = '';
                   14271:         if ($args->{'crssections'} =~ m/,/) {
                   14272:             @sections = split/,/,$args->{'crssections'};
                   14273:         } else {
                   14274:             $sections[0] = $args->{'crssections'};
                   14275:         }
                   14276:         if (@sections > 0) {
                   14277:             foreach my $item (@sections) {
                   14278:                 my ($sec,$gp) = split/:/,$item;
                   14279:                 my $class = $args->{'crscode'}.$sec;
                   14280:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14281:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14282:                 unless ($addcheck eq 'ok') {
                   14283:                     push @badclasses, $class;
                   14284:                 }
                   14285:             }
                   14286:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14287:         }
                   14288:     }
                   14289: # do not hide course coordinator from staff listing, 
                   14290: # even if privileged
                   14291:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14292: # add course coordinator's domain to domains to check for privileged users
                   14293: # if different to course domain
                   14294:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14295:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14296:     }
1.444     albertel 14297: # add crosslistings
                   14298:     if ($args->{'crsxlist'}) {
                   14299:         $cenv{'internal.crosslistings'}='';
                   14300:         if ($args->{'crsxlist'} =~ m/,/) {
                   14301:             @xlists = split/,/,$args->{'crsxlist'};
                   14302:         } else {
                   14303:             $xlists[0] = $args->{'crsxlist'};
                   14304:         }
                   14305:         if (@xlists > 0) {
                   14306:             foreach my $item (@xlists) {
                   14307:                 my ($xl,$gp) = split/:/,$item;
                   14308:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14309:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14310:                 unless ($addcheck eq 'ok') {
                   14311:                     push @badclasses, $xl;
                   14312:                 }
                   14313:             }
                   14314:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14315:         }
                   14316:     }
                   14317:     if ($args->{'autoadds'}) {
                   14318:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14319:     }
                   14320:     if ($args->{'autodrops'}) {
                   14321:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14322:     }
                   14323: # check for notification of enrollment changes
                   14324:     my @notified = ();
                   14325:     if ($args->{'notify_owner'}) {
                   14326:         if ($args->{'ccuname'} ne '') {
                   14327:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14328:         }
                   14329:     }
                   14330:     if ($args->{'notify_dc'}) {
                   14331:         if ($uname ne '') { 
1.630     raeburn  14332:             push(@notified,$uname.':'.$udom);
1.444     albertel 14333:         }
                   14334:     }
                   14335:     if (@notified > 0) {
                   14336:         my $notifylist;
                   14337:         if (@notified > 1) {
                   14338:             $notifylist = join(',',@notified);
                   14339:         } else {
                   14340:             $notifylist = $notified[0];
                   14341:         }
                   14342:         $cenv{'internal.notifylist'} = $notifylist;
                   14343:     }
                   14344:     if (@badclasses > 0) {
                   14345:         my %lt=&Apache::lonlocal::texthash(
                   14346:                 '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',
                   14347:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14348:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14349:         );
1.541     raeburn  14350:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14351:                            ' ('.$lt{'adby'}.')';
                   14352:         if ($context eq 'auto') {
                   14353:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14354:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14355:             foreach my $item (@badclasses) {
                   14356:                 if ($context eq 'auto') {
                   14357:                     $outcome .= " - $item\n";
                   14358:                 } else {
                   14359:                     $outcome .= "<li>$item</li>\n";
                   14360:                 }
                   14361:             }
                   14362:             if ($context eq 'auto') {
                   14363:                 $outcome .= $linefeed;
                   14364:             } else {
1.566     albertel 14365:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14366:             }
                   14367:         } 
1.444     albertel 14368:     }
                   14369:     if ($args->{'no_end_date'}) {
                   14370:         $args->{'endaccess'} = 0;
                   14371:     }
                   14372:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14373:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14374:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14375:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14376:     if ($args->{'showphotos'}) {
                   14377:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14378:     }
                   14379:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14380:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14381:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14382:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14383:             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'); 
                   14384:             if ($context eq 'auto') {
                   14385:                 $outcome .= $krb_msg;
                   14386:             } else {
1.566     albertel 14387:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14388:             }
                   14389:             $outcome .= $linefeed;
1.444     albertel 14390:         }
                   14391:     }
                   14392:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14393:        if ($args->{'setpolicy'}) {
                   14394:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14395:        }
                   14396:        if ($args->{'setcontent'}) {
                   14397:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14398:        }
                   14399:     }
                   14400:     if ($args->{'reshome'}) {
                   14401: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14402: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14403:     }
                   14404: #
                   14405: # course has keyed access
                   14406: #
                   14407:     if ($args->{'setkeys'}) {
                   14408:        $cenv{'keyaccess'}='yes';
                   14409:     }
                   14410: # if specified, key authority is not course, but user
                   14411: # only active if keyaccess is yes
                   14412:     if ($args->{'keyauth'}) {
1.487     albertel 14413: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14414: 	$user = &LONCAPA::clean_username($user);
                   14415: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14416: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14417: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14418: 	}
                   14419:     }
                   14420: 
1.1075.2.59  raeburn  14421: #
                   14422: #  generate and store uniquecode (available to course requester), if course should have one.
                   14423: #
                   14424:     if ($args->{'uniquecode'}) {
                   14425:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14426:         if ($code) {
                   14427:             $cenv{'internal.uniquecode'} = $code;
                   14428:             my %crsinfo =
                   14429:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14430:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14431:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14432:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14433:             }
                   14434:             if (ref($coderef)) {
                   14435:                 $$coderef = $code;
                   14436:             }
                   14437:         }
                   14438:     }
                   14439: 
1.444     albertel 14440:     if ($args->{'disresdis'}) {
                   14441:         $cenv{'pch.roles.denied'}='st';
                   14442:     }
                   14443:     if ($args->{'disablechat'}) {
                   14444:         $cenv{'plc.roles.denied'}='st';
                   14445:     }
                   14446: 
                   14447:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14448:     # course
                   14449:     $cenv{'course.helper.not.run'} = 1;
                   14450:     #
                   14451:     # Use new Randomseed
                   14452:     #
                   14453:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14454:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14455:     #
                   14456:     # The encryption code and receipt prefix for this course
                   14457:     #
                   14458:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14459:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14460:     #
                   14461:     # By default, use standard grading
                   14462:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14463: 
1.541     raeburn  14464:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14465:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14466: #
                   14467: # Open all assignments
                   14468: #
                   14469:     if ($args->{'openall'}) {
                   14470:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14471:        my %storecontent = ($storeunder         => time,
                   14472:                            $storeunder.'.type' => 'date_start');
                   14473:        
                   14474:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14475:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14476:    }
                   14477: #
                   14478: # Set first page
                   14479: #
                   14480:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14481: 	    || ($cloneid)) {
1.445     albertel 14482: 	use LONCAPA::map;
1.444     albertel 14483: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14484: 
                   14485: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14486:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14487: 
1.444     albertel 14488:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14489:         my $title; my $url;
                   14490:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14491: 	    $title=&mt('Syllabus');
1.444     albertel 14492:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14493:         } else {
1.963     raeburn  14494:             $title=&mt('Table of Contents');
1.444     albertel 14495:             $url='/adm/navmaps';
                   14496:         }
1.445     albertel 14497: 
                   14498:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14499: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14500: 
                   14501: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14502:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14503:     }
1.566     albertel 14504: 
                   14505:     return (1,$outcome);
1.444     albertel 14506: }
                   14507: 
1.1075.2.59  raeburn  14508: sub make_unique_code {
                   14509:     my ($cdom,$cnum) = @_;
                   14510:     # get lock on uniquecodes db
                   14511:     my $lockhash = {
                   14512:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14513:                                                   ':'.$env{'user.domain'},
                   14514:                    };
                   14515:     my $tries = 0;
                   14516:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14517:     my ($code,$error);
                   14518: 
                   14519:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14520:         $tries ++;
                   14521:         sleep 1;
                   14522:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14523:     }
                   14524:     if ($gotlock eq 'ok') {
                   14525:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14526:         my $gotcode;
                   14527:         my $attempts = 0;
                   14528:         while ((!$gotcode) && ($attempts < 100)) {
                   14529:             $code = &generate_code();
                   14530:             if (!exists($currcodes{$code})) {
                   14531:                 $gotcode = 1;
                   14532:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14533:                     $error = 'nostore';
                   14534:                 }
                   14535:             }
                   14536:             $attempts ++;
                   14537:         }
                   14538:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14539:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14540:     } else {
                   14541:         $error = 'nolock';
                   14542:     }
                   14543:     return ($code,$error);
                   14544: }
                   14545: 
                   14546: sub generate_code {
                   14547:     my $code;
                   14548:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14549:     for (my $i=0; $i<6; $i++) {
                   14550:         my $lettnum = int (rand 2);
                   14551:         my $item = '';
                   14552:         if ($lettnum) {
                   14553:             $item = $letts[int( rand(18) )];
                   14554:         } else {
                   14555:             $item = 1+int( rand(8) );
                   14556:         }
                   14557:         $code .= $item;
                   14558:     }
                   14559:     return $code;
                   14560: }
                   14561: 
1.444     albertel 14562: ############################################################
                   14563: ############################################################
                   14564: 
1.953     droeschl 14565: #SD
                   14566: # only Community and Course, or anything else?
1.378     raeburn  14567: sub course_type {
                   14568:     my ($cid) = @_;
                   14569:     if (!defined($cid)) {
                   14570:         $cid = $env{'request.course.id'};
                   14571:     }
1.404     albertel 14572:     if (defined($env{'course.'.$cid.'.type'})) {
                   14573:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14574:     } else {
                   14575:         return 'Course';
1.377     raeburn  14576:     }
                   14577: }
1.156     albertel 14578: 
1.406     raeburn  14579: sub group_term {
                   14580:     my $crstype = &course_type();
                   14581:     my %names = (
                   14582:                   'Course' => 'group',
1.865     raeburn  14583:                   'Community' => 'group',
1.406     raeburn  14584:                 );
                   14585:     return $names{$crstype};
                   14586: }
                   14587: 
1.902     raeburn  14588: sub course_types {
1.1075.2.59  raeburn  14589:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14590:     my %typename = (
                   14591:                          official   => 'Official course',
                   14592:                          unofficial => 'Unofficial course',
                   14593:                          community  => 'Community',
1.1075.2.59  raeburn  14594:                          textbook   => 'Textbook course',
1.902     raeburn  14595:                    );
                   14596:     return (\@types,\%typename);
                   14597: }
                   14598: 
1.156     albertel 14599: sub icon {
                   14600:     my ($file)=@_;
1.505     albertel 14601:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14602:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14603:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14604:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14605: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14606: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14607: 	            $curfext.".gif") {
                   14608: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14609: 		$curfext.".gif";
                   14610: 	}
                   14611:     }
1.249     albertel 14612:     return &lonhttpdurl($iconname);
1.154     albertel 14613: } 
1.84      albertel 14614: 
1.575     albertel 14615: sub lonhttpdurl {
1.692     www      14616: #
                   14617: # Had been used for "small fry" static images on separate port 8080.
                   14618: # Modify here if lightweight http functionality desired again.
                   14619: # Currently eliminated due to increasing firewall issues.
                   14620: #
1.575     albertel 14621:     my ($url)=@_;
1.692     www      14622:     return $url;
1.215     albertel 14623: }
                   14624: 
1.213     albertel 14625: sub connection_aborted {
                   14626:     my ($r)=@_;
                   14627:     $r->print(" ");$r->rflush();
                   14628:     my $c = $r->connection;
                   14629:     return $c->aborted();
                   14630: }
                   14631: 
1.221     foxr     14632: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14633: #    strings as 'strings'.
                   14634: sub escape_single {
1.221     foxr     14635:     my ($input) = @_;
1.223     albertel 14636:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14637:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14638:     return $input;
                   14639: }
1.223     albertel 14640: 
1.222     foxr     14641: #  Same as escape_single, but escape's "'s  This 
                   14642: #  can be used for  "strings"
                   14643: sub escape_double {
                   14644:     my ($input) = @_;
                   14645:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14646:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14647:     return $input;
                   14648: }
1.223     albertel 14649:  
1.222     foxr     14650: #   Escapes the last element of a full URL.
                   14651: sub escape_url {
                   14652:     my ($url)   = @_;
1.238     raeburn  14653:     my @urlslices = split(/\//, $url,-1);
1.369     www      14654:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  14655:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14656: }
1.462     albertel 14657: 
1.820     raeburn  14658: sub compare_arrays {
                   14659:     my ($arrayref1,$arrayref2) = @_;
                   14660:     my (@difference,%count);
                   14661:     @difference = ();
                   14662:     %count = ();
                   14663:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14664:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14665:         foreach my $element (keys(%count)) {
                   14666:             if ($count{$element} == 1) {
                   14667:                 push(@difference,$element);
                   14668:             }
                   14669:         }
                   14670:     }
                   14671:     return @difference;
                   14672: }
                   14673: 
1.817     bisitz   14674: # -------------------------------------------------------- Initialize user login
1.462     albertel 14675: sub init_user_environment {
1.463     albertel 14676:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14677:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14678: 
                   14679:     my $public=($username eq 'public' && $domain eq 'public');
                   14680: 
                   14681: # See if old ID present, if so, remove
                   14682: 
1.1062    raeburn  14683:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14684:     my $now=time;
                   14685: 
                   14686:     if ($public) {
                   14687: 	my $max_public=100;
                   14688: 	my $oldest;
                   14689: 	my $oldest_time=0;
                   14690: 	for(my $next=1;$next<=$max_public;$next++) {
                   14691: 	    if (-e $lonids."/publicuser_$next.id") {
                   14692: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14693: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14694: 		    $oldest_time=$mtime;
                   14695: 		    $oldest=$next;
                   14696: 		}
                   14697: 	    } else {
                   14698: 		$cookie="publicuser_$next";
                   14699: 		last;
                   14700: 	    }
                   14701: 	}
                   14702: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14703:     } else {
1.463     albertel 14704: 	# if this isn't a robot, kill any existing non-robot sessions
                   14705: 	if (!$args->{'robot'}) {
                   14706: 	    opendir(DIR,$lonids);
                   14707: 	    while ($filename=readdir(DIR)) {
                   14708: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14709: 		    unlink($lonids.'/'.$filename);
                   14710: 		}
1.462     albertel 14711: 	    }
1.463     albertel 14712: 	    closedir(DIR);
1.1075.2.84  raeburn  14713: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   14714:             my $namespace = 'nohist_courseeditor';
                   14715:             my $lockingkey = 'paste'."\0".'locked_num';
                   14716:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   14717:                                                 $domain,$username);
                   14718:             if (exists($lockhash{$lockingkey})) {
                   14719:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   14720:                 unless ($delresult eq 'ok') {
                   14721:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   14722:                 }
                   14723:             }
1.462     albertel 14724: 	}
                   14725: # Give them a new cookie
1.463     albertel 14726: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14727: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14728: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14729:     
                   14730: # Initialize roles
                   14731: 
1.1062    raeburn  14732: 	($userroles,$firstaccenv,$timerintenv) = 
                   14733:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14734:     }
                   14735: # ------------------------------------ Check browser type and MathML capability
                   14736: 
1.1075.2.77  raeburn  14737:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   14738:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 14739: 
                   14740: # ------------------------------------------------------------- Get environment
                   14741: 
                   14742:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14743:     my ($tmp) = keys(%userenv);
                   14744:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14745:     } else {
                   14746: 	undef(%userenv);
                   14747:     }
                   14748:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14749: 	$form->{'interface'}=$userenv{'interface'};
                   14750:     }
                   14751:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14752: 
                   14753: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14754:     foreach my $option ('interface','localpath','localres') {
                   14755:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14756:     }
                   14757: # --------------------------------------------------------- Write first profile
                   14758: 
                   14759:     {
                   14760: 	my %initial_env = 
                   14761: 	    ("user.name"          => $username,
                   14762: 	     "user.domain"        => $domain,
                   14763: 	     "user.home"          => $authhost,
                   14764: 	     "browser.type"       => $clientbrowser,
                   14765: 	     "browser.version"    => $clientversion,
                   14766: 	     "browser.mathml"     => $clientmathml,
                   14767: 	     "browser.unicode"    => $clientunicode,
                   14768: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  14769:              "browser.mobile"     => $clientmobile,
                   14770:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  14771:              "browser.osversion"  => $clientosversion,
1.462     albertel 14772: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14773: 	     "request.course.fn"  => '',
                   14774: 	     "request.course.uri" => '',
                   14775: 	     "request.course.sec" => '',
                   14776: 	     "request.role"       => 'cm',
                   14777: 	     "request.role.adv"   => $env{'user.adv'},
                   14778: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14779: 
                   14780:         if ($form->{'localpath'}) {
                   14781: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14782: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14783:         }
                   14784: 	
                   14785: 	if ($form->{'interface'}) {
                   14786: 	    $form->{'interface'}=~s/\W//gs;
                   14787: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14788: 	    $env{'browser.interface'}=$form->{'interface'};
                   14789: 	}
                   14790: 
1.1075.2.54  raeburn  14791:         if ($form->{'iptoken'}) {
                   14792:             my $lonhost = $r->dir_config('lonHostID');
                   14793:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14794:             $env{'user.noloadbalance'} = $lonhost;
                   14795:         }
                   14796: 
1.981     raeburn  14797:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14798:         my %domdef;
                   14799:         unless ($domain eq 'public') {
                   14800:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14801:         }
1.980     raeburn  14802: 
1.1075.2.7  raeburn  14803:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14804:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14805:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14806:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14807:         }
                   14808: 
1.1075.2.59  raeburn  14809:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14810:             $userenv{'canrequest.'.$crstype} =
                   14811:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14812:                                                   'reload','requestcourses',
                   14813:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14814:         }
                   14815: 
1.1075.2.14  raeburn  14816:         $userenv{'canrequest.author'} =
                   14817:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14818:                                         'reload','requestauthor',
                   14819:                                         \%userenv,\%domdef,\%is_adv);
                   14820:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14821:                                              $domain,$username);
                   14822:         my $reqstatus = $reqauthor{'author_status'};
                   14823:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   14824:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14825:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14826:                                                   $reqauthor{'author'}{'timestamp'};
                   14827:             }
                   14828:         }
                   14829: 
1.462     albertel 14830: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14831: 
1.462     albertel 14832: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14833: 		 &GDBM_WRCREAT(),0640)) {
                   14834: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14835: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14836: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14837:             if (ref($firstaccenv) eq 'HASH') {
                   14838:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14839:             }
                   14840:             if (ref($timerintenv) eq 'HASH') {
                   14841:                 &_add_to_env(\%disk_env,$timerintenv);
                   14842:             }
1.463     albertel 14843: 	    if (ref($args->{'extra_env'})) {
                   14844: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14845: 	    }
1.462     albertel 14846: 	    untie(%disk_env);
                   14847: 	} else {
1.705     tempelho 14848: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14849: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14850: 	    return 'error: '.$!;
                   14851: 	}
                   14852:     }
                   14853:     $env{'request.role'}='cm';
                   14854:     $env{'request.role.adv'}=$env{'user.adv'};
                   14855:     $env{'browser.type'}=$clientbrowser;
                   14856: 
                   14857:     return $cookie;
                   14858: 
                   14859: }
                   14860: 
                   14861: sub _add_to_env {
                   14862:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14863:     if (ref($env_data) eq 'HASH') {
                   14864:         while (my ($key,$value) = each(%$env_data)) {
                   14865: 	    $idf->{$prefix.$key} = $value;
                   14866: 	    $env{$prefix.$key}   = $value;
                   14867:         }
1.462     albertel 14868:     }
                   14869: }
                   14870: 
1.685     tempelho 14871: # --- Get the symbolic name of a problem and the url
                   14872: sub get_symb {
                   14873:     my ($request,$silent) = @_;
1.726     raeburn  14874:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14875:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14876:     if ($symb eq '') {
                   14877:         if (!$silent) {
1.1071    raeburn  14878:             if (ref($request)) { 
                   14879:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14880:             }
1.685     tempelho 14881:             return ();
                   14882:         }
                   14883:     }
                   14884:     &Apache::lonenc::check_decrypt(\$symb);
                   14885:     return ($symb);
                   14886: }
                   14887: 
                   14888: # --------------------------------------------------------------Get annotation
                   14889: 
                   14890: sub get_annotation {
                   14891:     my ($symb,$enc) = @_;
                   14892: 
                   14893:     my $key = $symb;
                   14894:     if (!$enc) {
                   14895:         $key =
                   14896:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14897:     }
                   14898:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14899:     return $annotation{$key};
                   14900: }
                   14901: 
                   14902: sub clean_symb {
1.731     raeburn  14903:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14904: 
                   14905:     &Apache::lonenc::check_decrypt(\$symb);
                   14906:     my $enc = $env{'request.enc'};
1.731     raeburn  14907:     if ($delete_enc) {
1.730     raeburn  14908:         delete($env{'request.enc'});
                   14909:     }
1.685     tempelho 14910: 
                   14911:     return ($symb,$enc);
                   14912: }
1.462     albertel 14913: 
1.1075.2.69  raeburn  14914: ############################################################
                   14915: ############################################################
                   14916: 
                   14917: =pod
                   14918: 
                   14919: =head1 Routines for building display used to search for courses
                   14920: 
                   14921: 
                   14922: =over 4
                   14923: 
                   14924: =item * &build_filters()
                   14925: 
                   14926: Create markup for a table used to set filters to use when selecting
                   14927: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   14928: and quotacheck.pl
                   14929: 
                   14930: 
                   14931: Inputs:
                   14932: 
                   14933: filterlist - anonymous array of fields to include as potential filters
                   14934: 
                   14935: crstype - course type
                   14936: 
                   14937: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   14938:               to pop-open a course selector (will contain "extra element").
                   14939: 
                   14940: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   14941: 
                   14942: filter - anonymous hash of criteria and their values
                   14943: 
                   14944: action - form action
                   14945: 
                   14946: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   14947: 
                   14948: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   14949: 
                   14950: cloneruname - username of owner of new course who wants to clone
                   14951: 
                   14952: clonerudom - domain of owner of new course who wants to clone
                   14953: 
                   14954: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   14955: 
                   14956: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   14957: 
                   14958: codedom - domain
                   14959: 
                   14960: formname - value of form element named "form".
                   14961: 
                   14962: fixeddom - domain, if fixed.
                   14963: 
                   14964: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   14965: 
                   14966: cnameelement - name of form element in form on opener page which will receive title of selected course
                   14967: 
                   14968: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   14969: 
                   14970: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   14971: 
                   14972: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   14973: 
                   14974: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   14975: 
                   14976: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   14977: 
                   14978: 
                   14979: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   14980: 
                   14981: 
                   14982: Side Effects: None
                   14983: 
                   14984: =cut
                   14985: 
                   14986: # ---------------------------------------------- search for courses based on last activity etc.
                   14987: 
                   14988: sub build_filters {
                   14989:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   14990:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   14991:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   14992:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   14993:         $clonetext,$clonewarning) = @_;
                   14994:     my ($list,$jscript);
                   14995:     my $onchange = 'javascript:updateFilters(this)';
                   14996:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   14997:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   14998:         $typeselectform,$instcodetitle);
                   14999:     if ($formname eq '') {
                   15000:         $formname = $caller;
                   15001:     }
                   15002:     foreach my $item (@{$filterlist}) {
                   15003:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15004:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15005:             if ($item eq 'domainfilter') {
                   15006:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15007:             } elsif ($item eq 'coursefilter') {
                   15008:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15009:             } elsif ($item eq 'ownerfilter') {
                   15010:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15011:             } elsif ($item eq 'ownerdomfilter') {
                   15012:                 $filter->{'ownerdomfilter'} =
                   15013:                     &LONCAPA::clean_domain($filter->{$item});
                   15014:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15015:                                                        'ownerdomfilter',1);
                   15016:             } elsif ($item eq 'personfilter') {
                   15017:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15018:             } elsif ($item eq 'persondomfilter') {
                   15019:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15020:                                                         'persondomfilter',1);
                   15021:             } else {
                   15022:                 $filter->{$item} =~ s/\W//g;
                   15023:             }
                   15024:             if (!$filter->{$item}) {
                   15025:                 $filter->{$item} = '';
                   15026:             }
                   15027:         }
                   15028:         if ($item eq 'domainfilter') {
                   15029:             my $allow_blank = 1;
                   15030:             if ($formname eq 'portform') {
                   15031:                 $allow_blank=0;
                   15032:             } elsif ($formname eq 'studentform') {
                   15033:                 $allow_blank=0;
                   15034:             }
                   15035:             if ($fixeddom) {
                   15036:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15037:                                     ' value="'.$codedom.'" />'.
                   15038:                                     &Apache::lonnet::domain($codedom,'description');
                   15039:             } else {
                   15040:                 $domainselectform = &select_dom_form($filter->{$item},
                   15041:                                                      'domainfilter',
                   15042:                                                       $allow_blank,'',$onchange);
                   15043:             }
                   15044:         } else {
                   15045:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15046:         }
                   15047:     }
                   15048: 
                   15049:     # last course activity filter and selection
                   15050:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15051: 
                   15052:     # course created filter and selection
                   15053:     if (exists($filter->{'createdfilter'})) {
                   15054:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15055:     }
                   15056: 
                   15057:     my %lt = &Apache::lonlocal::texthash(
                   15058:                 'cac' => "$crstype Activity",
                   15059:                 'ccr' => "$crstype Created",
                   15060:                 'cde' => "$crstype Title",
                   15061:                 'cdo' => "$crstype Domain",
                   15062:                 'ins' => 'Institutional Code',
                   15063:                 'inc' => 'Institutional Categorization',
                   15064:                 'cow' => "$crstype Owner/Co-owner",
                   15065:                 'cop' => "$crstype Personnel Includes",
                   15066:                 'cog' => 'Type',
                   15067:              );
                   15068: 
                   15069:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15070:         my $typeval = 'Course';
                   15071:         if ($crstype eq 'Community') {
                   15072:             $typeval = 'Community';
                   15073:         }
                   15074:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15075:     } else {
                   15076:         $typeselectform =  '<select name="type" size="1"';
                   15077:         if ($onchange) {
                   15078:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15079:         }
                   15080:         $typeselectform .= '>'."\n";
                   15081:         foreach my $posstype ('Course','Community') {
                   15082:             $typeselectform.='<option value="'.$posstype.'"'.
                   15083:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15084:         }
                   15085:         $typeselectform.="</select>";
                   15086:     }
                   15087: 
                   15088:     my ($cloneableonlyform,$cloneabletitle);
                   15089:     if (exists($filter->{'cloneableonly'})) {
                   15090:         my $cloneableon = '';
                   15091:         my $cloneableoff = ' checked="checked"';
                   15092:         if ($filter->{'cloneableonly'}) {
                   15093:             $cloneableon = $cloneableoff;
                   15094:             $cloneableoff = '';
                   15095:         }
                   15096:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
                   15097:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15098:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15099:         } else {
                   15100:             $cloneabletitle = &mt('Cloneable by you');
                   15101:         }
                   15102:     }
                   15103:     my $officialjs;
                   15104:     if ($crstype eq 'Course') {
                   15105:         if (exists($filter->{'instcodefilter'})) {
                   15106: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15107: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15108:             if ($codedom) {
                   15109:                 $officialjs = 1;
                   15110:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15111:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15112:                                                                   $officialjs,$codetitlesref);
                   15113:                 if ($jscript) {
                   15114:                     $jscript = '<script type="text/javascript">'."\n".
                   15115:                                '// <![CDATA['."\n".
                   15116:                                $jscript."\n".
                   15117:                                '// ]]>'."\n".
                   15118:                                '</script>'."\n";
                   15119:                 }
                   15120:             }
                   15121:             if ($instcodeform eq '') {
                   15122:                 $instcodeform =
                   15123:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15124:                     $list->{'instcodefilter'}.'" />';
                   15125:                 $instcodetitle = $lt{'ins'};
                   15126:             } else {
                   15127:                 $instcodetitle = $lt{'inc'};
                   15128:             }
                   15129:             if ($fixeddom) {
                   15130:                 $instcodetitle .= '<br />('.$codedom.')';
                   15131:             }
                   15132:         }
                   15133:     }
                   15134:     my $output = qq|
                   15135: <form method="post" name="filterpicker" action="$action">
                   15136: <input type="hidden" name="form" value="$formname" />
                   15137: |;
                   15138:     if ($formname eq 'modifycourse') {
                   15139:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15140:                    '<input type="hidden" name="prevphase" value="'.
                   15141:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15142:     } elsif ($formname eq 'quotacheck') {
                   15143:         $output .= qq|
                   15144: <input type="hidden" name="sortby" value="" />
                   15145: <input type="hidden" name="sortorder" value="" />
                   15146: |;
                   15147:     } else {
1.1075.2.69  raeburn  15148:         my $name_input;
                   15149:         if ($cnameelement ne '') {
                   15150:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15151:                           $cnameelement.'" />';
                   15152:         }
                   15153:         $output .= qq|
                   15154: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15155: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15156: $name_input
                   15157: $roleelement
                   15158: $multelement
                   15159: $typeelement
                   15160: |;
                   15161:         if ($formname eq 'portform') {
                   15162:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15163:         }
                   15164:     }
                   15165:     if ($fixeddom) {
                   15166:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15167:     }
                   15168:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15169:     if ($sincefilterform) {
                   15170:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15171:                   .$sincefilterform
                   15172:                   .&Apache::lonhtmlcommon::row_closure();
                   15173:     }
                   15174:     if ($createdfilterform) {
                   15175:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15176:                   .$createdfilterform
                   15177:                   .&Apache::lonhtmlcommon::row_closure();
                   15178:     }
                   15179:     if ($domainselectform) {
                   15180:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15181:                   .$domainselectform
                   15182:                   .&Apache::lonhtmlcommon::row_closure();
                   15183:     }
                   15184:     if ($typeselectform) {
                   15185:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15186:             $output .= $typeselectform;
                   15187:         } else {
                   15188:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15189:                       .$typeselectform
                   15190:                       .&Apache::lonhtmlcommon::row_closure();
                   15191:         }
                   15192:     }
                   15193:     if ($instcodeform) {
                   15194:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15195:                   .$instcodeform
                   15196:                   .&Apache::lonhtmlcommon::row_closure();
                   15197:     }
                   15198:     if (exists($filter->{'ownerfilter'})) {
                   15199:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15200:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15201:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15202:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15203:                    $ownerdomselectform.'</td></tr></table>'.
                   15204:                    &Apache::lonhtmlcommon::row_closure();
                   15205:     }
                   15206:     if (exists($filter->{'personfilter'})) {
                   15207:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15208:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15209:                    '<input type="text" name="personfilter" size="20" value="'.
                   15210:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15211:                    $persondomselectform.'</td></tr></table>'.
                   15212:                    &Apache::lonhtmlcommon::row_closure();
                   15213:     }
                   15214:     if (exists($filter->{'coursefilter'})) {
                   15215:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15216:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15217:                   .$list->{'coursefilter'}.'" />'
                   15218:                   .&Apache::lonhtmlcommon::row_closure();
                   15219:     }
                   15220:     if ($cloneableonlyform) {
                   15221:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15222:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15223:     }
                   15224:     if (exists($filter->{'descriptfilter'})) {
                   15225:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15226:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15227:                   .$list->{'descriptfilter'}.'" />'
                   15228:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15229:     }
                   15230:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15231:                '<input type="hidden" name="updater" value="" />'."\n".
                   15232:                '<input type="submit" name="gosearch" value="'.
                   15233:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15234:     return $jscript.$clonewarning.$output;
                   15235: }
                   15236: 
                   15237: =pod
                   15238: 
                   15239: =item * &timebased_select_form()
                   15240: 
                   15241: Create markup for a dropdown list used to select a time-based
                   15242: filter e.g., Course Activity, Course Created, when searching for courses
                   15243: or communities
                   15244: 
                   15245: Inputs:
                   15246: 
                   15247: item - name of form element (sincefilter or createdfilter)
                   15248: 
                   15249: filter - anonymous hash of criteria and their values
                   15250: 
                   15251: Returns: HTML for a select box contained a blank, then six time selections,
                   15252:          with value set in incoming form variables currently selected.
                   15253: 
                   15254: Side Effects: None
                   15255: 
                   15256: =cut
                   15257: 
                   15258: sub timebased_select_form {
                   15259:     my ($item,$filter) = @_;
                   15260:     if (ref($filter) eq 'HASH') {
                   15261:         $filter->{$item} =~ s/[^\d-]//g;
                   15262:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15263:         return &select_form(
                   15264:                             $filter->{$item},
                   15265:                             $item,
                   15266:                             {      '-1' => '',
                   15267:                                 '86400' => &mt('today'),
                   15268:                                '604800' => &mt('last week'),
                   15269:                               '2592000' => &mt('last month'),
                   15270:                               '7776000' => &mt('last three months'),
                   15271:                              '15552000' => &mt('last six months'),
                   15272:                              '31104000' => &mt('last year'),
                   15273:                     'select_form_order' =>
                   15274:                            ['-1','86400','604800','2592000','7776000',
                   15275:                             '15552000','31104000']});
                   15276:     }
                   15277: }
                   15278: 
                   15279: =pod
                   15280: 
                   15281: =item * &js_changer()
                   15282: 
                   15283: Create script tag containing Javascript used to submit course search form
                   15284: when course type or domain is changed, and also to hide 'Searching ...' on
                   15285: page load completion for page showing search result.
                   15286: 
                   15287: Inputs: None
                   15288: 
                   15289: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15290: 
                   15291: Side Effects: None
                   15292: 
                   15293: =cut
                   15294: 
                   15295: sub js_changer {
                   15296:     return <<ENDJS;
                   15297: <script type="text/javascript">
                   15298: // <![CDATA[
                   15299: function updateFilters(caller) {
                   15300:     if (typeof(caller) != "undefined") {
                   15301:         document.filterpicker.updater.value = caller.name;
                   15302:     }
                   15303:     document.filterpicker.submit();
                   15304: }
                   15305: 
                   15306: function hideSearching() {
                   15307:     if (document.getElementById('searching')) {
                   15308:         document.getElementById('searching').style.display = 'none';
                   15309:     }
                   15310:     return;
                   15311: }
                   15312: 
                   15313: // ]]>
                   15314: </script>
                   15315: 
                   15316: ENDJS
                   15317: }
                   15318: 
                   15319: =pod
                   15320: 
                   15321: =item * &search_courses()
                   15322: 
                   15323: Process selected filters form course search form and pass to lonnet::courseiddump
                   15324: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15325: 
                   15326: Inputs:
                   15327: 
                   15328: dom - domain being searched
                   15329: 
                   15330: type - course type ('Course' or 'Community' or '.' if any).
                   15331: 
                   15332: filter - anonymous hash of criteria and their values
                   15333: 
                   15334: numtitles - for institutional codes - number of categories
                   15335: 
                   15336: cloneruname - optional username of new course owner
                   15337: 
                   15338: clonerudom - optional domain of new course owner
                   15339: 
                   15340: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
                   15341:             (used when DC is using course creation form)
                   15342: 
                   15343: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15344: 
                   15345: 
                   15346: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15347: 
                   15348: 
                   15349: Side Effects: None
                   15350: 
                   15351: =cut
                   15352: 
                   15353: 
                   15354: sub search_courses {
                   15355:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
                   15356:     my (%courses,%showcourses,$cloner);
                   15357:     if (($filter->{'ownerfilter'} ne '') ||
                   15358:         ($filter->{'ownerdomfilter'} ne '')) {
                   15359:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15360:                                        $filter->{'ownerdomfilter'};
                   15361:     }
                   15362:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15363:         if (!$filter->{$item}) {
                   15364:             $filter->{$item}='.';
                   15365:         }
                   15366:     }
                   15367:     my $now = time;
                   15368:     my $timefilter =
                   15369:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15370:     my ($createdbefore,$createdafter);
                   15371:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15372:         $createdbefore = $now;
                   15373:         $createdafter = $now-$filter->{'createdfilter'};
                   15374:     }
                   15375:     my ($instcodefilter,$regexpok);
                   15376:     if ($numtitles) {
                   15377:         if ($env{'form.official'} eq 'on') {
                   15378:             $instcodefilter =
                   15379:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15380:             $regexpok = 1;
                   15381:         } elsif ($env{'form.official'} eq 'off') {
                   15382:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15383:             unless ($instcodefilter eq '') {
                   15384:                 $regexpok = -1;
                   15385:             }
                   15386:         }
                   15387:     } else {
                   15388:         $instcodefilter = $filter->{'instcodefilter'};
                   15389:     }
                   15390:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15391:     if ($type eq '') { $type = '.'; }
                   15392: 
                   15393:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15394:         $cloner = $cloneruname.':'.$clonerudom;
                   15395:     }
                   15396:     %courses = &Apache::lonnet::courseiddump($dom,
                   15397:                                              $filter->{'descriptfilter'},
                   15398:                                              $timefilter,
                   15399:                                              $instcodefilter,
                   15400:                                              $filter->{'combownerfilter'},
                   15401:                                              $filter->{'coursefilter'},
                   15402:                                              undef,undef,$type,$regexpok,undef,undef,
                   15403:                                              undef,undef,$cloner,$env{'form.cc_clone'},
                   15404:                                              $filter->{'cloneableonly'},
                   15405:                                              $createdbefore,$createdafter,undef,
                   15406:                                              $domcloner);
                   15407:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15408:         my $ccrole;
                   15409:         if ($type eq 'Community') {
                   15410:             $ccrole = 'co';
                   15411:         } else {
                   15412:             $ccrole = 'cc';
                   15413:         }
                   15414:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15415:                                                      $filter->{'persondomfilter'},
                   15416:                                                      'userroles',undef,
                   15417:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15418:                                                      $dom);
                   15419:         foreach my $role (keys(%rolehash)) {
                   15420:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15421:             my $cid = $cdom.'_'.$cnum;
                   15422:             if (exists($courses{$cid})) {
                   15423:                 if (ref($courses{$cid}) eq 'HASH') {
                   15424:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15425:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15426:                             push (@{$courses{$cid}{roles}},$courserole);
                   15427:                         }
                   15428:                     } else {
                   15429:                         $courses{$cid}{roles} = [$courserole];
                   15430:                     }
                   15431:                     $showcourses{$cid} = $courses{$cid};
                   15432:                 }
                   15433:             }
                   15434:         }
                   15435:         %courses = %showcourses;
                   15436:     }
                   15437:     return %courses;
                   15438: }
                   15439: 
                   15440: =pod
                   15441: 
                   15442: =back
                   15443: 
1.1075.2.88  raeburn  15444: =head1 Routines for version requirements for current course.
                   15445: 
                   15446: =over 4
                   15447: 
                   15448: =item * &check_release_required()
                   15449: 
                   15450: Compares required LON-CAPA version with version on server, and
                   15451: if required version is newer looks for a server with the required version.
                   15452: 
                   15453: Looks first at servers in user's owen domain; if none suitable, looks at
                   15454: servers in course's domain are permitted to host sessions for user's domain.
                   15455: 
                   15456: Inputs:
                   15457: 
                   15458: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15459: 
                   15460: $courseid - Course ID of current course
                   15461: 
                   15462: $rolecode - User's current role in course (for switchserver query string).
                   15463: 
                   15464: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15465: 
                   15466: 
                   15467: Returns:
                   15468: 
                   15469: $switchserver - query string tp append to /adm/switchserver call (if
                   15470:                 current server's LON-CAPA version is too old.
                   15471: 
                   15472: $warning - Message is displayed if no suitable server could be found.
                   15473: 
                   15474: =cut
                   15475: 
                   15476: sub check_release_required {
                   15477:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15478:     my ($switchserver,$warning);
                   15479:     if ($required ne '') {
                   15480:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15481:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15482:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15483:             my $otherserver;
                   15484:             if (($major eq '' && $minor eq '') ||
                   15485:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15486:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15487:                 my $switchlcrev =
                   15488:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15489:                                                            $userdomserver);
                   15490:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15491:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15492:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15493:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15494:                     if ($cdom ne $env{'user.domain'}) {
                   15495:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15496:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15497:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15498:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15499:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15500:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15501:                         my $canhost =
                   15502:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15503:                                                               $coursedomserver,
                   15504:                                                               $remoterev,
                   15505:                                                               $udomdefaults{'remotesessions'},
                   15506:                                                               $defdomdefaults{'hostedsessions'});
                   15507: 
                   15508:                         if ($canhost) {
                   15509:                             $otherserver = $coursedomserver;
                   15510:                         } else {
                   15511:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
                   15512:                         }
                   15513:                     } else {
                   15514:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
                   15515:                     }
                   15516:                 } else {
                   15517:                     $otherserver = $userdomserver;
                   15518:                 }
                   15519:             }
                   15520:             if ($otherserver ne '') {
                   15521:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   15522:             }
                   15523:         }
                   15524:     }
                   15525:     return ($switchserver,$warning);
                   15526: }
                   15527: 
                   15528: =pod
                   15529: 
                   15530: =item * &check_release_result()
                   15531: 
                   15532: Inputs:
                   15533: 
                   15534: $switchwarning - Warning message if no suitable server found to host session.
                   15535: 
                   15536: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15537:                 and current role.
                   15538: 
                   15539: Returns: HTML to display with information about requirement to switch server.
                   15540:          Either displaying warning with link to Roles/Courses screen or
                   15541:          display link to switchserver.
                   15542: 
1.1075.2.69  raeburn  15543: =cut
                   15544: 
1.1075.2.88  raeburn  15545: sub check_release_result {
                   15546:     my ($switchwarning,$switchserver) = @_;
                   15547:     my $output = &start_page('Selected course unavailable on this server').
                   15548:                  '<p class="LC_warning">';
                   15549:     if ($switchwarning) {
                   15550:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   15551:         if (&show_course()) {
                   15552:             $output .= &mt('Display courses');
                   15553:         } else {
                   15554:             $output .= &mt('Display roles');
                   15555:         }
                   15556:         $output .= '</a>';
                   15557:     } elsif ($switchserver) {
                   15558:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   15559:                    '<br />'.
                   15560:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   15561:                    &mt('Switch Server').
                   15562:                    '</a>';
                   15563:     }
                   15564:     $output .= '</p>'.&end_page();
                   15565:     return $output;
                   15566: }
                   15567: 
                   15568: =pod
                   15569: 
                   15570: =item * &needs_coursereinit()
                   15571: 
                   15572: Determine if course contents stored for user's session needs to be
                   15573: refreshed, because content has changed since "Big Hash" last tied.
                   15574: 
                   15575: Check for change is made if time last checked is more than 10 minutes ago
                   15576: (by default).
                   15577: 
                   15578: Inputs:
                   15579: 
                   15580: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15581: 
                   15582: $interval (optional) - Time which may elapse (in s) between last check for content
                   15583:                        change in current course. (default: 600 s).
                   15584: 
                   15585: Returns: an array; first element is:
                   15586: 
                   15587: =over 4
                   15588: 
                   15589: 'switch' - if content updates mean user's session
                   15590:            needs to be switched to a server running a newer LON-CAPA version
                   15591: 
                   15592: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   15593:            on current server hosting user's session
                   15594: 
                   15595: ''       - if no action required.
                   15596: 
                   15597: =back
                   15598: 
                   15599: If first item element is 'switch':
                   15600: 
                   15601: second item is $switchwarning - Warning message if no suitable server found to host session.
                   15602: 
                   15603: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15604:                               and current role.
                   15605: 
                   15606: otherwise: no other elements returned.
                   15607: 
                   15608: =back
                   15609: 
                   15610: =cut
                   15611: 
                   15612: sub needs_coursereinit {
                   15613:     my ($loncaparev,$interval) = @_;
                   15614:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   15615:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   15616:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   15617:     my $now = time;
                   15618:     if ($interval eq '') {
                   15619:         $interval = 600;
                   15620:     }
                   15621:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   15622:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15623:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   15624:         if ($lastchange > $env{'request.course.tied'}) {
                   15625:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15626:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   15627:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   15628:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   15629:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   15630:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   15631:                     my ($switchserver,$switchwarning) =
                   15632:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   15633:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   15634:                     if ($switchwarning ne '' || $switchserver ne '') {
                   15635:                         return ('switch',$switchwarning,$switchserver);
                   15636:                     }
                   15637:                 }
                   15638:             }
                   15639:             return ('update');
                   15640:         }
                   15641:     }
                   15642:     return ();
                   15643: }
1.1075.2.69  raeburn  15644: 
1.1075.2.11  raeburn  15645: sub update_content_constraints {
                   15646:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15647:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15648:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15649:     my %checkresponsetypes;
                   15650:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15651:         my ($item,$name,$value) = split(/:/,$key);
                   15652:         if ($item eq 'resourcetag') {
                   15653:             if ($name eq 'responsetype') {
                   15654:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15655:             }
                   15656:         }
                   15657:     }
                   15658:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15659:     if (defined($navmap)) {
                   15660:         my %allresponses;
                   15661:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15662:             my %responses = $res->responseTypes();
                   15663:             foreach my $key (keys(%responses)) {
                   15664:                 next unless(exists($checkresponsetypes{$key}));
                   15665:                 $allresponses{$key} += $responses{$key};
                   15666:             }
                   15667:         }
                   15668:         foreach my $key (keys(%allresponses)) {
                   15669:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15670:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15671:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15672:             }
                   15673:         }
                   15674:         undef($navmap);
                   15675:     }
                   15676:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15677:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15678:     }
                   15679:     return;
                   15680: }
                   15681: 
1.1075.2.27  raeburn  15682: sub allmaps_incourse {
                   15683:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15684:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15685:         $cid = $env{'request.course.id'};
                   15686:         $cdom = $env{'course.'.$cid.'.domain'};
                   15687:         $cnum = $env{'course.'.$cid.'.num'};
                   15688:         $chome = $env{'course.'.$cid.'.home'};
                   15689:     }
                   15690:     my %allmaps = ();
                   15691:     my $lastchange =
                   15692:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15693:     if ($lastchange > $env{'request.course.tied'}) {
                   15694:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15695:         unless ($ferr) {
                   15696:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15697:         }
                   15698:     }
                   15699:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15700:     if (defined($navmap)) {
                   15701:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15702:             $allmaps{$res->src()} = 1;
                   15703:         }
                   15704:     }
                   15705:     return \%allmaps;
                   15706: }
                   15707: 
1.1075.2.11  raeburn  15708: sub parse_supplemental_title {
                   15709:     my ($title) = @_;
                   15710: 
                   15711:     my ($foldertitle,$renametitle);
                   15712:     if ($title =~ /&amp;&amp;&amp;/) {
                   15713:         $title = &HTML::Entites::decode($title);
                   15714:     }
                   15715:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   15716:         $renametitle=$4;
                   15717:         my ($time,$uname,$udom) = ($1,$2,$3);
                   15718:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   15719:         my $name =  &plainname($uname,$udom);
                   15720:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   15721:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   15722:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   15723:             $name.': <br />'.$foldertitle;
                   15724:     }
                   15725:     if (wantarray) {
                   15726:         return ($title,$foldertitle,$renametitle);
                   15727:     }
                   15728:     return $title;
                   15729: }
                   15730: 
1.1075.2.43  raeburn  15731: sub recurse_supplemental {
                   15732:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   15733:     if ($suppmap) {
                   15734:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   15735:         if ($fatal) {
                   15736:             $errors ++;
                   15737:         } else {
                   15738:             if ($#LONCAPA::map::resources > 0) {
                   15739:                 foreach my $res (@LONCAPA::map::resources) {
                   15740:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   15741:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  15742:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   15743:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  15744:                         } else {
                   15745:                             $numfiles ++;
                   15746:                         }
                   15747:                     }
                   15748:                 }
                   15749:             }
                   15750:         }
                   15751:     }
                   15752:     return ($numfiles,$errors);
                   15753: }
                   15754: 
1.1075.2.18  raeburn  15755: sub symb_to_docspath {
                   15756:     my ($symb) = @_;
                   15757:     return unless ($symb);
                   15758:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   15759:     if ($resurl=~/\.(sequence|page)$/) {
                   15760:         $mapurl=$resurl;
                   15761:     } elsif ($resurl eq 'adm/navmaps') {
                   15762:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   15763:     }
                   15764:     my $mapresobj;
                   15765:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15766:     if (ref($navmap)) {
                   15767:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   15768:     }
                   15769:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   15770:     my $type=$2;
                   15771:     my $path;
                   15772:     if (ref($mapresobj)) {
                   15773:         my $pcslist = $mapresobj->map_hierarchy();
                   15774:         if ($pcslist ne '') {
                   15775:             foreach my $pc (split(/,/,$pcslist)) {
                   15776:                 next if ($pc <= 1);
                   15777:                 my $res = $navmap->getByMapPc($pc);
                   15778:                 if (ref($res)) {
                   15779:                     my $thisurl = $res->src();
                   15780:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   15781:                     my $thistitle = $res->title();
                   15782:                     $path .= '&'.
                   15783:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  15784:                              &escape($thistitle).
1.1075.2.18  raeburn  15785:                              ':'.$res->randompick().
                   15786:                              ':'.$res->randomout().
                   15787:                              ':'.$res->encrypted().
                   15788:                              ':'.$res->randomorder().
                   15789:                              ':'.$res->is_page();
                   15790:                 }
                   15791:             }
                   15792:         }
                   15793:         $path =~ s/^\&//;
                   15794:         my $maptitle = $mapresobj->title();
                   15795:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  15796:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  15797:         }
                   15798:         $path .= (($path ne '')? '&' : '').
                   15799:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  15800:                  &escape($maptitle).
1.1075.2.18  raeburn  15801:                  ':'.$mapresobj->randompick().
                   15802:                  ':'.$mapresobj->randomout().
                   15803:                  ':'.$mapresobj->encrypted().
                   15804:                  ':'.$mapresobj->randomorder().
                   15805:                  ':'.$mapresobj->is_page();
                   15806:     } else {
                   15807:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   15808:         my $ispage = (($type eq 'page')? 1 : '');
                   15809:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  15810:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  15811:         }
                   15812:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  15813:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  15814:     }
                   15815:     unless ($mapurl eq 'default') {
                   15816:         $path = 'default&'.
1.1075.2.46  raeburn  15817:                 &escape('Main Content').
1.1075.2.18  raeburn  15818:                 ':::::&'.$path;
                   15819:     }
                   15820:     return $path;
                   15821: }
                   15822: 
1.1075.2.14  raeburn  15823: sub captcha_display {
                   15824:     my ($context,$lonhost) = @_;
                   15825:     my ($output,$error);
                   15826:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   15827:     if ($captcha eq 'original') {
                   15828:         $output = &create_captcha();
                   15829:         unless ($output) {
                   15830:             $error = 'captcha';
                   15831:         }
                   15832:     } elsif ($captcha eq 'recaptcha') {
                   15833:         $output = &create_recaptcha($pubkey);
                   15834:         unless ($output) {
                   15835:             $error = 'recaptcha';
                   15836:         }
                   15837:     }
1.1075.2.66  raeburn  15838:     return ($output,$error,$captcha);
1.1075.2.14  raeburn  15839: }
                   15840: 
                   15841: sub captcha_response {
                   15842:     my ($context,$lonhost) = @_;
                   15843:     my ($captcha_chk,$captcha_error);
                   15844:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   15845:     if ($captcha eq 'original') {
                   15846:         ($captcha_chk,$captcha_error) = &check_captcha();
                   15847:     } elsif ($captcha eq 'recaptcha') {
                   15848:         $captcha_chk = &check_recaptcha($privkey);
                   15849:     } else {
                   15850:         $captcha_chk = 1;
                   15851:     }
                   15852:     return ($captcha_chk,$captcha_error);
                   15853: }
                   15854: 
                   15855: sub get_captcha_config {
                   15856:     my ($context,$lonhost) = @_;
                   15857:     my ($captcha,$pubkey,$privkey,$hashtocheck);
                   15858:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   15859:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   15860:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15861:     if ($context eq 'usercreation') {
                   15862:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   15863:         if (ref($domconfig{$context}) eq 'HASH') {
                   15864:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   15865:             if (ref($hashtocheck) eq 'HASH') {
                   15866:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   15867:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   15868:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   15869:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   15870:                     }
                   15871:                     if ($privkey && $pubkey) {
                   15872:                         $captcha = 'recaptcha';
                   15873:                     } else {
                   15874:                         $captcha = 'original';
                   15875:                     }
                   15876:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   15877:                     $captcha = 'original';
                   15878:                 }
                   15879:             }
                   15880:         } else {
                   15881:             $captcha = 'captcha';
                   15882:         }
                   15883:     } elsif ($context eq 'login') {
                   15884:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   15885:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   15886:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   15887:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   15888:             if ($privkey && $pubkey) {
                   15889:                 $captcha = 'recaptcha';
                   15890:             } else {
                   15891:                 $captcha = 'original';
                   15892:             }
                   15893:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   15894:             $captcha = 'original';
                   15895:         }
                   15896:     }
                   15897:     return ($captcha,$pubkey,$privkey);
                   15898: }
                   15899: 
                   15900: sub create_captcha {
                   15901:     my %captcha_params = &captcha_settings();
                   15902:     my ($output,$maxtries,$tries) = ('',10,0);
                   15903:     while ($tries < $maxtries) {
                   15904:         $tries ++;
                   15905:         my $captcha = Authen::Captcha->new (
                   15906:                                            output_folder => $captcha_params{'output_dir'},
                   15907:                                            data_folder   => $captcha_params{'db_dir'},
                   15908:                                           );
                   15909:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   15910: 
                   15911:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   15912:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   15913:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  15914:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   15915:                       '<br />'.
                   15916:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  15917:             last;
                   15918:         }
                   15919:     }
                   15920:     return $output;
                   15921: }
                   15922: 
                   15923: sub captcha_settings {
                   15924:     my %captcha_params = (
                   15925:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   15926:                            www_output_dir => "/captchaspool",
                   15927:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   15928:                            numchars       => '5',
                   15929:                          );
                   15930:     return %captcha_params;
                   15931: }
                   15932: 
                   15933: sub check_captcha {
                   15934:     my ($captcha_chk,$captcha_error);
                   15935:     my $code = $env{'form.code'};
                   15936:     my $md5sum = $env{'form.crypt'};
                   15937:     my %captcha_params = &captcha_settings();
                   15938:     my $captcha = Authen::Captcha->new(
                   15939:                       output_folder => $captcha_params{'output_dir'},
                   15940:                       data_folder   => $captcha_params{'db_dir'},
                   15941:                   );
1.1075.2.26  raeburn  15942:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  15943:     my %captcha_hash = (
                   15944:                         0       => 'Code not checked (file error)',
                   15945:                        -1      => 'Failed: code expired',
                   15946:                        -2      => 'Failed: invalid code (not in database)',
                   15947:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   15948:     );
                   15949:     if ($captcha_chk != 1) {
                   15950:         $captcha_error = $captcha_hash{$captcha_chk}
                   15951:     }
                   15952:     return ($captcha_chk,$captcha_error);
                   15953: }
                   15954: 
                   15955: sub create_recaptcha {
                   15956:     my ($pubkey) = @_;
1.1075.2.51  raeburn  15957:     my $use_ssl;
                   15958:     if ($ENV{'SERVER_PORT'} == 443) {
                   15959:         $use_ssl = 1;
                   15960:     }
1.1075.2.14  raeburn  15961:     my $captcha = Captcha::reCAPTCHA->new;
                   15962:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1075.2.51  raeburn  15963:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1075.2.92! raeburn  15964:            &mt('If the text is hard to read, [_1] will replace them.',
1.1075.2.39  raeburn  15965:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1075.2.14  raeburn  15966:            '<br /><br />';
                   15967: }
                   15968: 
                   15969: sub check_recaptcha {
                   15970:     my ($privkey) = @_;
                   15971:     my $captcha_chk;
                   15972:     my $captcha = Captcha::reCAPTCHA->new;
                   15973:     my $captcha_result =
                   15974:         $captcha->check_answer(
                   15975:                                 $privkey,
                   15976:                                 $ENV{'REMOTE_ADDR'},
                   15977:                                 $env{'form.recaptcha_challenge_field'},
                   15978:                                 $env{'form.recaptcha_response_field'},
                   15979:                               );
                   15980:     if ($captcha_result->{is_valid}) {
                   15981:         $captcha_chk = 1;
                   15982:     }
                   15983:     return $captcha_chk;
                   15984: }
                   15985: 
1.1075.2.64  raeburn  15986: sub emailusername_info {
1.1075.2.67  raeburn  15987:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1075.2.64  raeburn  15988:     my %titles = &Apache::lonlocal::texthash (
                   15989:                      lastname      => 'Last Name',
                   15990:                      firstname     => 'First Name',
                   15991:                      institution   => 'School/college/university',
                   15992:                      location      => "School's city, state/province, country",
                   15993:                      web           => "School's web address",
                   15994:                      officialemail => 'E-mail address at institution (if different)',
                   15995:                  );
                   15996:     return (\@fields,\%titles);
                   15997: }
                   15998: 
1.1075.2.56  raeburn  15999: sub cleanup_html {
                   16000:     my ($incoming) = @_;
                   16001:     my $outgoing;
                   16002:     if ($incoming ne '') {
                   16003:         $outgoing = $incoming;
                   16004:         $outgoing =~ s/;/&#059;/g;
                   16005:         $outgoing =~ s/\#/&#035;/g;
                   16006:         $outgoing =~ s/\&/&#038;/g;
                   16007:         $outgoing =~ s/</&#060;/g;
                   16008:         $outgoing =~ s/>/&#062;/g;
                   16009:         $outgoing =~ s/\(/&#040/g;
                   16010:         $outgoing =~ s/\)/&#041;/g;
                   16011:         $outgoing =~ s/"/&#034;/g;
                   16012:         $outgoing =~ s/'/&#039;/g;
                   16013:         $outgoing =~ s/\$/&#036;/g;
                   16014:         $outgoing =~ s{/}{&#047;}g;
                   16015:         $outgoing =~ s/=/&#061;/g;
                   16016:         $outgoing =~ s/\\/&#092;/g
                   16017:     }
                   16018:     return $outgoing;
                   16019: }
                   16020: 
1.1075.2.74  raeburn  16021: # Checks for critical messages and returns a redirect url if one exists.
                   16022: # $interval indicates how often to check for messages.
                   16023: sub critical_redirect {
                   16024:     my ($interval) = @_;
                   16025:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16026:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16027:                                         $env{'user.name'});
                   16028:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16029:         my $redirecturl;
                   16030:         if ($what[0]) {
                   16031:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16032:                 $redirecturl='/adm/email?critical=display';
                   16033:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16034:                 return (1, $url);
                   16035:             }
                   16036:         }
                   16037:     }
                   16038:     return ();
                   16039: }
                   16040: 
1.1075.2.64  raeburn  16041: # Use:
                   16042: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16043: #
                   16044: ##################################################
                   16045: #          password associated functions         #
                   16046: ##################################################
                   16047: sub des_keys {
                   16048:     # Make a new key for DES encryption.
                   16049:     # Each key has two parts which are returned separately.
                   16050:     # Please note:  Each key must be passed through the &hex function
                   16051:     # before it is output to the web browser.  The hex versions cannot
                   16052:     # be used to decrypt.
                   16053:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16054:                 '8','9','a','b','c','d','e','f');
                   16055:     my $lkey='';
                   16056:     for (0..7) {
                   16057:         $lkey.=$hexstr[rand(15)];
                   16058:     }
                   16059:     my $ukey='';
                   16060:     for (0..7) {
                   16061:         $ukey.=$hexstr[rand(15)];
                   16062:     }
                   16063:     return ($lkey,$ukey);
                   16064: }
                   16065: 
                   16066: sub des_decrypt {
                   16067:     my ($key,$cyphertext) = @_;
                   16068:     my $keybin=pack("H16",$key);
                   16069:     my $cypher;
                   16070:     if ($Crypt::DES::VERSION>=2.03) {
                   16071:         $cypher=new Crypt::DES $keybin;
                   16072:     } else {
                   16073:         $cypher=new DES $keybin;
                   16074:     }
                   16075:     my $plaintext=
                   16076:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16077:     $plaintext.=
                   16078:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16079:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16080:     return $plaintext;
                   16081: }
                   16082: 
1.112     bowersj2 16083: 1;
                   16084: __END__;
1.41      ng       16085: 

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