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

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.93! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.92 2015/04/07 15:13:35 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');
1.1075.2.93! raeburn  4651:     my $class = 'LC_comblock';
1.1062    raeburn  4652:     if ($activity eq 'docs') {
                   4653:         $text = &mt('Content Access Blocked');
1.1075.2.93! raeburn  4654:         $class = '';
1.1063    raeburn  4655:     } elsif ($activity eq 'printout') {
                   4656:         $text = &mt('Printing Blocked');
1.1062    raeburn  4657:     }
1.1061    raeburn  4658:     $output .= <<"END_BLOCK";
1.1075.2.93! raeburn  4659: <div class='$class'>
1.869     kalberla 4660:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4661:   title='$text'>
                   4662:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4663:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4664:   title='$text'>$text</a>
1.867     kalberla 4665: </div>
                   4666: 
                   4667: END_BLOCK
1.474     raeburn  4668: 
1.1061    raeburn  4669:     return ($blocked, $output);
1.854     kalberla 4670: }
1.490     raeburn  4671: 
1.60      matthew  4672: ###############################################
                   4673: 
1.682     raeburn  4674: sub check_ip_acc {
                   4675:     my ($acc)=@_;
                   4676:     &Apache::lonxml::debug("acc is $acc");
                   4677:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4678:         return 1;
                   4679:     }
                   4680:     my $allowed=0;
                   4681:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4682: 
                   4683:     my $name;
                   4684:     foreach my $pattern (split(',',$acc)) {
                   4685:         $pattern =~ s/^\s*//;
                   4686:         $pattern =~ s/\s*$//;
                   4687:         if ($pattern =~ /\*$/) {
                   4688:             #35.8.*
                   4689:             $pattern=~s/\*//;
                   4690:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4691:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4692:             #35.8.3.[34-56]
                   4693:             my $low=$2;
                   4694:             my $high=$3;
                   4695:             $pattern=$1;
                   4696:             if ($ip =~ /^\Q$pattern\E/) {
                   4697:                 my $last=(split(/\./,$ip))[3];
                   4698:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4699:             }
                   4700:         } elsif ($pattern =~ /^\*/) {
                   4701:             #*.msu.edu
                   4702:             $pattern=~s/\*//;
                   4703:             if (!defined($name)) {
                   4704:                 use Socket;
                   4705:                 my $netaddr=inet_aton($ip);
                   4706:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4707:             }
                   4708:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4709:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4710:             #127.0.0.1
                   4711:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4712:         } else {
                   4713:             #some.name.com
                   4714:             if (!defined($name)) {
                   4715:                 use Socket;
                   4716:                 my $netaddr=inet_aton($ip);
                   4717:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4718:             }
                   4719:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4720:         }
                   4721:         if ($allowed) { last; }
                   4722:     }
                   4723:     return $allowed;
                   4724: }
                   4725: 
                   4726: ###############################################
                   4727: 
1.60      matthew  4728: =pod
                   4729: 
1.112     bowersj2 4730: =head1 Domain Template Functions
                   4731: 
                   4732: =over 4
                   4733: 
                   4734: =item * &determinedomain()
1.60      matthew  4735: 
                   4736: Inputs: $domain (usually will be undef)
                   4737: 
1.63      www      4738: Returns: Determines which domain should be used for designs
1.60      matthew  4739: 
                   4740: =cut
1.54      www      4741: 
1.60      matthew  4742: ###############################################
1.63      www      4743: sub determinedomain {
                   4744:     my $domain=shift;
1.531     albertel 4745:     if (! $domain) {
1.60      matthew  4746:         # Determine domain if we have not been given one
1.893     raeburn  4747:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4748:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4749:         if ($env{'request.role.domain'}) { 
                   4750:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4751:         }
                   4752:     }
1.63      www      4753:     return $domain;
                   4754: }
                   4755: ###############################################
1.517     raeburn  4756: 
1.518     albertel 4757: sub devalidate_domconfig_cache {
                   4758:     my ($udom)=@_;
                   4759:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4760: }
                   4761: 
                   4762: # ---------------------- Get domain configuration for a domain
                   4763: sub get_domainconf {
                   4764:     my ($udom) = @_;
                   4765:     my $cachetime=1800;
                   4766:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4767:     if (defined($cached)) { return %{$result}; }
                   4768: 
                   4769:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4770: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4771:     my (%designhash,%legacy);
1.518     albertel 4772:     if (keys(%domconfig) > 0) {
                   4773:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4774:             if (keys(%{$domconfig{'login'}})) {
                   4775:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4776:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  4777:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   4778:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   4779:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   4780:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   4781:                                         if ($key eq 'loginvia') {
                   4782:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4783:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4784:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   4785:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4786:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4787:                                                 } else {
                   4788:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   4789:                                                 }
1.948     raeburn  4790:                                             }
1.1075.2.87  raeburn  4791:                                         } elsif ($key eq 'headtag') {
                   4792:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   4793:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  4794:                                             }
1.946     raeburn  4795:                                         }
1.1075.2.87  raeburn  4796:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   4797:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   4798:                                         }
1.946     raeburn  4799:                                     }
                   4800:                                 }
                   4801:                             }
                   4802:                         } else {
                   4803:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4804:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4805:                                     $domconfig{'login'}{$key}{$img};
                   4806:                             }
1.699     raeburn  4807:                         }
                   4808:                     } else {
                   4809:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4810:                     }
1.632     raeburn  4811:                 }
                   4812:             } else {
                   4813:                 $legacy{'login'} = 1;
1.518     albertel 4814:             }
1.632     raeburn  4815:         } else {
                   4816:             $legacy{'login'} = 1;
1.518     albertel 4817:         }
                   4818:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4819:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4820:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4821:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4822:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4823:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4824:                         }
1.518     albertel 4825:                     }
                   4826:                 }
1.632     raeburn  4827:             } else {
                   4828:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4829:             }
1.632     raeburn  4830:         } else {
                   4831:             $legacy{'rolecolors'} = 1;
1.518     albertel 4832:         }
1.948     raeburn  4833:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4834:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4835:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4836:             }
                   4837:         }
1.632     raeburn  4838:         if (keys(%legacy) > 0) {
                   4839:             my %legacyhash = &get_legacy_domconf($udom);
                   4840:             foreach my $item (keys(%legacyhash)) {
                   4841:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4842:                     if ($legacy{'login'}) { 
                   4843:                         $designhash{$item} = $legacyhash{$item};
                   4844:                     }
                   4845:                 } else {
                   4846:                     if ($legacy{'rolecolors'}) {
                   4847:                         $designhash{$item} = $legacyhash{$item};
                   4848:                     }
1.518     albertel 4849:                 }
                   4850:             }
                   4851:         }
1.632     raeburn  4852:     } else {
                   4853:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4854:     }
                   4855:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4856: 				  $cachetime);
                   4857:     return %designhash;
                   4858: }
                   4859: 
1.632     raeburn  4860: sub get_legacy_domconf {
                   4861:     my ($udom) = @_;
                   4862:     my %legacyhash;
                   4863:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4864:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4865:     if (-e $designfile) {
                   4866:         if ( open (my $fh,"<$designfile") ) {
                   4867:             while (my $line = <$fh>) {
                   4868:                 next if ($line =~ /^\#/);
                   4869:                 chomp($line);
                   4870:                 my ($key,$val)=(split(/\=/,$line));
                   4871:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4872:             }
                   4873:             close($fh);
                   4874:         }
                   4875:     }
1.1026    raeburn  4876:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4877:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4878:     }
                   4879:     return %legacyhash;
                   4880: }
                   4881: 
1.63      www      4882: =pod
                   4883: 
1.112     bowersj2 4884: =item * &domainlogo()
1.63      www      4885: 
                   4886: Inputs: $domain (usually will be undef)
                   4887: 
                   4888: Returns: A link to a domain logo, if the domain logo exists.
                   4889: If the domain logo does not exist, a description of the domain.
                   4890: 
                   4891: =cut
1.112     bowersj2 4892: 
1.63      www      4893: ###############################################
                   4894: sub domainlogo {
1.517     raeburn  4895:     my $domain = &determinedomain(shift);
1.518     albertel 4896:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4897:     # See if there is a logo
                   4898:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4899:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4900:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4901: 	    if ($imgsrc =~ m{^/res/}) {
                   4902: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4903: 		&Apache::lonnet::repcopy($local_name);
                   4904: 	    }
                   4905: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4906:         } 
                   4907:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4908:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4909:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4910:     } else {
1.60      matthew  4911:         return '';
1.59      www      4912:     }
                   4913: }
1.63      www      4914: ##############################################
                   4915: 
                   4916: =pod
                   4917: 
1.112     bowersj2 4918: =item * &designparm()
1.63      www      4919: 
                   4920: Inputs: $which parameter; $domain (usually will be undef)
                   4921: 
                   4922: Returns: value of designparamter $which
                   4923: 
                   4924: =cut
1.112     bowersj2 4925: 
1.397     albertel 4926: 
1.400     albertel 4927: ##############################################
1.397     albertel 4928: sub designparm {
                   4929:     my ($which,$domain)=@_;
                   4930:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4931:         return $env{'environment.color.'.$which};
1.96      www      4932:     }
1.63      www      4933:     $domain=&determinedomain($domain);
1.1016    raeburn  4934:     my %domdesign;
                   4935:     unless ($domain eq 'public') {
                   4936:         %domdesign = &get_domainconf($domain);
                   4937:     }
1.520     raeburn  4938:     my $output;
1.517     raeburn  4939:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4940:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4941:     } else {
1.520     raeburn  4942:         $output = $defaultdesign{$which};
                   4943:     }
                   4944:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4945:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4946:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4947:             if ($output =~ m{^/res/}) {
                   4948:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4949:                 &Apache::lonnet::repcopy($local_name);
                   4950:             }
1.520     raeburn  4951:             $output = &lonhttpdurl($output);
                   4952:         }
1.63      www      4953:     }
1.520     raeburn  4954:     return $output;
1.63      www      4955: }
1.59      www      4956: 
1.822     bisitz   4957: ##############################################
                   4958: =pod
                   4959: 
1.832     bisitz   4960: =item * &authorspace()
                   4961: 
1.1028    raeburn  4962: Inputs: $url (usually will be undef).
1.832     bisitz   4963: 
1.1075.2.40  raeburn  4964: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  4965:          directory being viewed (or for which action is being taken). 
                   4966:          If $url is provided, and begins /priv/<domain>/<uname>
                   4967:          the path will be that portion of the $context argument.
                   4968:          Otherwise the path will be for the author space of the current
                   4969:          user when the current role is author, or for that of the 
                   4970:          co-author/assistant co-author space when the current role 
                   4971:          is co-author or assistant co-author.
1.832     bisitz   4972: 
                   4973: =cut
                   4974: 
                   4975: sub authorspace {
1.1028    raeburn  4976:     my ($url) = @_;
                   4977:     if ($url ne '') {
                   4978:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4979:            return $1;
                   4980:         }
                   4981:     }
1.832     bisitz   4982:     my $caname = '';
1.1024    www      4983:     my $cadom = '';
1.1028    raeburn  4984:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4985:         ($cadom,$caname) =
1.832     bisitz   4986:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4987:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4988:         $caname = $env{'user.name'};
1.1024    www      4989:         $cadom = $env{'user.domain'};
1.832     bisitz   4990:     }
1.1028    raeburn  4991:     if (($caname ne '') && ($cadom ne '')) {
                   4992:         return "/priv/$cadom/$caname/";
                   4993:     }
                   4994:     return;
1.832     bisitz   4995: }
                   4996: 
                   4997: ##############################################
                   4998: =pod
                   4999: 
1.822     bisitz   5000: =item * &head_subbox()
                   5001: 
                   5002: Inputs: $content (contains HTML code with page functions, etc.)
                   5003: 
                   5004: Returns: HTML div with $content
                   5005:          To be included in page header
                   5006: 
                   5007: =cut
                   5008: 
                   5009: sub head_subbox {
                   5010:     my ($content)=@_;
                   5011:     my $output =
1.993     raeburn  5012:         '<div class="LC_head_subbox">'
1.822     bisitz   5013:        .$content
                   5014:        .'</div>'
                   5015: }
                   5016: 
                   5017: ##############################################
                   5018: =pod
                   5019: 
                   5020: =item * &CSTR_pageheader()
                   5021: 
1.1026    raeburn  5022: Input: (optional) filename from which breadcrumb trail is built.
                   5023:        In most cases no input as needed, as $env{'request.filename'}
                   5024:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5025: 
                   5026: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5027:          To be included on Authoring Space pages
1.822     bisitz   5028: 
                   5029: =cut
                   5030: 
                   5031: sub CSTR_pageheader {
1.1026    raeburn  5032:     my ($trailfile) = @_;
                   5033:     if ($trailfile eq '') {
                   5034:         $trailfile = $env{'request.filename'};
                   5035:     }
                   5036: 
                   5037: # this is for resources; directories have customtitle, and crumbs
                   5038: # and select recent are created in lonpubdir.pm
                   5039: 
                   5040:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5041:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5042:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5043:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5044:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5045: 
                   5046:     my $parentpath = '';
                   5047:     my $lastitem = '';
                   5048:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5049:         $parentpath = $1;
                   5050:         $lastitem = $2;
                   5051:     } else {
                   5052:         $lastitem = $thisdisfn;
                   5053:     }
1.921     bisitz   5054: 
                   5055:     my $output =
1.822     bisitz   5056:          '<div>'
                   5057:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5058:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5059:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5060:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5061:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5062: 
                   5063:     if ($lastitem) {
                   5064:         $output .=
                   5065:              '<span class="LC_filename">'
                   5066:             .$lastitem
                   5067:             .'</span>';
                   5068:     }
                   5069:     $output .=
                   5070:          '<br />'
1.822     bisitz   5071:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5072:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5073:         .'</form>'
                   5074:         .&Apache::lonmenu::constspaceform()
                   5075:         .'</div>';
1.921     bisitz   5076: 
                   5077:     return $output;
1.822     bisitz   5078: }
                   5079: 
1.60      matthew  5080: ###############################################
                   5081: ###############################################
                   5082: 
                   5083: =pod
                   5084: 
1.112     bowersj2 5085: =back
                   5086: 
1.549     albertel 5087: =head1 HTML Helpers
1.112     bowersj2 5088: 
                   5089: =over 4
                   5090: 
                   5091: =item * &bodytag()
1.60      matthew  5092: 
                   5093: Returns a uniform header for LON-CAPA web pages.
                   5094: 
                   5095: Inputs: 
                   5096: 
1.112     bowersj2 5097: =over 4
                   5098: 
                   5099: =item * $title, A title to be displayed on the page.
                   5100: 
                   5101: =item * $function, the current role (can be undef).
                   5102: 
                   5103: =item * $addentries, extra parameters for the <body> tag.
                   5104: 
                   5105: =item * $bodyonly, if defined, only return the <body> tag.
                   5106: 
                   5107: =item * $domain, if defined, force a given domain.
                   5108: 
                   5109: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5110:             text interface only)
1.60      matthew  5111: 
1.814     bisitz   5112: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5113:                      navigational links
1.317     albertel 5114: 
1.338     albertel 5115: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5116: 
1.1075.2.12  raeburn  5117: =item * $no_inline_link, if true and in remote mode, don't show the
                   5118:          'Switch To Inline Menu' link
                   5119: 
1.460     albertel 5120: =item * $args, optional argument valid values are
                   5121:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5122:             inherit_jsmath -> when creating popup window in a page,
                   5123:                               should it have jsmath forced on by the
                   5124:                               current page
1.460     albertel 5125: 
1.1075.2.15  raeburn  5126: =item * $advtoolsref, optional argument, ref to an array containing
                   5127:             inlineremote items to be added in "Functions" menu below
                   5128:             breadcrumbs.
                   5129: 
1.112     bowersj2 5130: =back
                   5131: 
1.60      matthew  5132: Returns: A uniform header for LON-CAPA web pages.  
                   5133: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5134: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5135: other decorations will be returned.
                   5136: 
                   5137: =cut
                   5138: 
1.54      www      5139: sub bodytag {
1.831     bisitz   5140:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5141:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5142: 
1.954     raeburn  5143:     my $public;
                   5144:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5145:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5146:         $public = 1;
                   5147:     }
1.460     albertel 5148:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5149:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5150: 
1.183     matthew  5151:     $function = &get_users_function() if (!$function);
1.339     albertel 5152:     my $img =    &designparm($function.'.img',$domain);
                   5153:     my $font =   &designparm($function.'.font',$domain);
                   5154:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5155: 
1.803     bisitz   5156:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5157: 		   'bgcolor' => $pgbg,
1.339     albertel 5158: 		   'text'    => $font,
                   5159:                    'alink'   => &designparm($function.'.alink',$domain),
                   5160: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5161: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5162:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5163: 
1.63      www      5164:  # role and realm
1.1075.2.68  raeburn  5165:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5166:     if ($realm) {
                   5167:         $realm = '/'.$realm;
                   5168:     }
1.378     raeburn  5169:     if ($role  eq 'ca') {
1.479     albertel 5170:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5171:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5172:     } 
1.55      www      5173: # realm
1.258     albertel 5174:     if ($env{'request.course.id'}) {
1.378     raeburn  5175:         if ($env{'request.role'} !~ /^cr/) {
                   5176:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5177:         }
1.898     raeburn  5178:         if ($env{'request.course.sec'}) {
                   5179:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5180:         }   
1.359     albertel 5181: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5182:     } else {
                   5183:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5184:     }
1.433     albertel 5185: 
1.359     albertel 5186:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5187: 
1.438     albertel 5188:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5189: 
1.101     www      5190: # construct main body tag
1.359     albertel 5191:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5192: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5193: 
1.1075.2.38  raeburn  5194:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5195: 
                   5196:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5197:         return $bodytag;
1.1075.2.38  raeburn  5198:     }
1.359     albertel 5199: 
1.954     raeburn  5200:     if ($public) {
1.433     albertel 5201: 	undef($role);
                   5202:     }
1.359     albertel 5203:     
1.762     bisitz   5204:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5205:     #
                   5206:     # Extra info if you are the DC
                   5207:     my $dc_info = '';
                   5208:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5209:                         $env{'course.'.$env{'request.course.id'}.
                   5210:                                  '.domain'}.'/'})) {
                   5211:         my $cid = $env{'request.course.id'};
1.917     raeburn  5212:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5213:         $dc_info =~ s/\s+$//;
1.359     albertel 5214:     }
                   5215: 
1.898     raeburn  5216:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.903     droeschl 5217: 
1.1075.2.13  raeburn  5218:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5219: 
1.1075.2.38  raeburn  5220: 
                   5221: 
1.1075.2.21  raeburn  5222:     my $funclist;
                   5223:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5224:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5225:                     Apache::lonmenu::serverform();
                   5226:         my $forbodytag;
                   5227:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5228:                                             $forcereg,$args->{'group'},
                   5229:                                             $args->{'bread_crumbs'},
                   5230:                                             $advtoolsref,'',\$forbodytag);
                   5231:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5232:             $funclist = $forbodytag;
                   5233:         }
                   5234:     } else {
1.903     droeschl 5235: 
                   5236:         #    if ($env{'request.state'} eq 'construct') {
                   5237:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5238:         #    }
                   5239: 
1.1075.2.38  raeburn  5240:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5241:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5242: 
1.1075.2.38  raeburn  5243:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5244: 
1.916     droeschl 5245:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5246:             if ($dc_info) {
                   5247:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5248:             }
1.1075.2.38  raeburn  5249:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5250:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5251:             return $bodytag;
                   5252:         }
1.894     droeschl 5253: 
1.927     raeburn  5254:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5255:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5256:         }
1.916     droeschl 5257: 
1.1075.2.38  raeburn  5258:         $bodytag .= $right;
1.852     droeschl 5259: 
1.917     raeburn  5260:         if ($dc_info) {
                   5261:             $dc_info = &dc_courseid_toggle($dc_info);
                   5262:         }
                   5263:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5264: 
1.1075.2.61  raeburn  5265:         #if directed to not display the secondary menu, don't.
                   5266:         if ($args->{'no_secondary_menu'}) {
                   5267:             return $bodytag;
                   5268:         }
1.903     droeschl 5269:         #don't show menus for public users
1.954     raeburn  5270:         if (!$public){
1.1075.2.52  raeburn  5271:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5272:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5273:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5274:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5275:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5276:                                 $args->{'bread_crumbs'});
                   5277:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5278:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5279:                                                             $args->{'group'});
1.1075.2.15  raeburn  5280:             } else {
1.1075.2.21  raeburn  5281:                 my $forbodytag;
                   5282:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5283:                                                     $forcereg,$args->{'group'},
                   5284:                                                     $args->{'bread_crumbs'},
                   5285:                                                     $advtoolsref,'',\$forbodytag);
                   5286:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5287:                     $bodytag .= $forbodytag;
                   5288:                 }
1.920     raeburn  5289:             }
1.903     droeschl 5290:         }else{
                   5291:             # this is to seperate menu from content when there's no secondary
                   5292:             # menu. Especially needed for public accessible ressources.
                   5293:             $bodytag .= '<hr style="clear:both" />';
                   5294:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5295:         }
1.903     droeschl 5296: 
1.235     raeburn  5297:         return $bodytag;
1.1075.2.12  raeburn  5298:     }
                   5299: 
                   5300: #
                   5301: # Top frame rendering, Remote is up
                   5302: #
                   5303: 
                   5304:     my $imgsrc = $img;
                   5305:     if ($img =~ /^\/adm/) {
                   5306:         $imgsrc = &lonhttpdurl($img);
                   5307:     }
                   5308:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5309: 
1.1075.2.60  raeburn  5310:     my $help=($no_inline_link?''
                   5311:               :&Apache::loncommon::top_nav_help('Help'));
                   5312: 
1.1075.2.12  raeburn  5313:     # Explicit link to get inline menu
                   5314:     my $menu= ($no_inline_link?''
                   5315:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5316: 
                   5317:     if ($dc_info) {
                   5318:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5319:     }
                   5320: 
1.1075.2.38  raeburn  5321:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5322:     unless ($public) {
                   5323:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5324:                                 undef,'LC_menubuttons_link');
                   5325:     }
                   5326: 
1.1075.2.12  raeburn  5327:     unless ($env{'form.inhibitmenu'}) {
                   5328:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5329:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5330:                        <li>$help</li>
1.1075.2.12  raeburn  5331:                        <li>$menu</li>
                   5332:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5333:     }
1.1075.2.13  raeburn  5334:     if ($env{'request.state'} eq 'construct') {
                   5335:         if (!$public){
                   5336:             if ($env{'request.state'} eq 'construct') {
                   5337:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5338:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5339:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5340:                             &Apache::lonmenu::innerregister($forcereg,
                   5341:                                                             $args->{'bread_crumbs'});
                   5342:             }
                   5343:         }
                   5344:     }
1.1075.2.21  raeburn  5345:     return $bodytag."\n".$funclist;
1.182     matthew  5346: }
                   5347: 
1.917     raeburn  5348: sub dc_courseid_toggle {
                   5349:     my ($dc_info) = @_;
1.980     raeburn  5350:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5351:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5352:            &mt('(More ...)').'</a></span>'.
                   5353:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5354: }
                   5355: 
1.330     albertel 5356: sub make_attr_string {
                   5357:     my ($register,$attr_ref) = @_;
                   5358: 
                   5359:     if ($attr_ref && !ref($attr_ref)) {
                   5360: 	die("addentries Must be a hash ref ".
                   5361: 	    join(':',caller(1))." ".
                   5362: 	    join(':',caller(0))." ");
                   5363:     }
                   5364: 
                   5365:     if ($register) {
1.339     albertel 5366: 	my ($on_load,$on_unload);
                   5367: 	foreach my $key (keys(%{$attr_ref})) {
                   5368: 	    if      (lc($key) eq 'onload') {
                   5369: 		$on_load.=$attr_ref->{$key}.';';
                   5370: 		delete($attr_ref->{$key});
                   5371: 
                   5372: 	    } elsif (lc($key) eq 'onunload') {
                   5373: 		$on_unload.=$attr_ref->{$key}.';';
                   5374: 		delete($attr_ref->{$key});
                   5375: 	    }
                   5376: 	}
1.1075.2.12  raeburn  5377:         if ($env{'environment.remote'} eq 'on') {
                   5378:             $attr_ref->{'onload'}  =
                   5379:                 &Apache::lonmenu::loadevents().  $on_load;
                   5380:             $attr_ref->{'onunload'}=
                   5381:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5382:         } else {  
                   5383: 	    $attr_ref->{'onload'}  = $on_load;
                   5384: 	    $attr_ref->{'onunload'}= $on_unload;
                   5385:         }
1.330     albertel 5386:     }
1.339     albertel 5387: 
1.330     albertel 5388:     my $attr_string;
1.1075.2.56  raeburn  5389:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5390: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5391:     }
                   5392:     return $attr_string;
                   5393: }
                   5394: 
                   5395: 
1.182     matthew  5396: ###############################################
1.251     albertel 5397: ###############################################
                   5398: 
                   5399: =pod
                   5400: 
                   5401: =item * &endbodytag()
                   5402: 
                   5403: Returns a uniform footer for LON-CAPA web pages.
                   5404: 
1.635     raeburn  5405: Inputs: 1 - optional reference to an args hash
                   5406: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5407: a 'Continue' link is not displayed if the page contains an
                   5408: internal redirect in the <head></head> section,
                   5409: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5410: 
                   5411: =cut
                   5412: 
                   5413: sub endbodytag {
1.635     raeburn  5414:     my ($args) = @_;
1.1075.2.6  raeburn  5415:     my $endbodytag;
                   5416:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5417:         $endbodytag='</body>';
                   5418:     }
1.269     albertel 5419:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5420:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5421:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5422: 	    $endbodytag=
                   5423: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5424: 	        &mt('Continue').'</a>'.
                   5425: 	        $endbodytag;
                   5426:         }
1.315     albertel 5427:     }
1.251     albertel 5428:     return $endbodytag;
                   5429: }
                   5430: 
1.352     albertel 5431: =pod
                   5432: 
                   5433: =item * &standard_css()
                   5434: 
                   5435: Returns a style sheet
                   5436: 
                   5437: Inputs: (all optional)
                   5438:             domain         -> force to color decorate a page for a specific
                   5439:                                domain
                   5440:             function       -> force usage of a specific rolish color scheme
                   5441:             bgcolor        -> override the default page bgcolor
                   5442: 
                   5443: =cut
                   5444: 
1.343     albertel 5445: sub standard_css {
1.345     albertel 5446:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5447:     $function  = &get_users_function() if (!$function);
                   5448:     my $img    = &designparm($function.'.img',   $domain);
                   5449:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5450:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5451:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5452: #second colour for later usage
1.345     albertel 5453:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5454:     my $pgbg_or_bgcolor =
                   5455: 	         $bgcolor ||
1.352     albertel 5456: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5457:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5458:     my $alink  = &designparm($function.'.alink', $domain);
                   5459:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5460:     my $link   = &designparm($function.'.link',  $domain);
                   5461: 
1.602     albertel 5462:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5463:     my $mono                 = 'monospace';
1.850     bisitz   5464:     my $data_table_head      = $sidebg;
                   5465:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5466:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5467:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5468:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5469:     my $mail_new             = '#FFBB77';
                   5470:     my $mail_new_hover       = '#DD9955';
                   5471:     my $mail_read            = '#BBBB77';
                   5472:     my $mail_read_hover      = '#999944';
                   5473:     my $mail_replied         = '#AAAA88';
                   5474:     my $mail_replied_hover   = '#888855';
                   5475:     my $mail_other           = '#99BBBB';
                   5476:     my $mail_other_hover     = '#669999';
1.391     albertel 5477:     my $table_header         = '#DDDDDD';
1.489     raeburn  5478:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5479:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5480:     my $button_hover         = '#BF2317';
1.392     albertel 5481: 
1.608     albertel 5482:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5483:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5484:                                              : '0 3px 0 4px';
1.448     albertel 5485: 
1.523     albertel 5486: 
1.343     albertel 5487:     return <<END;
1.947     droeschl 5488: 
                   5489: /* needed for iframe to allow 100% height in FF */
                   5490: body, html { 
                   5491:     margin: 0;
                   5492:     padding: 0 0.5%;
                   5493:     height: 99%; /* to avoid scrollbars */
                   5494: }
                   5495: 
1.795     www      5496: body {
1.911     bisitz   5497:   font-family: $sans;
                   5498:   line-height:130%;
                   5499:   font-size:0.83em;
                   5500:   color:$font;
1.795     www      5501: }
                   5502: 
1.959     onken    5503: a:focus,
                   5504: a:focus img {
1.795     www      5505:   color: red;
                   5506: }
1.698     harmsja  5507: 
1.911     bisitz   5508: form, .inline {
                   5509:   display: inline;
1.795     www      5510: }
1.721     harmsja  5511: 
1.795     www      5512: .LC_right {
1.911     bisitz   5513:   text-align:right;
1.795     www      5514: }
                   5515: 
                   5516: .LC_middle {
1.911     bisitz   5517:   vertical-align:middle;
1.795     www      5518: }
1.721     harmsja  5519: 
1.1075.2.38  raeburn  5520: .LC_floatleft {
                   5521:   float: left;
                   5522: }
                   5523: 
                   5524: .LC_floatright {
                   5525:   float: right;
                   5526: }
                   5527: 
1.911     bisitz   5528: .LC_400Box {
                   5529:   width:400px;
                   5530: }
1.721     harmsja  5531: 
1.947     droeschl 5532: .LC_iframecontainer {
                   5533:     width: 98%;
                   5534:     margin: 0;
                   5535:     position: fixed;
                   5536:     top: 8.5em;
                   5537:     bottom: 0;
                   5538: }
                   5539: 
                   5540: .LC_iframecontainer iframe{
                   5541:     border: none;
                   5542:     width: 100%;
                   5543:     height: 100%;
                   5544: }
                   5545: 
1.778     bisitz   5546: .LC_filename {
                   5547:   font-family: $mono;
                   5548:   white-space:pre;
1.921     bisitz   5549:   font-size: 120%;
1.778     bisitz   5550: }
                   5551: 
                   5552: .LC_fileicon {
                   5553:   border: none;
                   5554:   height: 1.3em;
                   5555:   vertical-align: text-bottom;
                   5556:   margin-right: 0.3em;
                   5557:   text-decoration:none;
                   5558: }
                   5559: 
1.1008    www      5560: .LC_setting {
                   5561:   text-decoration:underline;
                   5562: }
                   5563: 
1.350     albertel 5564: .LC_error {
                   5565:   color: red;
                   5566: }
1.795     www      5567: 
1.1075.2.15  raeburn  5568: .LC_warning {
                   5569:   color: darkorange;
                   5570: }
                   5571: 
1.457     albertel 5572: .LC_diff_removed {
1.733     bisitz   5573:   color: red;
1.394     albertel 5574: }
1.532     albertel 5575: 
                   5576: .LC_info,
1.457     albertel 5577: .LC_success,
                   5578: .LC_diff_added {
1.350     albertel 5579:   color: green;
                   5580: }
1.795     www      5581: 
1.802     bisitz   5582: div.LC_confirm_box {
                   5583:   background-color: #FAFAFA;
                   5584:   border: 1px solid $lg_border_color;
                   5585:   margin-right: 0;
                   5586:   padding: 5px;
                   5587: }
                   5588: 
                   5589: div.LC_confirm_box .LC_error img,
                   5590: div.LC_confirm_box .LC_success img {
                   5591:   vertical-align: middle;
                   5592: }
                   5593: 
1.440     albertel 5594: .LC_icon {
1.771     droeschl 5595:   border: none;
1.790     droeschl 5596:   vertical-align: middle;
1.771     droeschl 5597: }
                   5598: 
1.543     albertel 5599: .LC_docs_spacer {
                   5600:   width: 25px;
                   5601:   height: 1px;
1.771     droeschl 5602:   border: none;
1.543     albertel 5603: }
1.346     albertel 5604: 
1.532     albertel 5605: .LC_internal_info {
1.735     bisitz   5606:   color: #999999;
1.532     albertel 5607: }
                   5608: 
1.794     www      5609: .LC_discussion {
1.1050    www      5610:   background: $data_table_dark;
1.911     bisitz   5611:   border: 1px solid black;
                   5612:   margin: 2px;
1.794     www      5613: }
                   5614: 
                   5615: .LC_disc_action_left {
1.1050    www      5616:   background: $sidebg;
1.911     bisitz   5617:   text-align: left;
1.1050    www      5618:   padding: 4px;
                   5619:   margin: 2px;
1.794     www      5620: }
                   5621: 
                   5622: .LC_disc_action_right {
1.1050    www      5623:   background: $sidebg;
1.911     bisitz   5624:   text-align: right;
1.1050    www      5625:   padding: 4px;
                   5626:   margin: 2px;
1.794     www      5627: }
                   5628: 
                   5629: .LC_disc_new_item {
1.911     bisitz   5630:   background: white;
                   5631:   border: 2px solid red;
1.1050    www      5632:   margin: 4px;
                   5633:   padding: 4px;
1.794     www      5634: }
                   5635: 
                   5636: .LC_disc_old_item {
1.911     bisitz   5637:   background: white;
1.1050    www      5638:   margin: 4px;
                   5639:   padding: 4px;
1.794     www      5640: }
                   5641: 
1.458     albertel 5642: table.LC_pastsubmission {
                   5643:   border: 1px solid black;
                   5644:   margin: 2px;
                   5645: }
                   5646: 
1.924     bisitz   5647: table#LC_menubuttons {
1.345     albertel 5648:   width: 100%;
                   5649:   background: $pgbg;
1.392     albertel 5650:   border: 2px;
1.402     albertel 5651:   border-collapse: separate;
1.803     bisitz   5652:   padding: 0;
1.345     albertel 5653: }
1.392     albertel 5654: 
1.801     tempelho 5655: table#LC_title_bar a {
                   5656:   color: $fontmenu;
                   5657: }
1.836     bisitz   5658: 
1.807     droeschl 5659: table#LC_title_bar {
1.819     tempelho 5660:   clear: both;
1.836     bisitz   5661:   display: none;
1.807     droeschl 5662: }
                   5663: 
1.795     www      5664: table#LC_title_bar,
1.933     droeschl 5665: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5666: table#LC_title_bar.LC_with_remote {
1.359     albertel 5667:   width: 100%;
1.392     albertel 5668:   border-color: $pgbg;
                   5669:   border-style: solid;
                   5670:   border-width: $border;
1.379     albertel 5671:   background: $pgbg;
1.801     tempelho 5672:   color: $fontmenu;
1.392     albertel 5673:   border-collapse: collapse;
1.803     bisitz   5674:   padding: 0;
1.819     tempelho 5675:   margin: 0;
1.359     albertel 5676: }
1.795     www      5677: 
1.933     droeschl 5678: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5679:     margin: 0;
                   5680:     padding: 0;
1.933     droeschl 5681:     position: relative;
                   5682:     list-style: none;
1.913     droeschl 5683: }
1.933     droeschl 5684: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5685:     display: inline;
                   5686: }
1.933     droeschl 5687: 
                   5688: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5689:     padding: 0;
1.933     droeschl 5690:     margin: 0;
                   5691:     float: left;
1.913     droeschl 5692: }
1.933     droeschl 5693: .LC_breadcrumb_tools_tools {
                   5694:     padding: 0;
                   5695:     margin: 0;
1.913     droeschl 5696:     float: right;
                   5697: }
                   5698: 
1.359     albertel 5699: table#LC_title_bar td {
                   5700:   background: $tabbg;
                   5701: }
1.795     www      5702: 
1.911     bisitz   5703: table#LC_menubuttons img {
1.803     bisitz   5704:   border: none;
1.346     albertel 5705: }
1.795     www      5706: 
1.842     droeschl 5707: .LC_breadcrumbs_component {
1.911     bisitz   5708:   float: right;
                   5709:   margin: 0 1em;
1.357     albertel 5710: }
1.842     droeschl 5711: .LC_breadcrumbs_component img {
1.911     bisitz   5712:   vertical-align: middle;
1.777     tempelho 5713: }
1.795     www      5714: 
1.383     albertel 5715: td.LC_table_cell_checkbox {
                   5716:   text-align: center;
                   5717: }
1.795     www      5718: 
                   5719: .LC_fontsize_small {
1.911     bisitz   5720:   font-size: 70%;
1.705     tempelho 5721: }
                   5722: 
1.844     bisitz   5723: #LC_breadcrumbs {
1.911     bisitz   5724:   clear:both;
                   5725:   background: $sidebg;
                   5726:   border-bottom: 1px solid $lg_border_color;
                   5727:   line-height: 2.5em;
1.933     droeschl 5728:   overflow: hidden;
1.911     bisitz   5729:   margin: 0;
                   5730:   padding: 0;
1.995     raeburn  5731:   text-align: left;
1.819     tempelho 5732: }
1.862     bisitz   5733: 
1.1075.2.16  raeburn  5734: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5735:   clear:both;
                   5736:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5737:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5738:   margin: 0 0 10px 0;
1.966     bisitz   5739:   padding: 3px;
1.995     raeburn  5740:   text-align: left;
1.822     bisitz   5741: }
                   5742: 
1.795     www      5743: .LC_fontsize_medium {
1.911     bisitz   5744:   font-size: 85%;
1.705     tempelho 5745: }
                   5746: 
1.795     www      5747: .LC_fontsize_large {
1.911     bisitz   5748:   font-size: 120%;
1.705     tempelho 5749: }
                   5750: 
1.346     albertel 5751: .LC_menubuttons_inline_text {
                   5752:   color: $font;
1.698     harmsja  5753:   font-size: 90%;
1.701     harmsja  5754:   padding-left:3px;
1.346     albertel 5755: }
                   5756: 
1.934     droeschl 5757: .LC_menubuttons_inline_text img{
                   5758:   vertical-align: middle;
                   5759: }
                   5760: 
1.1051    www      5761: li.LC_menubuttons_inline_text img {
1.951     onken    5762:   cursor:pointer;
1.1002    droeschl 5763:   text-decoration: none;
1.951     onken    5764: }
                   5765: 
1.526     www      5766: .LC_menubuttons_link {
                   5767:   text-decoration: none;
                   5768: }
1.795     www      5769: 
1.522     albertel 5770: .LC_menubuttons_category {
1.521     www      5771:   color: $font;
1.526     www      5772:   background: $pgbg;
1.521     www      5773:   font-size: larger;
                   5774:   font-weight: bold;
                   5775: }
                   5776: 
1.346     albertel 5777: td.LC_menubuttons_text {
1.911     bisitz   5778:   color: $font;
1.346     albertel 5779: }
1.706     harmsja  5780: 
1.346     albertel 5781: .LC_current_location {
                   5782:   background: $tabbg;
                   5783: }
1.795     www      5784: 
1.938     bisitz   5785: table.LC_data_table {
1.347     albertel 5786:   border: 1px solid #000000;
1.402     albertel 5787:   border-collapse: separate;
1.426     albertel 5788:   border-spacing: 1px;
1.610     albertel 5789:   background: $pgbg;
1.347     albertel 5790: }
1.795     www      5791: 
1.422     albertel 5792: .LC_data_table_dense {
                   5793:   font-size: small;
                   5794: }
1.795     www      5795: 
1.507     raeburn  5796: table.LC_nested_outer {
                   5797:   border: 1px solid #000000;
1.589     raeburn  5798:   border-collapse: collapse;
1.803     bisitz   5799:   border-spacing: 0;
1.507     raeburn  5800:   width: 100%;
                   5801: }
1.795     www      5802: 
1.879     raeburn  5803: table.LC_innerpickbox,
1.507     raeburn  5804: table.LC_nested {
1.803     bisitz   5805:   border: none;
1.589     raeburn  5806:   border-collapse: collapse;
1.803     bisitz   5807:   border-spacing: 0;
1.507     raeburn  5808:   width: 100%;
                   5809: }
1.795     www      5810: 
1.911     bisitz   5811: table.LC_data_table tr th,
                   5812: table.LC_calendar tr th,
1.879     raeburn  5813: table.LC_prior_tries tr th,
                   5814: table.LC_innerpickbox tr th {
1.349     albertel 5815:   font-weight: bold;
                   5816:   background-color: $data_table_head;
1.801     tempelho 5817:   color:$fontmenu;
1.701     harmsja  5818:   font-size:90%;
1.347     albertel 5819: }
1.795     www      5820: 
1.879     raeburn  5821: table.LC_innerpickbox tr th,
                   5822: table.LC_innerpickbox tr td {
                   5823:   vertical-align: top;
                   5824: }
                   5825: 
1.711     raeburn  5826: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5827:   background-color: #CCCCCC;
1.711     raeburn  5828:   font-weight: bold;
                   5829:   text-align: left;
                   5830: }
1.795     www      5831: 
1.912     bisitz   5832: table.LC_data_table tr.LC_odd_row > td {
                   5833:   background-color: $data_table_light;
                   5834:   padding: 2px;
                   5835:   vertical-align: top;
                   5836: }
                   5837: 
1.809     bisitz   5838: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5839:   background-color: $data_table_light;
1.912     bisitz   5840:   vertical-align: top;
                   5841: }
                   5842: 
                   5843: table.LC_data_table tr.LC_even_row > td {
                   5844:   background-color: $data_table_dark;
1.425     albertel 5845:   padding: 2px;
1.900     bisitz   5846:   vertical-align: top;
1.347     albertel 5847: }
1.795     www      5848: 
1.809     bisitz   5849: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5850:   background-color: $data_table_dark;
1.900     bisitz   5851:   vertical-align: top;
1.347     albertel 5852: }
1.795     www      5853: 
1.425     albertel 5854: table.LC_data_table tr.LC_data_table_highlight td {
                   5855:   background-color: $data_table_darker;
                   5856: }
1.795     www      5857: 
1.639     raeburn  5858: table.LC_data_table tr td.LC_leftcol_header {
                   5859:   background-color: $data_table_head;
                   5860:   font-weight: bold;
                   5861: }
1.795     www      5862: 
1.451     albertel 5863: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5864: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5865:   font-weight: bold;
                   5866:   font-style: italic;
                   5867:   text-align: center;
                   5868:   padding: 8px;
1.347     albertel 5869: }
1.795     www      5870: 
1.1075.2.30  raeburn  5871: table.LC_data_table tr.LC_empty_row td,
                   5872: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5873:   background-color: $sidebg;
                   5874: }
                   5875: 
                   5876: table.LC_nested tr.LC_empty_row td {
                   5877:   background-color: #FFFFFF;
                   5878: }
                   5879: 
1.890     droeschl 5880: table.LC_caption {
                   5881: }
                   5882: 
1.507     raeburn  5883: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5884:   padding: 4ex
                   5885: }
1.795     www      5886: 
1.507     raeburn  5887: table.LC_nested_outer tr th {
                   5888:   font-weight: bold;
1.801     tempelho 5889:   color:$fontmenu;
1.507     raeburn  5890:   background-color: $data_table_head;
1.701     harmsja  5891:   font-size: small;
1.507     raeburn  5892:   border-bottom: 1px solid #000000;
                   5893: }
1.795     www      5894: 
1.507     raeburn  5895: table.LC_nested_outer tr td.LC_subheader {
                   5896:   background-color: $data_table_head;
                   5897:   font-weight: bold;
                   5898:   font-size: small;
                   5899:   border-bottom: 1px solid #000000;
                   5900:   text-align: right;
1.451     albertel 5901: }
1.795     www      5902: 
1.507     raeburn  5903: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5904:   background-color: #CCCCCC;
1.451     albertel 5905:   font-weight: bold;
                   5906:   font-size: small;
1.507     raeburn  5907:   text-align: center;
                   5908: }
1.795     www      5909: 
1.589     raeburn  5910: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5911: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5912:   text-align: left;
1.451     albertel 5913: }
1.795     www      5914: 
1.507     raeburn  5915: table.LC_nested td {
1.735     bisitz   5916:   background-color: #FFFFFF;
1.451     albertel 5917:   font-size: small;
1.507     raeburn  5918: }
1.795     www      5919: 
1.507     raeburn  5920: table.LC_nested_outer tr th.LC_right_item,
                   5921: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5922: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5923: table.LC_nested tr td.LC_right_item {
1.451     albertel 5924:   text-align: right;
                   5925: }
                   5926: 
1.507     raeburn  5927: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5928:   background-color: #EEEEEE;
1.451     albertel 5929: }
                   5930: 
1.473     raeburn  5931: table.LC_createuser {
                   5932: }
                   5933: 
                   5934: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5935:   font-size: small;
1.473     raeburn  5936: }
                   5937: 
                   5938: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5939:   background-color: #CCCCCC;
1.473     raeburn  5940:   font-weight: bold;
                   5941:   text-align: center;
                   5942: }
                   5943: 
1.349     albertel 5944: table.LC_calendar {
                   5945:   border: 1px solid #000000;
                   5946:   border-collapse: collapse;
1.917     raeburn  5947:   width: 98%;
1.349     albertel 5948: }
1.795     www      5949: 
1.349     albertel 5950: table.LC_calendar_pickdate {
                   5951:   font-size: xx-small;
                   5952: }
1.795     www      5953: 
1.349     albertel 5954: table.LC_calendar tr td {
                   5955:   border: 1px solid #000000;
                   5956:   vertical-align: top;
1.917     raeburn  5957:   width: 14%;
1.349     albertel 5958: }
1.795     www      5959: 
1.349     albertel 5960: table.LC_calendar tr td.LC_calendar_day_empty {
                   5961:   background-color: $data_table_dark;
                   5962: }
1.795     www      5963: 
1.779     bisitz   5964: table.LC_calendar tr td.LC_calendar_day_current {
                   5965:   background-color: $data_table_highlight;
1.777     tempelho 5966: }
1.795     www      5967: 
1.938     bisitz   5968: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5969:   background-color: $mail_new;
                   5970: }
1.795     www      5971: 
1.938     bisitz   5972: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5973:   background-color: $mail_new_hover;
                   5974: }
1.795     www      5975: 
1.938     bisitz   5976: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5977:   background-color: $mail_read;
                   5978: }
1.795     www      5979: 
1.938     bisitz   5980: /*
                   5981: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5982:   background-color: $mail_read_hover;
                   5983: }
1.938     bisitz   5984: */
1.795     www      5985: 
1.938     bisitz   5986: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5987:   background-color: $mail_replied;
                   5988: }
1.795     www      5989: 
1.938     bisitz   5990: /*
                   5991: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5992:   background-color: $mail_replied_hover;
                   5993: }
1.938     bisitz   5994: */
1.795     www      5995: 
1.938     bisitz   5996: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5997:   background-color: $mail_other;
                   5998: }
1.795     www      5999: 
1.938     bisitz   6000: /*
                   6001: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6002:   background-color: $mail_other_hover;
                   6003: }
1.938     bisitz   6004: */
1.494     raeburn  6005: 
1.777     tempelho 6006: table.LC_data_table tr > td.LC_browser_file,
                   6007: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6008:   background: #AAEE77;
1.389     albertel 6009: }
1.795     www      6010: 
1.777     tempelho 6011: table.LC_data_table tr > td.LC_browser_file_locked,
                   6012: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6013:   background: #FFAA99;
1.387     albertel 6014: }
1.795     www      6015: 
1.777     tempelho 6016: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6017:   background: #888888;
1.779     bisitz   6018: }
1.795     www      6019: 
1.777     tempelho 6020: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6021: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6022:   background: #F8F866;
1.777     tempelho 6023: }
1.795     www      6024: 
1.696     bisitz   6025: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6026:   background: #E0E8FF;
1.387     albertel 6027: }
1.696     bisitz   6028: 
1.707     bisitz   6029: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6030:   /* background: #77FF77; */
1.707     bisitz   6031: }
1.795     www      6032: 
1.707     bisitz   6033: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6034:   border-right: 8px solid #FFFF77;
1.707     bisitz   6035: }
1.795     www      6036: 
1.707     bisitz   6037: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6038:   border-right: 8px solid #FFAA77;
1.707     bisitz   6039: }
1.795     www      6040: 
1.707     bisitz   6041: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6042:   border-right: 8px solid #FF7777;
1.707     bisitz   6043: }
1.795     www      6044: 
1.707     bisitz   6045: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6046:   border-right: 8px solid #AAFF77;
1.707     bisitz   6047: }
1.795     www      6048: 
1.707     bisitz   6049: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6050:   border-right: 8px solid #11CC55;
1.707     bisitz   6051: }
                   6052: 
1.388     albertel 6053: span.LC_current_location {
1.701     harmsja  6054:   font-size:larger;
1.388     albertel 6055:   background: $pgbg;
                   6056: }
1.387     albertel 6057: 
1.1029    www      6058: span.LC_current_nav_location {
                   6059:   font-weight:bold;
                   6060:   background: $sidebg;
                   6061: }
                   6062: 
1.395     albertel 6063: span.LC_parm_menu_item {
                   6064:   font-size: larger;
                   6065: }
1.795     www      6066: 
1.395     albertel 6067: span.LC_parm_scope_all {
                   6068:   color: red;
                   6069: }
1.795     www      6070: 
1.395     albertel 6071: span.LC_parm_scope_folder {
                   6072:   color: green;
                   6073: }
1.795     www      6074: 
1.395     albertel 6075: span.LC_parm_scope_resource {
                   6076:   color: orange;
                   6077: }
1.795     www      6078: 
1.395     albertel 6079: span.LC_parm_part {
                   6080:   color: blue;
                   6081: }
1.795     www      6082: 
1.911     bisitz   6083: span.LC_parm_folder,
                   6084: span.LC_parm_symb {
1.395     albertel 6085:   font-size: x-small;
                   6086:   font-family: $mono;
                   6087:   color: #AAAAAA;
                   6088: }
                   6089: 
1.977     bisitz   6090: ul.LC_parm_parmlist li {
                   6091:   display: inline-block;
                   6092:   padding: 0.3em 0.8em;
                   6093:   vertical-align: top;
                   6094:   width: 150px;
                   6095:   border-top:1px solid $lg_border_color;
                   6096: }
                   6097: 
1.795     www      6098: td.LC_parm_overview_level_menu,
                   6099: td.LC_parm_overview_map_menu,
                   6100: td.LC_parm_overview_parm_selectors,
                   6101: td.LC_parm_overview_restrictions  {
1.396     albertel 6102:   border: 1px solid black;
                   6103:   border-collapse: collapse;
                   6104: }
1.795     www      6105: 
1.396     albertel 6106: table.LC_parm_overview_restrictions td {
                   6107:   border-width: 1px 4px 1px 4px;
                   6108:   border-style: solid;
                   6109:   border-color: $pgbg;
                   6110:   text-align: center;
                   6111: }
1.795     www      6112: 
1.396     albertel 6113: table.LC_parm_overview_restrictions th {
                   6114:   background: $tabbg;
                   6115:   border-width: 1px 4px 1px 4px;
                   6116:   border-style: solid;
                   6117:   border-color: $pgbg;
                   6118: }
1.795     www      6119: 
1.398     albertel 6120: table#LC_helpmenu {
1.803     bisitz   6121:   border: none;
1.398     albertel 6122:   height: 55px;
1.803     bisitz   6123:   border-spacing: 0;
1.398     albertel 6124: }
                   6125: 
                   6126: table#LC_helpmenu fieldset legend {
                   6127:   font-size: larger;
                   6128: }
1.795     www      6129: 
1.397     albertel 6130: table#LC_helpmenu_links {
                   6131:   width: 100%;
                   6132:   border: 1px solid black;
                   6133:   background: $pgbg;
1.803     bisitz   6134:   padding: 0;
1.397     albertel 6135:   border-spacing: 1px;
                   6136: }
1.795     www      6137: 
1.397     albertel 6138: table#LC_helpmenu_links tr td {
                   6139:   padding: 1px;
                   6140:   background: $tabbg;
1.399     albertel 6141:   text-align: center;
                   6142:   font-weight: bold;
1.397     albertel 6143: }
1.396     albertel 6144: 
1.795     www      6145: table#LC_helpmenu_links a:link,
                   6146: table#LC_helpmenu_links a:visited,
1.397     albertel 6147: table#LC_helpmenu_links a:active {
                   6148:   text-decoration: none;
                   6149:   color: $font;
                   6150: }
1.795     www      6151: 
1.397     albertel 6152: table#LC_helpmenu_links a:hover {
                   6153:   text-decoration: underline;
                   6154:   color: $vlink;
                   6155: }
1.396     albertel 6156: 
1.417     albertel 6157: .LC_chrt_popup_exists {
                   6158:   border: 1px solid #339933;
                   6159:   margin: -1px;
                   6160: }
1.795     www      6161: 
1.417     albertel 6162: .LC_chrt_popup_up {
                   6163:   border: 1px solid yellow;
                   6164:   margin: -1px;
                   6165: }
1.795     www      6166: 
1.417     albertel 6167: .LC_chrt_popup {
                   6168:   border: 1px solid #8888FF;
                   6169:   background: #CCCCFF;
                   6170: }
1.795     www      6171: 
1.421     albertel 6172: table.LC_pick_box {
                   6173:   border-collapse: separate;
                   6174:   background: white;
                   6175:   border: 1px solid black;
                   6176:   border-spacing: 1px;
                   6177: }
1.795     www      6178: 
1.421     albertel 6179: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6180:   background: $sidebg;
1.421     albertel 6181:   font-weight: bold;
1.900     bisitz   6182:   text-align: left;
1.740     bisitz   6183:   vertical-align: top;
1.421     albertel 6184:   width: 184px;
                   6185:   padding: 8px;
                   6186: }
1.795     www      6187: 
1.579     raeburn  6188: table.LC_pick_box td.LC_pick_box_value {
                   6189:   text-align: left;
                   6190:   padding: 8px;
                   6191: }
1.795     www      6192: 
1.579     raeburn  6193: table.LC_pick_box td.LC_pick_box_select {
                   6194:   text-align: left;
                   6195:   padding: 8px;
                   6196: }
1.795     www      6197: 
1.424     albertel 6198: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6199:   padding: 0;
1.421     albertel 6200:   height: 1px;
                   6201:   background: black;
                   6202: }
1.795     www      6203: 
1.421     albertel 6204: table.LC_pick_box td.LC_pick_box_submit {
                   6205:   text-align: right;
                   6206: }
1.795     www      6207: 
1.579     raeburn  6208: table.LC_pick_box td.LC_evenrow_value {
                   6209:   text-align: left;
                   6210:   padding: 8px;
                   6211:   background-color: $data_table_light;
                   6212: }
1.795     www      6213: 
1.579     raeburn  6214: table.LC_pick_box td.LC_oddrow_value {
                   6215:   text-align: left;
                   6216:   padding: 8px;
                   6217:   background-color: $data_table_light;
                   6218: }
1.795     www      6219: 
1.579     raeburn  6220: span.LC_helpform_receipt_cat {
                   6221:   font-weight: bold;
                   6222: }
1.795     www      6223: 
1.424     albertel 6224: table.LC_group_priv_box {
                   6225:   background: white;
                   6226:   border: 1px solid black;
                   6227:   border-spacing: 1px;
                   6228: }
1.795     www      6229: 
1.424     albertel 6230: table.LC_group_priv_box td.LC_pick_box_title {
                   6231:   background: $tabbg;
                   6232:   font-weight: bold;
                   6233:   text-align: right;
                   6234:   width: 184px;
                   6235: }
1.795     www      6236: 
1.424     albertel 6237: table.LC_group_priv_box td.LC_groups_fixed {
                   6238:   background: $data_table_light;
                   6239:   text-align: center;
                   6240: }
1.795     www      6241: 
1.424     albertel 6242: table.LC_group_priv_box td.LC_groups_optional {
                   6243:   background: $data_table_dark;
                   6244:   text-align: center;
                   6245: }
1.795     www      6246: 
1.424     albertel 6247: table.LC_group_priv_box td.LC_groups_functionality {
                   6248:   background: $data_table_darker;
                   6249:   text-align: center;
                   6250:   font-weight: bold;
                   6251: }
1.795     www      6252: 
1.424     albertel 6253: table.LC_group_priv td {
                   6254:   text-align: left;
1.803     bisitz   6255:   padding: 0;
1.424     albertel 6256: }
                   6257: 
                   6258: .LC_navbuttons {
                   6259:   margin: 2ex 0ex 2ex 0ex;
                   6260: }
1.795     www      6261: 
1.423     albertel 6262: .LC_topic_bar {
                   6263:   font-weight: bold;
                   6264:   background: $tabbg;
1.918     wenzelju 6265:   margin: 1em 0em 1em 2em;
1.805     bisitz   6266:   padding: 3px;
1.918     wenzelju 6267:   font-size: 1.2em;
1.423     albertel 6268: }
1.795     www      6269: 
1.423     albertel 6270: .LC_topic_bar span {
1.918     wenzelju 6271:   left: 0.5em;
                   6272:   position: absolute;
1.423     albertel 6273:   vertical-align: middle;
1.918     wenzelju 6274:   font-size: 1.2em;
1.423     albertel 6275: }
1.795     www      6276: 
1.423     albertel 6277: table.LC_course_group_status {
                   6278:   margin: 20px;
                   6279: }
1.795     www      6280: 
1.423     albertel 6281: table.LC_status_selector td {
                   6282:   vertical-align: top;
                   6283:   text-align: center;
1.424     albertel 6284:   padding: 4px;
                   6285: }
1.795     www      6286: 
1.599     albertel 6287: div.LC_feedback_link {
1.616     albertel 6288:   clear: both;
1.829     kalberla 6289:   background: $sidebg;
1.779     bisitz   6290:   width: 100%;
1.829     kalberla 6291:   padding-bottom: 10px;
                   6292:   border: 1px $tabbg solid;
1.833     kalberla 6293:   height: 22px;
                   6294:   line-height: 22px;
                   6295:   padding-top: 5px;
                   6296: }
                   6297: 
                   6298: div.LC_feedback_link img {
                   6299:   height: 22px;
1.867     kalberla 6300:   vertical-align:middle;
1.829     kalberla 6301: }
                   6302: 
1.911     bisitz   6303: div.LC_feedback_link a {
1.829     kalberla 6304:   text-decoration: none;
1.489     raeburn  6305: }
1.795     www      6306: 
1.867     kalberla 6307: div.LC_comblock {
1.911     bisitz   6308:   display:inline;
1.867     kalberla 6309:   color:$font;
                   6310:   font-size:90%;
                   6311: }
                   6312: 
                   6313: div.LC_feedback_link div.LC_comblock {
                   6314:   padding-left:5px;
                   6315: }
                   6316: 
                   6317: div.LC_feedback_link div.LC_comblock a {
                   6318:   color:$font;
                   6319: }
                   6320: 
1.489     raeburn  6321: span.LC_feedback_link {
1.858     bisitz   6322:   /* background: $feedback_link_bg; */
1.599     albertel 6323:   font-size: larger;
                   6324: }
1.795     www      6325: 
1.599     albertel 6326: span.LC_message_link {
1.858     bisitz   6327:   /* background: $feedback_link_bg; */
1.599     albertel 6328:   font-size: larger;
                   6329:   position: absolute;
                   6330:   right: 1em;
1.489     raeburn  6331: }
1.421     albertel 6332: 
1.515     albertel 6333: table.LC_prior_tries {
1.524     albertel 6334:   border: 1px solid #000000;
                   6335:   border-collapse: separate;
                   6336:   border-spacing: 1px;
1.515     albertel 6337: }
1.523     albertel 6338: 
1.515     albertel 6339: table.LC_prior_tries td {
1.524     albertel 6340:   padding: 2px;
1.515     albertel 6341: }
1.523     albertel 6342: 
                   6343: .LC_answer_correct {
1.795     www      6344:   background: lightgreen;
                   6345:   color: darkgreen;
                   6346:   padding: 6px;
1.523     albertel 6347: }
1.795     www      6348: 
1.523     albertel 6349: .LC_answer_charged_try {
1.797     www      6350:   background: #FFAAAA;
1.795     www      6351:   color: darkred;
                   6352:   padding: 6px;
1.523     albertel 6353: }
1.795     www      6354: 
1.779     bisitz   6355: .LC_answer_not_charged_try,
1.523     albertel 6356: .LC_answer_no_grade,
                   6357: .LC_answer_late {
1.795     www      6358:   background: lightyellow;
1.523     albertel 6359:   color: black;
1.795     www      6360:   padding: 6px;
1.523     albertel 6361: }
1.795     www      6362: 
1.523     albertel 6363: .LC_answer_previous {
1.795     www      6364:   background: lightblue;
                   6365:   color: darkblue;
                   6366:   padding: 6px;
1.523     albertel 6367: }
1.795     www      6368: 
1.779     bisitz   6369: .LC_answer_no_message {
1.777     tempelho 6370:   background: #FFFFFF;
                   6371:   color: black;
1.795     www      6372:   padding: 6px;
1.779     bisitz   6373: }
1.795     www      6374: 
1.779     bisitz   6375: .LC_answer_unknown {
                   6376:   background: orange;
                   6377:   color: black;
1.795     www      6378:   padding: 6px;
1.777     tempelho 6379: }
1.795     www      6380: 
1.529     albertel 6381: span.LC_prior_numerical,
                   6382: span.LC_prior_string,
                   6383: span.LC_prior_custom,
                   6384: span.LC_prior_reaction,
                   6385: span.LC_prior_math {
1.925     bisitz   6386:   font-family: $mono;
1.523     albertel 6387:   white-space: pre;
                   6388: }
                   6389: 
1.525     albertel 6390: span.LC_prior_string {
1.925     bisitz   6391:   font-family: $mono;
1.525     albertel 6392:   white-space: pre;
                   6393: }
                   6394: 
1.523     albertel 6395: table.LC_prior_option {
                   6396:   width: 100%;
                   6397:   border-collapse: collapse;
                   6398: }
1.795     www      6399: 
1.911     bisitz   6400: table.LC_prior_rank,
1.795     www      6401: table.LC_prior_match {
1.528     albertel 6402:   border-collapse: collapse;
                   6403: }
1.795     www      6404: 
1.528     albertel 6405: table.LC_prior_option tr td,
                   6406: table.LC_prior_rank tr td,
                   6407: table.LC_prior_match tr td {
1.524     albertel 6408:   border: 1px solid #000000;
1.515     albertel 6409: }
                   6410: 
1.855     bisitz   6411: .LC_nobreak {
1.544     albertel 6412:   white-space: nowrap;
1.519     raeburn  6413: }
                   6414: 
1.576     raeburn  6415: span.LC_cusr_emph {
                   6416:   font-style: italic;
                   6417: }
                   6418: 
1.633     raeburn  6419: span.LC_cusr_subheading {
                   6420:   font-weight: normal;
                   6421:   font-size: 85%;
                   6422: }
                   6423: 
1.861     bisitz   6424: div.LC_docs_entry_move {
1.859     bisitz   6425:   border: 1px solid #BBBBBB;
1.545     albertel 6426:   background: #DDDDDD;
1.861     bisitz   6427:   width: 22px;
1.859     bisitz   6428:   padding: 1px;
                   6429:   margin: 0;
1.545     albertel 6430: }
                   6431: 
1.861     bisitz   6432: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6433: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6434:   font-size: x-small;
                   6435: }
1.795     www      6436: 
1.861     bisitz   6437: .LC_docs_entry_parameter {
                   6438:   white-space: nowrap;
                   6439: }
                   6440: 
1.544     albertel 6441: .LC_docs_copy {
1.545     albertel 6442:   color: #000099;
1.544     albertel 6443: }
1.795     www      6444: 
1.544     albertel 6445: .LC_docs_cut {
1.545     albertel 6446:   color: #550044;
1.544     albertel 6447: }
1.795     www      6448: 
1.544     albertel 6449: .LC_docs_rename {
1.545     albertel 6450:   color: #009900;
1.544     albertel 6451: }
1.795     www      6452: 
1.544     albertel 6453: .LC_docs_remove {
1.545     albertel 6454:   color: #990000;
                   6455: }
                   6456: 
1.547     albertel 6457: .LC_docs_reinit_warn,
                   6458: .LC_docs_ext_edit {
                   6459:   font-size: x-small;
                   6460: }
                   6461: 
1.545     albertel 6462: table.LC_docs_adddocs td,
                   6463: table.LC_docs_adddocs th {
                   6464:   border: 1px solid #BBBBBB;
                   6465:   padding: 4px;
                   6466:   background: #DDDDDD;
1.543     albertel 6467: }
                   6468: 
1.584     albertel 6469: table.LC_sty_begin {
                   6470:   background: #BBFFBB;
                   6471: }
1.795     www      6472: 
1.584     albertel 6473: table.LC_sty_end {
                   6474:   background: #FFBBBB;
                   6475: }
                   6476: 
1.589     raeburn  6477: table.LC_double_column {
1.803     bisitz   6478:   border-width: 0;
1.589     raeburn  6479:   border-collapse: collapse;
                   6480:   width: 100%;
                   6481:   padding: 2px;
                   6482: }
                   6483: 
                   6484: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6485:   top: 2px;
1.589     raeburn  6486:   left: 2px;
                   6487:   width: 47%;
                   6488:   vertical-align: top;
                   6489: }
                   6490: 
                   6491: table.LC_double_column tr td.LC_right_col {
                   6492:   top: 2px;
1.779     bisitz   6493:   right: 2px;
1.589     raeburn  6494:   width: 47%;
                   6495:   vertical-align: top;
                   6496: }
                   6497: 
1.591     raeburn  6498: div.LC_left_float {
                   6499:   float: left;
                   6500:   padding-right: 5%;
1.597     albertel 6501:   padding-bottom: 4px;
1.591     raeburn  6502: }
                   6503: 
                   6504: div.LC_clear_float_header {
1.597     albertel 6505:   padding-bottom: 2px;
1.591     raeburn  6506: }
                   6507: 
                   6508: div.LC_clear_float_footer {
1.597     albertel 6509:   padding-top: 10px;
1.591     raeburn  6510:   clear: both;
                   6511: }
                   6512: 
1.597     albertel 6513: div.LC_grade_show_user {
1.941     bisitz   6514: /*  border-left: 5px solid $sidebg; */
                   6515:   border-top: 5px solid #000000;
                   6516:   margin: 50px 0 0 0;
1.936     bisitz   6517:   padding: 15px 0 5px 10px;
1.597     albertel 6518: }
1.795     www      6519: 
1.936     bisitz   6520: div.LC_grade_show_user_odd_row {
1.941     bisitz   6521: /*  border-left: 5px solid #000000; */
                   6522: }
                   6523: 
                   6524: div.LC_grade_show_user div.LC_Box {
                   6525:   margin-right: 50px;
1.597     albertel 6526: }
                   6527: 
                   6528: div.LC_grade_submissions,
                   6529: div.LC_grade_message_center,
1.936     bisitz   6530: div.LC_grade_info_links {
1.597     albertel 6531:   margin: 5px;
                   6532:   width: 99%;
                   6533:   background: #FFFFFF;
                   6534: }
1.795     www      6535: 
1.597     albertel 6536: div.LC_grade_submissions_header,
1.936     bisitz   6537: div.LC_grade_message_center_header {
1.705     tempelho 6538:   font-weight: bold;
                   6539:   font-size: large;
1.597     albertel 6540: }
1.795     www      6541: 
1.597     albertel 6542: div.LC_grade_submissions_body,
1.936     bisitz   6543: div.LC_grade_message_center_body {
1.597     albertel 6544:   border: 1px solid black;
                   6545:   width: 99%;
                   6546:   background: #FFFFFF;
                   6547: }
1.795     www      6548: 
1.613     albertel 6549: table.LC_scantron_action {
                   6550:   width: 100%;
                   6551: }
1.795     www      6552: 
1.613     albertel 6553: table.LC_scantron_action tr th {
1.698     harmsja  6554:   font-weight:bold;
                   6555:   font-style:normal;
1.613     albertel 6556: }
1.795     www      6557: 
1.779     bisitz   6558: .LC_edit_problem_header,
1.614     albertel 6559: div.LC_edit_problem_footer {
1.705     tempelho 6560:   font-weight: normal;
                   6561:   font-size:  medium;
1.602     albertel 6562:   margin: 2px;
1.1060    bisitz   6563:   background-color: $sidebg;
1.600     albertel 6564: }
1.795     www      6565: 
1.600     albertel 6566: div.LC_edit_problem_header,
1.602     albertel 6567: div.LC_edit_problem_header div,
1.614     albertel 6568: div.LC_edit_problem_footer,
                   6569: div.LC_edit_problem_footer div,
1.602     albertel 6570: div.LC_edit_problem_editxml_header,
                   6571: div.LC_edit_problem_editxml_header div {
1.600     albertel 6572:   margin-top: 5px;
                   6573: }
1.795     www      6574: 
1.600     albertel 6575: div.LC_edit_problem_header_title {
1.705     tempelho 6576:   font-weight: bold;
                   6577:   font-size: larger;
1.602     albertel 6578:   background: $tabbg;
                   6579:   padding: 3px;
1.1060    bisitz   6580:   margin: 0 0 5px 0;
1.602     albertel 6581: }
1.795     www      6582: 
1.602     albertel 6583: table.LC_edit_problem_header_title {
                   6584:   width: 100%;
1.600     albertel 6585:   background: $tabbg;
1.602     albertel 6586: }
                   6587: 
                   6588: div.LC_edit_problem_discards {
                   6589:   float: left;
                   6590:   padding-bottom: 5px;
                   6591: }
1.795     www      6592: 
1.602     albertel 6593: div.LC_edit_problem_saves {
                   6594:   float: right;
                   6595:   padding-bottom: 5px;
1.600     albertel 6596: }
1.795     www      6597: 
1.1075.2.34  raeburn  6598: .LC_edit_opt {
                   6599:   padding-left: 1em;
                   6600:   white-space: nowrap;
                   6601: }
                   6602: 
1.1075.2.57  raeburn  6603: .LC_edit_problem_latexhelper{
                   6604:     text-align: right;
                   6605: }
                   6606: 
                   6607: #LC_edit_problem_colorful div{
                   6608:     margin-left: 40px;
                   6609: }
                   6610: 
1.911     bisitz   6611: img.stift {
1.803     bisitz   6612:   border-width: 0;
                   6613:   vertical-align: middle;
1.677     riegler  6614: }
1.680     riegler  6615: 
1.923     bisitz   6616: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6617:   vertical-align: top;
1.777     tempelho 6618: }
1.795     www      6619: 
1.716     raeburn  6620: div.LC_createcourse {
1.911     bisitz   6621:   margin: 10px 10px 10px 10px;
1.716     raeburn  6622: }
                   6623: 
1.917     raeburn  6624: .LC_dccid {
1.1075.2.38  raeburn  6625:   float: right;
1.917     raeburn  6626:   margin: 0.2em 0 0 0;
                   6627:   padding: 0;
                   6628:   font-size: 90%;
                   6629:   display:none;
                   6630: }
                   6631: 
1.897     wenzelju 6632: ol.LC_primary_menu a:hover,
1.721     harmsja  6633: ol#LC_MenuBreadcrumbs a:hover,
                   6634: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6635: ul#LC_secondary_menu a:hover,
1.721     harmsja  6636: .LC_FormSectionClearButton input:hover
1.795     www      6637: ul.LC_TabContent   li:hover a {
1.952     onken    6638:   color:$button_hover;
1.911     bisitz   6639:   text-decoration:none;
1.693     droeschl 6640: }
                   6641: 
1.779     bisitz   6642: h1 {
1.911     bisitz   6643:   padding: 0;
                   6644:   line-height:130%;
1.693     droeschl 6645: }
1.698     harmsja  6646: 
1.911     bisitz   6647: h2,
                   6648: h3,
                   6649: h4,
                   6650: h5,
                   6651: h6 {
                   6652:   margin: 5px 0 5px 0;
                   6653:   padding: 0;
                   6654:   line-height:130%;
1.693     droeschl 6655: }
1.795     www      6656: 
                   6657: .LC_hcell {
1.911     bisitz   6658:   padding:3px 15px 3px 15px;
                   6659:   margin: 0;
                   6660:   background-color:$tabbg;
                   6661:   color:$fontmenu;
                   6662:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6663: }
1.795     www      6664: 
1.840     bisitz   6665: .LC_Box > .LC_hcell {
1.911     bisitz   6666:   margin: 0 -10px 10px -10px;
1.835     bisitz   6667: }
                   6668: 
1.721     harmsja  6669: .LC_noBorder {
1.911     bisitz   6670:   border: 0;
1.698     harmsja  6671: }
1.693     droeschl 6672: 
1.721     harmsja  6673: .LC_FormSectionClearButton input {
1.911     bisitz   6674:   background-color:transparent;
                   6675:   border: none;
                   6676:   cursor:pointer;
                   6677:   text-decoration:underline;
1.693     droeschl 6678: }
1.763     bisitz   6679: 
                   6680: .LC_help_open_topic {
1.911     bisitz   6681:   color: #FFFFFF;
                   6682:   background-color: #EEEEFF;
                   6683:   margin: 1px;
                   6684:   padding: 4px;
                   6685:   border: 1px solid #000033;
                   6686:   white-space: nowrap;
                   6687:   /* vertical-align: middle; */
1.759     neumanie 6688: }
1.693     droeschl 6689: 
1.911     bisitz   6690: dl,
                   6691: ul,
                   6692: div,
                   6693: fieldset {
                   6694:   margin: 10px 10px 10px 0;
                   6695:   /* overflow: hidden; */
1.693     droeschl 6696: }
1.795     www      6697: 
1.1075.2.90  raeburn  6698: article.geogebraweb div {
                   6699:     margin: 0;
                   6700: }
                   6701: 
1.838     bisitz   6702: fieldset > legend {
1.911     bisitz   6703:   font-weight: bold;
                   6704:   padding: 0 5px 0 5px;
1.838     bisitz   6705: }
                   6706: 
1.813     bisitz   6707: #LC_nav_bar {
1.911     bisitz   6708:   float: left;
1.995     raeburn  6709:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6710:   margin: 0 0 2px 0;
1.807     droeschl 6711: }
                   6712: 
1.916     droeschl 6713: #LC_realm {
                   6714:   margin: 0.2em 0 0 0;
                   6715:   padding: 0;
                   6716:   font-weight: bold;
                   6717:   text-align: center;
1.995     raeburn  6718:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6719: }
                   6720: 
1.911     bisitz   6721: #LC_nav_bar em {
                   6722:   font-weight: bold;
                   6723:   font-style: normal;
1.807     droeschl 6724: }
                   6725: 
1.897     wenzelju 6726: ol.LC_primary_menu {
1.934     droeschl 6727:   margin: 0;
1.1075.2.2  raeburn  6728:   padding: 0;
1.995     raeburn  6729:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6730: }
                   6731: 
1.852     droeschl 6732: ol#LC_PathBreadcrumbs {
1.911     bisitz   6733:   margin: 0;
1.693     droeschl 6734: }
                   6735: 
1.897     wenzelju 6736: ol.LC_primary_menu li {
1.1075.2.2  raeburn  6737:   color: RGB(80, 80, 80);
                   6738:   vertical-align: middle;
                   6739:   text-align: left;
                   6740:   list-style: none;
                   6741:   float: left;
                   6742: }
                   6743: 
                   6744: ol.LC_primary_menu li a {
                   6745:   display: block;
                   6746:   margin: 0;
                   6747:   padding: 0 5px 0 10px;
                   6748:   text-decoration: none;
                   6749: }
                   6750: 
                   6751: ol.LC_primary_menu li ul {
                   6752:   display: none;
                   6753:   width: 10em;
                   6754:   background-color: $data_table_light;
                   6755: }
                   6756: 
                   6757: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6758:   display: block;
                   6759:   position: absolute;
                   6760:   margin: 0;
                   6761:   padding: 0;
1.1075.2.5  raeburn  6762:   z-index: 2;
1.1075.2.2  raeburn  6763: }
                   6764: 
                   6765: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6766:   font-size: 90%;
1.911     bisitz   6767:   vertical-align: top;
1.1075.2.2  raeburn  6768:   float: none;
1.1075.2.5  raeburn  6769:   border-left: 1px solid black;
                   6770:   border-right: 1px solid black;
1.1075.2.2  raeburn  6771: }
                   6772: 
                   6773: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1075.2.5  raeburn  6774:   background-color:$data_table_light;
1.1075.2.2  raeburn  6775: }
                   6776: 
                   6777: ol.LC_primary_menu li li a:hover {
                   6778:    color:$button_hover;
                   6779:    background-color:$data_table_dark;
1.693     droeschl 6780: }
                   6781: 
1.897     wenzelju 6782: ol.LC_primary_menu li img {
1.911     bisitz   6783:   vertical-align: bottom;
1.934     droeschl 6784:   height: 1.1em;
1.1075.2.3  raeburn  6785:   margin: 0.2em 0 0 0;
1.693     droeschl 6786: }
                   6787: 
1.897     wenzelju 6788: ol.LC_primary_menu a {
1.911     bisitz   6789:   color: RGB(80, 80, 80);
                   6790:   text-decoration: none;
1.693     droeschl 6791: }
1.795     www      6792: 
1.949     droeschl 6793: ol.LC_primary_menu a.LC_new_message {
                   6794:   font-weight:bold;
                   6795:   color: darkred;
                   6796: }
                   6797: 
1.975     raeburn  6798: ol.LC_docs_parameters {
                   6799:   margin-left: 0;
                   6800:   padding: 0;
                   6801:   list-style: none;
                   6802: }
                   6803: 
                   6804: ol.LC_docs_parameters li {
                   6805:   margin: 0;
                   6806:   padding-right: 20px;
                   6807:   display: inline;
                   6808: }
                   6809: 
1.976     raeburn  6810: ol.LC_docs_parameters li:before {
                   6811:   content: "\\002022 \\0020";
                   6812: }
                   6813: 
                   6814: li.LC_docs_parameters_title {
                   6815:   font-weight: bold;
                   6816: }
                   6817: 
                   6818: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6819:   content: "";
                   6820: }
                   6821: 
1.897     wenzelju 6822: ul#LC_secondary_menu {
1.1075.2.23  raeburn  6823:   clear: right;
1.911     bisitz   6824:   color: $fontmenu;
                   6825:   background: $tabbg;
                   6826:   list-style: none;
                   6827:   padding: 0;
                   6828:   margin: 0;
                   6829:   width: 100%;
1.995     raeburn  6830:   text-align: left;
1.1075.2.4  raeburn  6831:   float: left;
1.808     droeschl 6832: }
                   6833: 
1.897     wenzelju 6834: ul#LC_secondary_menu li {
1.911     bisitz   6835:   font-weight: bold;
                   6836:   line-height: 1.8em;
                   6837:   border-right: 1px solid black;
                   6838:   vertical-align: middle;
1.1075.2.4  raeburn  6839:   float: left;
                   6840: }
                   6841: 
                   6842: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6843:   background-color: $data_table_light;
                   6844: }
                   6845: 
                   6846: ul#LC_secondary_menu li a {
                   6847:   padding: 0 0.8em;
                   6848: }
                   6849: 
                   6850: ul#LC_secondary_menu li ul {
                   6851:   display: none;
                   6852: }
                   6853: 
                   6854: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6855:   display: block;
                   6856:   position: absolute;
                   6857:   margin: 0;
                   6858:   padding: 0;
                   6859:   list-style:none;
                   6860:   float: none;
                   6861:   background-color: $data_table_light;
1.1075.2.5  raeburn  6862:   z-index: 2;
1.1075.2.10  raeburn  6863:   margin-left: -1px;
1.1075.2.4  raeburn  6864: }
                   6865: 
                   6866: ul#LC_secondary_menu li ul li {
                   6867:   font-size: 90%;
                   6868:   vertical-align: top;
                   6869:   border-left: 1px solid black;
                   6870:   border-right: 1px solid black;
1.1075.2.33  raeburn  6871:   background-color: $data_table_light;
1.1075.2.4  raeburn  6872:   list-style:none;
                   6873:   float: none;
                   6874: }
                   6875: 
                   6876: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6877:   background-color: $data_table_dark;
1.807     droeschl 6878: }
                   6879: 
1.847     tempelho 6880: ul.LC_TabContent {
1.911     bisitz   6881:   display:block;
                   6882:   background: $sidebg;
                   6883:   border-bottom: solid 1px $lg_border_color;
                   6884:   list-style:none;
1.1020    raeburn  6885:   margin: -1px -10px 0 -10px;
1.911     bisitz   6886:   padding: 0;
1.693     droeschl 6887: }
                   6888: 
1.795     www      6889: ul.LC_TabContent li,
                   6890: ul.LC_TabContentBigger li {
1.911     bisitz   6891:   float:left;
1.741     harmsja  6892: }
1.795     www      6893: 
1.897     wenzelju 6894: ul#LC_secondary_menu li a {
1.911     bisitz   6895:   color: $fontmenu;
                   6896:   text-decoration: none;
1.693     droeschl 6897: }
1.795     www      6898: 
1.721     harmsja  6899: ul.LC_TabContent {
1.952     onken    6900:   min-height:20px;
1.721     harmsja  6901: }
1.795     www      6902: 
                   6903: ul.LC_TabContent li {
1.911     bisitz   6904:   vertical-align:middle;
1.959     onken    6905:   padding: 0 16px 0 10px;
1.911     bisitz   6906:   background-color:$tabbg;
                   6907:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6908:   border-left: solid 1px $font;
1.721     harmsja  6909: }
1.795     www      6910: 
1.847     tempelho 6911: ul.LC_TabContent .right {
1.911     bisitz   6912:   float:right;
1.847     tempelho 6913: }
                   6914: 
1.911     bisitz   6915: ul.LC_TabContent li a,
                   6916: ul.LC_TabContent li {
                   6917:   color:rgb(47,47,47);
                   6918:   text-decoration:none;
                   6919:   font-size:95%;
                   6920:   font-weight:bold;
1.952     onken    6921:   min-height:20px;
                   6922: }
                   6923: 
1.959     onken    6924: ul.LC_TabContent li a:hover,
                   6925: ul.LC_TabContent li a:focus {
1.952     onken    6926:   color: $button_hover;
1.959     onken    6927:   background:none;
                   6928:   outline:none;
1.952     onken    6929: }
                   6930: 
                   6931: ul.LC_TabContent li:hover {
                   6932:   color: $button_hover;
                   6933:   cursor:pointer;
1.721     harmsja  6934: }
1.795     www      6935: 
1.911     bisitz   6936: ul.LC_TabContent li.active {
1.952     onken    6937:   color: $font;
1.911     bisitz   6938:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6939:   border-bottom:solid 1px #FFFFFF;
                   6940:   cursor: default;
1.744     ehlerst  6941: }
1.795     www      6942: 
1.959     onken    6943: ul.LC_TabContent li.active a {
                   6944:   color:$font;
                   6945:   background:#FFFFFF;
                   6946:   outline: none;
                   6947: }
1.1047    raeburn  6948: 
                   6949: ul.LC_TabContent li.goback {
                   6950:   float: left;
                   6951:   border-left: none;
                   6952: }
                   6953: 
1.870     tempelho 6954: #maincoursedoc {
1.911     bisitz   6955:   clear:both;
1.870     tempelho 6956: }
                   6957: 
                   6958: ul.LC_TabContentBigger {
1.911     bisitz   6959:   display:block;
                   6960:   list-style:none;
                   6961:   padding: 0;
1.870     tempelho 6962: }
                   6963: 
1.795     www      6964: ul.LC_TabContentBigger li {
1.911     bisitz   6965:   vertical-align:bottom;
                   6966:   height: 30px;
                   6967:   font-size:110%;
                   6968:   font-weight:bold;
                   6969:   color: #737373;
1.841     tempelho 6970: }
                   6971: 
1.957     onken    6972: ul.LC_TabContentBigger li.active {
                   6973:   position: relative;
                   6974:   top: 1px;
                   6975: }
                   6976: 
1.870     tempelho 6977: ul.LC_TabContentBigger li a {
1.911     bisitz   6978:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6979:   height: 30px;
                   6980:   line-height: 30px;
                   6981:   text-align: center;
                   6982:   display: block;
                   6983:   text-decoration: none;
1.958     onken    6984:   outline: none;  
1.741     harmsja  6985: }
1.795     www      6986: 
1.870     tempelho 6987: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6988:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6989:   color:$font;
1.744     ehlerst  6990: }
1.795     www      6991: 
1.870     tempelho 6992: ul.LC_TabContentBigger li b {
1.911     bisitz   6993:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6994:   display: block;
                   6995:   float: left;
                   6996:   padding: 0 30px;
1.957     onken    6997:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6998: }
                   6999: 
1.956     onken    7000: ul.LC_TabContentBigger li:hover b {
                   7001:   color:$button_hover;
                   7002: }
                   7003: 
1.870     tempelho 7004: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7005:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7006:   color:$font;
1.957     onken    7007:   border: 0;
1.741     harmsja  7008: }
1.693     droeschl 7009: 
1.870     tempelho 7010: 
1.862     bisitz   7011: ul.LC_CourseBreadcrumbs {
                   7012:   background: $sidebg;
1.1020    raeburn  7013:   height: 2em;
1.862     bisitz   7014:   padding-left: 10px;
1.1020    raeburn  7015:   margin: 0;
1.862     bisitz   7016:   list-style-position: inside;
                   7017: }
                   7018: 
1.911     bisitz   7019: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7020: ol#LC_PathBreadcrumbs {
1.911     bisitz   7021:   padding-left: 10px;
                   7022:   margin: 0;
1.933     droeschl 7023:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7024: }
                   7025: 
1.911     bisitz   7026: ol#LC_MenuBreadcrumbs li,
                   7027: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7028: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7029:   display: inline;
1.933     droeschl 7030:   white-space: normal;  
1.693     droeschl 7031: }
                   7032: 
1.823     bisitz   7033: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7034: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7035:   text-decoration: none;
                   7036:   font-size:90%;
1.693     droeschl 7037: }
1.795     www      7038: 
1.969     droeschl 7039: ol#LC_MenuBreadcrumbs h1 {
                   7040:   display: inline;
                   7041:   font-size: 90%;
                   7042:   line-height: 2.5em;
                   7043:   margin: 0;
                   7044:   padding: 0;
                   7045: }
                   7046: 
1.795     www      7047: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7048:   text-decoration:none;
                   7049:   font-size:100%;
                   7050:   font-weight:bold;
1.693     droeschl 7051: }
1.795     www      7052: 
1.840     bisitz   7053: .LC_Box {
1.911     bisitz   7054:   border: solid 1px $lg_border_color;
                   7055:   padding: 0 10px 10px 10px;
1.746     neumanie 7056: }
1.795     www      7057: 
1.1020    raeburn  7058: .LC_DocsBox {
                   7059:   border: solid 1px $lg_border_color;
                   7060:   padding: 0 0 10px 10px;
                   7061: }
                   7062: 
1.795     www      7063: .LC_AboutMe_Image {
1.911     bisitz   7064:   float:left;
                   7065:   margin-right:10px;
1.747     neumanie 7066: }
1.795     www      7067: 
                   7068: .LC_Clear_AboutMe_Image {
1.911     bisitz   7069:   clear:left;
1.747     neumanie 7070: }
1.795     www      7071: 
1.721     harmsja  7072: dl.LC_ListStyleClean dt {
1.911     bisitz   7073:   padding-right: 5px;
                   7074:   display: table-header-group;
1.693     droeschl 7075: }
                   7076: 
1.721     harmsja  7077: dl.LC_ListStyleClean dd {
1.911     bisitz   7078:   display: table-row;
1.693     droeschl 7079: }
                   7080: 
1.721     harmsja  7081: .LC_ListStyleClean,
                   7082: .LC_ListStyleSimple,
                   7083: .LC_ListStyleNormal,
1.795     www      7084: .LC_ListStyleSpecial {
1.911     bisitz   7085:   /* display:block; */
                   7086:   list-style-position: inside;
                   7087:   list-style-type: none;
                   7088:   overflow: hidden;
                   7089:   padding: 0;
1.693     droeschl 7090: }
                   7091: 
1.721     harmsja  7092: .LC_ListStyleSimple li,
                   7093: .LC_ListStyleSimple dd,
                   7094: .LC_ListStyleNormal li,
                   7095: .LC_ListStyleNormal dd,
                   7096: .LC_ListStyleSpecial li,
1.795     www      7097: .LC_ListStyleSpecial dd {
1.911     bisitz   7098:   margin: 0;
                   7099:   padding: 5px 5px 5px 10px;
                   7100:   clear: both;
1.693     droeschl 7101: }
                   7102: 
1.721     harmsja  7103: .LC_ListStyleClean li,
                   7104: .LC_ListStyleClean dd {
1.911     bisitz   7105:   padding-top: 0;
                   7106:   padding-bottom: 0;
1.693     droeschl 7107: }
                   7108: 
1.721     harmsja  7109: .LC_ListStyleSimple dd,
1.795     www      7110: .LC_ListStyleSimple li {
1.911     bisitz   7111:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7112: }
                   7113: 
1.721     harmsja  7114: .LC_ListStyleSpecial li,
                   7115: .LC_ListStyleSpecial dd {
1.911     bisitz   7116:   list-style-type: none;
                   7117:   background-color: RGB(220, 220, 220);
                   7118:   margin-bottom: 4px;
1.693     droeschl 7119: }
                   7120: 
1.721     harmsja  7121: table.LC_SimpleTable {
1.911     bisitz   7122:   margin:5px;
                   7123:   border:solid 1px $lg_border_color;
1.795     www      7124: }
1.693     droeschl 7125: 
1.721     harmsja  7126: table.LC_SimpleTable tr {
1.911     bisitz   7127:   padding: 0;
                   7128:   border:solid 1px $lg_border_color;
1.693     droeschl 7129: }
1.795     www      7130: 
                   7131: table.LC_SimpleTable thead {
1.911     bisitz   7132:   background:rgb(220,220,220);
1.693     droeschl 7133: }
                   7134: 
1.721     harmsja  7135: div.LC_columnSection {
1.911     bisitz   7136:   display: block;
                   7137:   clear: both;
                   7138:   overflow: hidden;
                   7139:   margin: 0;
1.693     droeschl 7140: }
                   7141: 
1.721     harmsja  7142: div.LC_columnSection>* {
1.911     bisitz   7143:   float: left;
                   7144:   margin: 10px 20px 10px 0;
                   7145:   overflow:hidden;
1.693     droeschl 7146: }
1.721     harmsja  7147: 
1.795     www      7148: table em {
1.911     bisitz   7149:   font-weight: bold;
                   7150:   font-style: normal;
1.748     schulted 7151: }
1.795     www      7152: 
1.779     bisitz   7153: table.LC_tableBrowseRes,
1.795     www      7154: table.LC_tableOfContent {
1.911     bisitz   7155:   border:none;
                   7156:   border-spacing: 1px;
                   7157:   padding: 3px;
                   7158:   background-color: #FFFFFF;
                   7159:   font-size: 90%;
1.753     droeschl 7160: }
1.789     droeschl 7161: 
1.911     bisitz   7162: table.LC_tableOfContent {
                   7163:   border-collapse: collapse;
1.789     droeschl 7164: }
                   7165: 
1.771     droeschl 7166: table.LC_tableBrowseRes a,
1.768     schulted 7167: table.LC_tableOfContent a {
1.911     bisitz   7168:   background-color: transparent;
                   7169:   text-decoration: none;
1.753     droeschl 7170: }
                   7171: 
1.795     www      7172: table.LC_tableOfContent img {
1.911     bisitz   7173:   border: none;
                   7174:   height: 1.3em;
                   7175:   vertical-align: text-bottom;
                   7176:   margin-right: 0.3em;
1.753     droeschl 7177: }
1.757     schulted 7178: 
1.795     www      7179: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7180:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7181: }
                   7182: 
1.795     www      7183: a#LC_content_toolbar_everything {
1.911     bisitz   7184:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7185: }
                   7186: 
1.795     www      7187: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7188:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7189: }
                   7190: 
1.795     www      7191: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7192:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7193: }
                   7194: 
1.795     www      7195: a#LC_content_toolbar_changefolder {
1.911     bisitz   7196:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7197: }
                   7198: 
1.795     www      7199: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7200:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7201: }
                   7202: 
1.1043    raeburn  7203: a#LC_content_toolbar_edittoplevel {
                   7204:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7205: }
                   7206: 
1.795     www      7207: ul#LC_toolbar li a:hover {
1.911     bisitz   7208:   background-position: bottom center;
1.757     schulted 7209: }
                   7210: 
1.795     www      7211: ul#LC_toolbar {
1.911     bisitz   7212:   padding: 0;
                   7213:   margin: 2px;
                   7214:   list-style:none;
                   7215:   position:relative;
                   7216:   background-color:white;
1.1075.2.9  raeburn  7217:   overflow: auto;
1.757     schulted 7218: }
                   7219: 
1.795     www      7220: ul#LC_toolbar li {
1.911     bisitz   7221:   border:1px solid white;
                   7222:   padding: 0;
                   7223:   margin: 0;
                   7224:   float: left;
                   7225:   display:inline;
                   7226:   vertical-align:middle;
1.1075.2.9  raeburn  7227:   white-space: nowrap;
1.911     bisitz   7228: }
1.757     schulted 7229: 
1.783     amueller 7230: 
1.795     www      7231: a.LC_toolbarItem {
1.911     bisitz   7232:   display:block;
                   7233:   padding: 0;
                   7234:   margin: 0;
                   7235:   height: 32px;
                   7236:   width: 32px;
                   7237:   color:white;
                   7238:   border: none;
                   7239:   background-repeat:no-repeat;
                   7240:   background-color:transparent;
1.757     schulted 7241: }
                   7242: 
1.915     droeschl 7243: ul.LC_funclist {
                   7244:     margin: 0;
                   7245:     padding: 0.5em 1em 0.5em 0;
                   7246: }
                   7247: 
1.933     droeschl 7248: ul.LC_funclist > li:first-child {
                   7249:     font-weight:bold; 
                   7250:     margin-left:0.8em;
                   7251: }
                   7252: 
1.915     droeschl 7253: ul.LC_funclist + ul.LC_funclist {
                   7254:     /* 
                   7255:        left border as a seperator if we have more than
                   7256:        one list 
                   7257:     */
                   7258:     border-left: 1px solid $sidebg;
                   7259:     /* 
                   7260:        this hides the left border behind the border of the 
                   7261:        outer box if element is wrapped to the next 'line' 
                   7262:     */
                   7263:     margin-left: -1px;
                   7264: }
                   7265: 
1.843     bisitz   7266: ul.LC_funclist li {
1.915     droeschl 7267:   display: inline;
1.782     bisitz   7268:   white-space: nowrap;
1.915     droeschl 7269:   margin: 0 0 0 25px;
                   7270:   line-height: 150%;
1.782     bisitz   7271: }
                   7272: 
1.974     wenzelju 7273: .LC_hidden {
                   7274:   display: none;
                   7275: }
                   7276: 
1.1030    www      7277: .LCmodal-overlay {
                   7278: 		position:fixed;
                   7279: 		top:0;
                   7280: 		right:0;
                   7281: 		bottom:0;
                   7282: 		left:0;
                   7283: 		height:100%;
                   7284: 		width:100%;
                   7285: 		margin:0;
                   7286: 		padding:0;
                   7287: 		background:#999;
                   7288: 		opacity:.75;
                   7289: 		filter: alpha(opacity=75);
                   7290: 		-moz-opacity: 0.75;
                   7291: 		z-index:101;
                   7292: }
                   7293: 
                   7294: * html .LCmodal-overlay {   
                   7295: 		position: absolute;
                   7296: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7297: }
                   7298: 
                   7299: .LCmodal-window {
                   7300: 		position:fixed;
                   7301: 		top:50%;
                   7302: 		left:50%;
                   7303: 		margin:0;
                   7304: 		padding:0;
                   7305: 		z-index:102;
                   7306: 	}
                   7307: 
                   7308: * html .LCmodal-window {
                   7309: 		position:absolute;
                   7310: }
                   7311: 
                   7312: .LCclose-window {
                   7313: 		position:absolute;
                   7314: 		width:32px;
                   7315: 		height:32px;
                   7316: 		right:8px;
                   7317: 		top:8px;
                   7318: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7319: 		text-indent:-99999px;
                   7320: 		overflow:hidden;
                   7321: 		cursor:pointer;
                   7322: }
                   7323: 
1.1075.2.17  raeburn  7324: /*
                   7325:   styles used by TTH when "Default set of options to pass to tth/m
                   7326:   when converting TeX" in course settings has been set
                   7327: 
                   7328:   option passed: -t
                   7329: 
                   7330: */
                   7331: 
                   7332: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7333: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7334: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7335: td div.norm {line-height:normal;}
                   7336: 
                   7337: /*
                   7338:   option passed -y3
                   7339: */
                   7340: 
                   7341: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7342: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7343: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7344: 
1.343     albertel 7345: END
                   7346: }
                   7347: 
1.306     albertel 7348: =pod
                   7349: 
                   7350: =item * &headtag()
                   7351: 
                   7352: Returns a uniform footer for LON-CAPA web pages.
                   7353: 
1.307     albertel 7354: Inputs: $title - optional title for the head
                   7355:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7356:         $args - optional arguments
1.319     albertel 7357:             force_register - if is true call registerurl so the remote is 
                   7358:                              informed
1.415     albertel 7359:             redirect       -> array ref of
                   7360:                                    1- seconds before redirect occurs
                   7361:                                    2- url to redirect to
                   7362:                                    3- whether the side effect should occur
1.315     albertel 7363:                            (side effect of setting 
                   7364:                                $env{'internal.head.redirect'} to the url 
                   7365:                                redirected too)
1.352     albertel 7366:             domain         -> force to color decorate a page for a specific
                   7367:                                domain
                   7368:             function       -> force usage of a specific rolish color scheme
                   7369:             bgcolor        -> override the default page bgcolor
1.460     albertel 7370:             no_auto_mt_title
                   7371:                            -> prevent &mt()ing the title arg
1.464     albertel 7372: 
1.306     albertel 7373: =cut
                   7374: 
                   7375: sub headtag {
1.313     albertel 7376:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7377:     
1.363     albertel 7378:     my $function = $args->{'function'} || &get_users_function();
                   7379:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7380:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7381:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7382:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7383: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7384: 		   #time(),
1.418     albertel 7385: 		   $env{'environment.color.timestamp'},
1.363     albertel 7386: 		   $function,$domain,$bgcolor);
                   7387: 
1.369     www      7388:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7389: 
1.308     albertel 7390:     my $result =
                   7391: 	'<head>'.
1.1075.2.56  raeburn  7392: 	&font_settings($args);
1.319     albertel 7393: 
1.1075.2.72  raeburn  7394:     my $inhibitprint;
                   7395:     if ($args->{'print_suppress'}) {
                   7396:         $inhibitprint = &print_suppression();
                   7397:     }
1.1064    raeburn  7398: 
1.461     albertel 7399:     if (!$args->{'frameset'}) {
                   7400: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7401:     }
1.1075.2.12  raeburn  7402:     if ($args->{'force_register'}) {
                   7403:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7404:     }
1.436     albertel 7405:     if (!$args->{'no_nav_bar'} 
                   7406: 	&& !$args->{'only_body'}
                   7407: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7408: 	$result .= &help_menu_js($httphost);
1.1032    www      7409:         $result.=&modal_window();
1.1038    www      7410:         $result.=&togglebox_script();
1.1034    www      7411:         $result.=&wishlist_window();
1.1041    www      7412:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7413:     } else {
                   7414:         if ($args->{'add_modal'}) {
                   7415:            $result.=&modal_window();
                   7416:         }
                   7417:         if ($args->{'add_wishlist'}) {
                   7418:            $result.=&wishlist_window();
                   7419:         }
1.1038    www      7420:         if ($args->{'add_togglebox'}) {
                   7421:            $result.=&togglebox_script();
                   7422:         }
1.1041    www      7423:         if ($args->{'add_progressbar'}) {
                   7424:            $result.=&LCprogressbarUpdate_script();
                   7425:         }
1.436     albertel 7426:     }
1.314     albertel 7427:     if (ref($args->{'redirect'})) {
1.414     albertel 7428: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7429: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7430: 	if (!$inhibit_continue) {
                   7431: 	    $env{'internal.head.redirect'} = $url;
                   7432: 	}
1.313     albertel 7433: 	$result.=<<ADDMETA
                   7434: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7435: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7436: ADDMETA
1.1075.2.89  raeburn  7437:     } else {
                   7438:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7439:             my $requrl = $env{'request.uri'};
                   7440:             if ($requrl eq '') {
                   7441:                 $requrl = $ENV{'REQUEST_URI'};
                   7442:                 $requrl =~ s/\?.+$//;
                   7443:             }
                   7444:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7445:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7446:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7447:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7448:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7449:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7450:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7451:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7452:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7453:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7454:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7455:                                 my $numsec = 5;
                   7456:                                 my $timeout = $numsec * 1000;
                   7457:                                 my ($newurl,$locknum,%locks,$msg);
                   7458:                                 if ($env{'request.role.adv'}) {
                   7459:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7460:                                 }
                   7461:                                 my $disable_submit = 0;
                   7462:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7463:                                     $disable_submit = 1;
                   7464:                                 }
                   7465:                                 if ($locknum) {
                   7466:                                     my @lockinfo = sort(values(%locks));
                   7467:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7468:                                            join(", ",sort(values(%locks)))."\\n".
                   7469:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7470:                                 } else {
                   7471:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7472:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7473:                                     }
                   7474:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7475:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7476:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7477:                                         $newurl .= '&role='.$env{'request.role'};
                   7478:                                     }
                   7479:                                     if ($env{'request.symb'}) {
                   7480:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7481:                                     } else {
                   7482:                                         $newurl .= '&origurl='.$requrl;
                   7483:                                     }
                   7484:                                 }
                   7485:                                 $result.=<<OFFLOAD
                   7486: <meta http-equiv="pragma" content="no-cache" />
                   7487: <script type="text/javascript">
1.1075.2.92  raeburn  7488: // <![CDATA[
1.1075.2.89  raeburn  7489: function LC_Offload_Now() {
                   7490:     var dest = "$newurl";
                   7491:     if (dest != '') {
                   7492:         window.location.href="$newurl";
                   7493:     }
                   7494: }
1.1075.2.92  raeburn  7495: \$(document).ready(function () {
                   7496:     window.alert('$msg');
                   7497:     if ($disable_submit) {
1.1075.2.89  raeburn  7498:         \$(".LC_hwk_submit").prop("disabled", true);
                   7499:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7500:     }
                   7501:     setTimeout('LC_Offload_Now()', $timeout);
                   7502: });
                   7503: // ]]>
1.1075.2.89  raeburn  7504: </script>
                   7505: OFFLOAD
                   7506:                             }
                   7507:                         }
                   7508:                     }
                   7509:                 }
                   7510:             }
                   7511:         }
1.313     albertel 7512:     }
1.306     albertel 7513:     if (!defined($title)) {
                   7514: 	$title = 'The LearningOnline Network with CAPA';
                   7515:     }
1.460     albertel 7516:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7517:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7518: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7519:     if (!$args->{'frameset'}) {
                   7520:         $result .= ' /';
                   7521:     }
                   7522:     $result .= '>'
1.1064    raeburn  7523:         .$inhibitprint
1.414     albertel 7524: 	.$head_extra;
1.1075.2.42  raeburn  7525:     if ($env{'browser.mobile'}) {
                   7526:         $result .= '
                   7527: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7528: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7529:     }
1.962     droeschl 7530:     return $result.'</head>';
1.306     albertel 7531: }
                   7532: 
                   7533: =pod
                   7534: 
1.340     albertel 7535: =item * &font_settings()
                   7536: 
                   7537: Returns neccessary <meta> to set the proper encoding
                   7538: 
1.1075.2.56  raeburn  7539: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7540: 
                   7541: =cut
                   7542: 
                   7543: sub font_settings {
1.1075.2.56  raeburn  7544:     my ($args) = @_;
1.340     albertel 7545:     my $headerstring='';
1.1075.2.56  raeburn  7546:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7547:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7548: 	$headerstring.=
1.1075.2.61  raeburn  7549: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7550:         if (!$args->{'frameset'}) {
                   7551:             $headerstring.= ' /';
                   7552:         }
                   7553:         $headerstring .= '>'."\n";
1.340     albertel 7554:     }
                   7555:     return $headerstring;
                   7556: }
                   7557: 
1.341     albertel 7558: =pod
                   7559: 
1.1064    raeburn  7560: =item * &print_suppression()
                   7561: 
                   7562: In course context returns css which causes the body to be blank when media="print",
                   7563: if printout generation is unavailable for the current resource.
                   7564: 
                   7565: This could be because:
                   7566: 
                   7567: (a) printstartdate is in the future
                   7568: 
                   7569: (b) printenddate is in the past
                   7570: 
                   7571: (c) there is an active exam block with "printout"
                   7572: functionality blocked
                   7573: 
                   7574: Users with pav, pfo or evb privileges are exempt.
                   7575: 
                   7576: Inputs: none
                   7577: 
                   7578: =cut
                   7579: 
                   7580: 
                   7581: sub print_suppression {
                   7582:     my $noprint;
                   7583:     if ($env{'request.course.id'}) {
                   7584:         my $scope = $env{'request.course.id'};
                   7585:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7586:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7587:             return;
                   7588:         }
                   7589:         if ($env{'request.course.sec'} ne '') {
                   7590:             $scope .= "/$env{'request.course.sec'}";
                   7591:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7592:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7593:                 return;
1.1064    raeburn  7594:             }
                   7595:         }
                   7596:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7597:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7598:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7599:         if ($blocked) {
                   7600:             my $checkrole = "cm./$cdom/$cnum";
                   7601:             if ($env{'request.course.sec'} ne '') {
                   7602:                 $checkrole .= "/$env{'request.course.sec'}";
                   7603:             }
                   7604:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7605:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7606:                 $noprint = 1;
                   7607:             }
                   7608:         }
                   7609:         unless ($noprint) {
                   7610:             my $symb = &Apache::lonnet::symbread();
                   7611:             if ($symb ne '') {
                   7612:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7613:                 if (ref($navmap)) {
                   7614:                     my $res = $navmap->getBySymb($symb);
                   7615:                     if (ref($res)) {
                   7616:                         if (!$res->resprintable()) {
                   7617:                             $noprint = 1;
                   7618:                         }
                   7619:                     }
                   7620:                 }
                   7621:             }
                   7622:         }
                   7623:         if ($noprint) {
                   7624:             return <<"ENDSTYLE";
                   7625: <style type="text/css" media="print">
                   7626:     body { display:none }
                   7627: </style>
                   7628: ENDSTYLE
                   7629:         }
                   7630:     }
                   7631:     return;
                   7632: }
                   7633: 
                   7634: =pod
                   7635: 
1.341     albertel 7636: =item * &xml_begin()
                   7637: 
                   7638: Returns the needed doctype and <html>
                   7639: 
                   7640: Inputs: none
                   7641: 
                   7642: =cut
                   7643: 
                   7644: sub xml_begin {
1.1075.2.61  raeburn  7645:     my ($is_frameset) = @_;
1.341     albertel 7646:     my $output='';
                   7647: 
                   7648:     if ($env{'browser.mathml'}) {
                   7649: 	$output='<?xml version="1.0"?>'
                   7650:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7651: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7652:             
                   7653: #	    .'<!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">] >'
                   7654: 	    .'<!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">'
                   7655:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7656: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  7657:     } elsif ($is_frameset) {
                   7658:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7659:                 '<html>'."\n";
1.341     albertel 7660:     } else {
1.1075.2.61  raeburn  7661: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7662:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7663:     }
                   7664:     return $output;
                   7665: }
1.340     albertel 7666: 
                   7667: =pod
                   7668: 
1.306     albertel 7669: =item * &start_page()
                   7670: 
                   7671: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7672: 
1.648     raeburn  7673: Inputs:
                   7674: 
                   7675: =over 4
                   7676: 
                   7677: $title - optional title for the page
                   7678: 
                   7679: $head_extra - optional extra HTML to incude inside the <head>
                   7680: 
                   7681: $args - additional optional args supported are:
                   7682: 
                   7683: =over 8
                   7684: 
                   7685:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7686:                                     arg on
1.814     bisitz   7687:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7688:              add_entries    -> additional attributes to add to the  <body>
                   7689:              domain         -> force to color decorate a page for a 
1.317     albertel 7690:                                     specific domain
1.648     raeburn  7691:              function       -> force usage of a specific rolish color
1.317     albertel 7692:                                     scheme
1.648     raeburn  7693:              redirect       -> see &headtag()
                   7694:              bgcolor        -> override the default page bg color
                   7695:              js_ready       -> return a string ready for being used in 
1.317     albertel 7696:                                     a javascript writeln
1.648     raeburn  7697:              html_encode    -> return a string ready for being used in 
1.320     albertel 7698:                                     a html attribute
1.648     raeburn  7699:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7700:                                     $forcereg arg
1.648     raeburn  7701:              frameset       -> if true will start with a <frameset>
1.330     albertel 7702:                                     rather than <body>
1.648     raeburn  7703:              skip_phases    -> hash ref of 
1.338     albertel 7704:                                     head -> skip the <html><head> generation
                   7705:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  7706:              no_inline_link -> if true and in remote mode, don't show the
                   7707:                                     'Switch To Inline Menu' link
1.648     raeburn  7708:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7709:              inherit_jsmath -> when creating popup window in a page,
                   7710:                                     should it have jsmath forced on by the
                   7711:                                     current page
1.867     kalberla 7712:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7713:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  7714:              group          -> includes the current group, if page is for a
                   7715:                                specific group
1.361     albertel 7716: 
1.648     raeburn  7717: =back
1.460     albertel 7718: 
1.648     raeburn  7719: =back
1.562     albertel 7720: 
1.306     albertel 7721: =cut
                   7722: 
                   7723: sub start_page {
1.309     albertel 7724:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7725:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7726: 
1.315     albertel 7727:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  7728:     my ($result,@advtools);
1.964     droeschl 7729: 
1.338     albertel 7730:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  7731:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 7732:     }
                   7733:     
                   7734:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7735: 	if ($args->{'frameset'}) {
                   7736: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7737: 						$args->{'add_entries'});
                   7738: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7739:         } else {
                   7740:             $result .=
                   7741:                 &bodytag($title, 
                   7742:                          $args->{'function'},       $args->{'add_entries'},
                   7743:                          $args->{'only_body'},      $args->{'domain'},
                   7744:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  7745:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  7746:                          $args,                     \@advtools);
1.831     bisitz   7747:         }
1.330     albertel 7748:     }
1.338     albertel 7749: 
1.315     albertel 7750:     if ($args->{'js_ready'}) {
1.713     kaisler  7751: 		$result = &js_ready($result);
1.315     albertel 7752:     }
1.320     albertel 7753:     if ($args->{'html_encode'}) {
1.713     kaisler  7754: 		$result = &html_encode($result);
                   7755:     }
                   7756: 
1.813     bisitz   7757:     # Preparation for new and consistent functionlist at top of screen
                   7758:     # if ($args->{'functionlist'}) {
                   7759:     #            $result .= &build_functionlist();
                   7760:     #}
                   7761: 
1.964     droeschl 7762:     # Don't add anything more if only_body wanted or in const space
                   7763:     return $result if    $args->{'only_body'} 
                   7764:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7765: 
                   7766:     #Breadcrumbs
1.758     kaisler  7767:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7768: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7769: 		#if any br links exists, add them to the breadcrumbs
                   7770: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7771: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7772: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7773: 			}
                   7774: 		}
1.1075.2.19  raeburn  7775:                 # if @advtools array contains items add then to the breadcrumbs
                   7776:                 if (@advtools > 0) {
                   7777:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7778:                 }
1.758     kaisler  7779: 
                   7780: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7781: 		if(exists($args->{'bread_crumbs_component'})){
                   7782: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7783: 		}else{
                   7784: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7785: 		}
1.1075.2.24  raeburn  7786:     } elsif (($env{'environment.remote'} eq 'on') &&
                   7787:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   7788:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   7789:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  7790:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 7791:     }
1.315     albertel 7792:     return $result;
1.306     albertel 7793: }
                   7794: 
                   7795: sub end_page {
1.315     albertel 7796:     my ($args) = @_;
                   7797:     $env{'internal.end_page'}++;
1.330     albertel 7798:     my $result;
1.335     albertel 7799:     if ($args->{'discussion'}) {
                   7800: 	my ($target,$parser);
                   7801: 	if (ref($args->{'discussion'})) {
                   7802: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7803: 				$args->{'discussion'}{'parser'});
                   7804: 	}
                   7805: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7806:     }
1.330     albertel 7807:     if ($args->{'frameset'}) {
                   7808: 	$result .= '</frameset>';
                   7809:     } else {
1.635     raeburn  7810: 	$result .= &endbodytag($args);
1.330     albertel 7811:     }
1.1075.2.6  raeburn  7812:     unless ($args->{'notbody'}) {
                   7813:         $result .= "\n</html>";
                   7814:     }
1.330     albertel 7815: 
1.315     albertel 7816:     if ($args->{'js_ready'}) {
1.317     albertel 7817: 	$result = &js_ready($result);
1.315     albertel 7818:     }
1.335     albertel 7819: 
1.320     albertel 7820:     if ($args->{'html_encode'}) {
                   7821: 	$result = &html_encode($result);
                   7822:     }
1.335     albertel 7823: 
1.315     albertel 7824:     return $result;
                   7825: }
                   7826: 
1.1034    www      7827: sub wishlist_window {
                   7828:     return(<<'ENDWISHLIST');
1.1046    raeburn  7829: <script type="text/javascript">
1.1034    www      7830: // <![CDATA[
                   7831: // <!-- BEGIN LON-CAPA Internal
                   7832: function set_wishlistlink(title, path) {
                   7833:     if (!title) {
                   7834:         title = document.title;
                   7835:         title = title.replace(/^LON-CAPA /,'');
                   7836:     }
1.1075.2.65  raeburn  7837:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  7838:     title = title.replace("'","\\\'");
1.1034    www      7839:     if (!path) {
                   7840:         path = location.pathname;
                   7841:     }
1.1075.2.65  raeburn  7842:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  7843:     path = path.replace("'","\\\'");
1.1034    www      7844:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7845:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7846: }
                   7847: // END LON-CAPA Internal -->
                   7848: // ]]>
                   7849: </script>
                   7850: ENDWISHLIST
                   7851: }
                   7852: 
1.1030    www      7853: sub modal_window {
                   7854:     return(<<'ENDMODAL');
1.1046    raeburn  7855: <script type="text/javascript">
1.1030    www      7856: // <![CDATA[
                   7857: // <!-- BEGIN LON-CAPA Internal
                   7858: var modalWindow = {
                   7859: 	parent:"body",
                   7860: 	windowId:null,
                   7861: 	content:null,
                   7862: 	width:null,
                   7863: 	height:null,
                   7864: 	close:function()
                   7865: 	{
                   7866: 	        $(".LCmodal-window").remove();
                   7867: 	        $(".LCmodal-overlay").remove();
                   7868: 	},
                   7869: 	open:function()
                   7870: 	{
                   7871: 		var modal = "";
                   7872: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7873: 		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;\">";
                   7874: 		modal += this.content;
                   7875: 		modal += "</div>";	
                   7876: 
                   7877: 		$(this.parent).append(modal);
                   7878: 
                   7879: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7880: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7881: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7882: 	}
                   7883: };
1.1075.2.42  raeburn  7884: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      7885: 	{
1.1075.2.83  raeburn  7886:                 source = source.replace("'","&#39;");
1.1030    www      7887: 		modalWindow.windowId = "myModal";
                   7888: 		modalWindow.width = width;
                   7889: 		modalWindow.height = height;
1.1075.2.80  raeburn  7890: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      7891: 		modalWindow.open();
1.1075.2.87  raeburn  7892: 	};
1.1030    www      7893: // END LON-CAPA Internal -->
                   7894: // ]]>
                   7895: </script>
                   7896: ENDMODAL
                   7897: }
                   7898: 
                   7899: sub modal_link {
1.1075.2.42  raeburn  7900:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      7901:     unless ($width) { $width=480; }
                   7902:     unless ($height) { $height=400; }
1.1031    www      7903:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  7904:     unless ($transparency) { $transparency='true'; }
                   7905: 
1.1074    raeburn  7906:     my $target_attr;
                   7907:     if (defined($target)) {
                   7908:         $target_attr = 'target="'.$target.'"';
                   7909:     }
                   7910:     return <<"ENDLINK";
1.1075.2.42  raeburn  7911: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  7912:            $linktext</a>
                   7913: ENDLINK
1.1030    www      7914: }
                   7915: 
1.1032    www      7916: sub modal_adhoc_script {
                   7917:     my ($funcname,$width,$height,$content)=@_;
                   7918:     return (<<ENDADHOC);
1.1046    raeburn  7919: <script type="text/javascript">
1.1032    www      7920: // <![CDATA[
                   7921:         var $funcname = function()
                   7922:         {
                   7923:                 modalWindow.windowId = "myModal";
                   7924:                 modalWindow.width = $width;
                   7925:                 modalWindow.height = $height;
                   7926:                 modalWindow.content = '$content';
                   7927:                 modalWindow.open();
                   7928:         };  
                   7929: // ]]>
                   7930: </script>
                   7931: ENDADHOC
                   7932: }
                   7933: 
1.1041    www      7934: sub modal_adhoc_inner {
                   7935:     my ($funcname,$width,$height,$content)=@_;
                   7936:     my $innerwidth=$width-20;
                   7937:     $content=&js_ready(
1.1042    www      7938:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  7939:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   7940:                  $content.
1.1041    www      7941:                  &end_scrollbox().
1.1075.2.42  raeburn  7942:                  &end_page()
1.1041    www      7943:              );
                   7944:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7945: }
                   7946: 
                   7947: sub modal_adhoc_window {
                   7948:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7949:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7950:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7951: }
                   7952: 
                   7953: sub modal_adhoc_launch {
                   7954:     my ($funcname,$width,$height,$content)=@_;
                   7955:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7956: <script type="text/javascript">
                   7957: // <![CDATA[
                   7958: $funcname();
                   7959: // ]]>
                   7960: </script>
                   7961: ENDLAUNCH
                   7962: }
                   7963: 
                   7964: sub modal_adhoc_close {
                   7965:     return (<<ENDCLOSE);
                   7966: <script type="text/javascript">
                   7967: // <![CDATA[
                   7968: modalWindow.close();
                   7969: // ]]>
                   7970: </script>
                   7971: ENDCLOSE
                   7972: }
                   7973: 
1.1038    www      7974: sub togglebox_script {
                   7975:    return(<<ENDTOGGLE);
                   7976: <script type="text/javascript"> 
                   7977: // <![CDATA[
                   7978: function LCtoggleDisplay(id,hidetext,showtext) {
                   7979:    link = document.getElementById(id + "link").childNodes[0];
                   7980:    with (document.getElementById(id).style) {
                   7981:       if (display == "none" ) {
                   7982:           display = "inline";
                   7983:           link.nodeValue = hidetext;
                   7984:         } else {
                   7985:           display = "none";
                   7986:           link.nodeValue = showtext;
                   7987:        }
                   7988:    }
                   7989: }
                   7990: // ]]>
                   7991: </script>
                   7992: ENDTOGGLE
                   7993: }
                   7994: 
1.1039    www      7995: sub start_togglebox {
                   7996:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7997:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7998:     unless ($showtext) { $showtext=&mt('show'); }
                   7999:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8000:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8001:     return &start_data_table().
                   8002:            &start_data_table_header_row().
                   8003:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8004:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8005:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8006:            &end_data_table_header_row().
                   8007:            '<tr id="'.$id.'" style="display:none""><td>';
                   8008: }
                   8009: 
                   8010: sub end_togglebox {
                   8011:     return '</td></tr>'.&end_data_table();
                   8012: }
                   8013: 
1.1041    www      8014: sub LCprogressbar_script {
1.1045    www      8015:    my ($id)=@_;
1.1041    www      8016:    return(<<ENDPROGRESS);
                   8017: <script type="text/javascript">
                   8018: // <![CDATA[
1.1045    www      8019: \$('#progressbar$id').progressbar({
1.1041    www      8020:   value: 0,
                   8021:   change: function(event, ui) {
                   8022:     var newVal = \$(this).progressbar('option', 'value');
                   8023:     \$('.pblabel', this).text(LCprogressTxt);
                   8024:   }
                   8025: });
                   8026: // ]]>
                   8027: </script>
                   8028: ENDPROGRESS
                   8029: }
                   8030: 
                   8031: sub LCprogressbarUpdate_script {
                   8032:    return(<<ENDPROGRESSUPDATE);
                   8033: <style type="text/css">
                   8034: .ui-progressbar { position:relative; }
                   8035: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8036: </style>
                   8037: <script type="text/javascript">
                   8038: // <![CDATA[
1.1045    www      8039: var LCprogressTxt='---';
                   8040: 
                   8041: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8042:    LCprogressTxt=progresstext;
1.1045    www      8043:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8044: }
                   8045: // ]]>
                   8046: </script>
                   8047: ENDPROGRESSUPDATE
                   8048: }
                   8049: 
1.1042    www      8050: my $LClastpercent;
1.1045    www      8051: my $LCidcnt;
                   8052: my $LCcurrentid;
1.1042    www      8053: 
1.1041    www      8054: sub LCprogressbar {
1.1042    www      8055:     my ($r)=(@_);
                   8056:     $LClastpercent=0;
1.1045    www      8057:     $LCidcnt++;
                   8058:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8059:     my $starting=&mt('Starting');
                   8060:     my $content=(<<ENDPROGBAR);
1.1045    www      8061:   <div id="progressbar$LCcurrentid">
1.1041    www      8062:     <span class="pblabel">$starting</span>
                   8063:   </div>
                   8064: ENDPROGBAR
1.1045    www      8065:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8066: }
                   8067: 
                   8068: sub LCprogressbarUpdate {
1.1042    www      8069:     my ($r,$val,$text)=@_;
                   8070:     unless ($val) { 
                   8071:        if ($LClastpercent) {
                   8072:            $val=$LClastpercent;
                   8073:        } else {
                   8074:            $val=0;
                   8075:        }
                   8076:     }
1.1041    www      8077:     if ($val<0) { $val=0; }
                   8078:     if ($val>100) { $val=0; }
1.1042    www      8079:     $LClastpercent=$val;
1.1041    www      8080:     unless ($text) { $text=$val.'%'; }
                   8081:     $text=&js_ready($text);
1.1044    www      8082:     &r_print($r,<<ENDUPDATE);
1.1041    www      8083: <script type="text/javascript">
                   8084: // <![CDATA[
1.1045    www      8085: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8086: // ]]>
                   8087: </script>
                   8088: ENDUPDATE
1.1035    www      8089: }
                   8090: 
1.1042    www      8091: sub LCprogressbarClose {
                   8092:     my ($r)=@_;
                   8093:     $LClastpercent=0;
1.1044    www      8094:     &r_print($r,<<ENDCLOSE);
1.1042    www      8095: <script type="text/javascript">
                   8096: // <![CDATA[
1.1045    www      8097: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8098: // ]]>
                   8099: </script>
                   8100: ENDCLOSE
1.1044    www      8101: }
                   8102: 
                   8103: sub r_print {
                   8104:     my ($r,$to_print)=@_;
                   8105:     if ($r) {
                   8106:       $r->print($to_print);
                   8107:       $r->rflush();
                   8108:     } else {
                   8109:       print($to_print);
                   8110:     }
1.1042    www      8111: }
                   8112: 
1.320     albertel 8113: sub html_encode {
                   8114:     my ($result) = @_;
                   8115: 
1.322     albertel 8116:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8117:     
                   8118:     return $result;
                   8119: }
1.1044    www      8120: 
1.317     albertel 8121: sub js_ready {
                   8122:     my ($result) = @_;
                   8123: 
1.323     albertel 8124:     $result =~ s/[\n\r]/ /xmsg;
                   8125:     $result =~ s/\\/\\\\/xmsg;
                   8126:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8127:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8128:     
                   8129:     return $result;
                   8130: }
                   8131: 
1.315     albertel 8132: sub validate_page {
                   8133:     if (  exists($env{'internal.start_page'})
1.316     albertel 8134: 	  &&     $env{'internal.start_page'} > 1) {
                   8135: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8136: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8137: 				 $ENV{'request.filename'});
1.315     albertel 8138:     }
                   8139:     if (  exists($env{'internal.end_page'})
1.316     albertel 8140: 	  &&     $env{'internal.end_page'} > 1) {
                   8141: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8142: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8143: 				 $env{'request.filename'});
1.315     albertel 8144:     }
                   8145:     if (     exists($env{'internal.start_page'})
                   8146: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8147: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8148: 				 $env{'request.filename'});
1.315     albertel 8149:     }
                   8150:     if (   ! exists($env{'internal.start_page'})
                   8151: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8152: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8153: 				 $env{'request.filename'});
1.315     albertel 8154:     }
1.306     albertel 8155: }
1.315     albertel 8156: 
1.996     www      8157: 
                   8158: sub start_scrollbox {
1.1075.2.56  raeburn  8159:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8160:     unless ($outerwidth) { $outerwidth='520px'; }
                   8161:     unless ($width) { $width='500px'; }
                   8162:     unless ($height) { $height='200px'; }
1.1075    raeburn  8163:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8164:     if ($id ne '') {
1.1075.2.42  raeburn  8165:         $table_id = ' id="table_'.$id.'"';
                   8166:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8167:     }
1.1075    raeburn  8168:     if ($bgcolor ne '') {
                   8169:         $tdcol = "background-color: $bgcolor;";
                   8170:     }
1.1075.2.42  raeburn  8171:     my $nicescroll_js;
                   8172:     if ($env{'browser.mobile'}) {
                   8173:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8174:     }
1.1075    raeburn  8175:     return <<"END";
1.1075.2.42  raeburn  8176: $nicescroll_js
                   8177: 
                   8178: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8179: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8180: END
1.996     www      8181: }
                   8182: 
                   8183: sub end_scrollbox {
1.1036    www      8184:     return '</div></td></tr></table>';
1.996     www      8185: }
                   8186: 
1.1075.2.42  raeburn  8187: sub nicescroll_javascript {
                   8188:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8189:     my %options;
                   8190:     if (ref($cursor) eq 'HASH') {
                   8191:         %options = %{$cursor};
                   8192:     }
                   8193:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8194:         $options{'railalign'} = 'left';
                   8195:     }
                   8196:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8197:         my $function  = &get_users_function();
                   8198:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8199:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8200:             $options{'cursorcolor'} = '#00F';
                   8201:         }
                   8202:     }
                   8203:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8204:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8205:             $options{'cursoropacity'}='1.0';
                   8206:         }
                   8207:     } else {
                   8208:         $options{'cursoropacity'}='1.0';
                   8209:     }
                   8210:     if ($options{'cursorfixedheight'} eq 'none') {
                   8211:         delete($options{'cursorfixedheight'});
                   8212:     } else {
                   8213:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8214:     }
                   8215:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8216:         delete($options{'railoffset'});
                   8217:     }
                   8218:     my @niceoptions;
                   8219:     while (my($key,$value) = each(%options)) {
                   8220:         if ($value =~ /^\{.+\}$/) {
                   8221:             push(@niceoptions,$key.':'.$value);
                   8222:         } else {
                   8223:             push(@niceoptions,$key.':"'.$value.'"');
                   8224:         }
                   8225:     }
                   8226:     my $nicescroll_js = '
                   8227: $(document).ready(
                   8228:       function() {
                   8229:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8230:       }
                   8231: );
                   8232: ';
                   8233:     if ($framecheck) {
                   8234:         $nicescroll_js .= '
                   8235: function expand_div(caller) {
                   8236:     if (top === self) {
                   8237:         document.getElementById("'.$id.'").style.width = "auto";
                   8238:         document.getElementById("'.$id.'").style.height = "auto";
                   8239:     } else {
                   8240:         try {
                   8241:             if (parent.frames) {
                   8242:                 if (parent.frames.length > 1) {
                   8243:                     var framesrc = parent.frames[1].location.href;
                   8244:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8245:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8246:                         document.getElementById("'.$id.'").style.width = "auto";
                   8247:                         document.getElementById("'.$id.'").style.height = "auto";
                   8248:                     }
                   8249:                 }
                   8250:             }
                   8251:         } catch (e) {
                   8252:             return;
                   8253:         }
                   8254:     }
                   8255:     return;
                   8256: }
                   8257: ';
                   8258:     }
                   8259:     if ($needjsready) {
                   8260:         $nicescroll_js = '
                   8261: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8262:     } else {
                   8263:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8264:     }
                   8265:     return $nicescroll_js;
                   8266: }
                   8267: 
1.318     albertel 8268: sub simple_error_page {
1.1075.2.49  raeburn  8269:     my ($r,$title,$msg,$args) = @_;
                   8270:     if (ref($args) eq 'HASH') {
                   8271:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8272:     } else {
                   8273:         $msg = &mt($msg);
                   8274:     }
                   8275: 
1.318     albertel 8276:     my $page =
                   8277: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8278: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8279: 	&Apache::loncommon::end_page();
                   8280:     if (ref($r)) {
                   8281: 	$r->print($page);
1.327     albertel 8282: 	return;
1.318     albertel 8283:     }
                   8284:     return $page;
                   8285: }
1.347     albertel 8286: 
                   8287: {
1.610     albertel 8288:     my @row_count;
1.961     onken    8289: 
                   8290:     sub start_data_table_count {
                   8291:         unshift(@row_count, 0);
                   8292:         return;
                   8293:     }
                   8294: 
                   8295:     sub end_data_table_count {
                   8296:         shift(@row_count);
                   8297:         return;
                   8298:     }
                   8299: 
1.347     albertel 8300:     sub start_data_table {
1.1018    raeburn  8301: 	my ($add_class,$id) = @_;
1.422     albertel 8302: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8303:         my $table_id;
                   8304:         if (defined($id)) {
                   8305:             $table_id = ' id="'.$id.'"';
                   8306:         }
1.961     onken    8307: 	&start_data_table_count();
1.1018    raeburn  8308: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8309:     }
                   8310: 
                   8311:     sub end_data_table {
1.961     onken    8312: 	&end_data_table_count();
1.389     albertel 8313: 	return '</table>'."\n";;
1.347     albertel 8314:     }
                   8315: 
                   8316:     sub start_data_table_row {
1.974     wenzelju 8317: 	my ($add_class, $id) = @_;
1.610     albertel 8318: 	$row_count[0]++;
                   8319: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8320: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8321:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8322:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8323:     }
1.471     banghart 8324:     
                   8325:     sub continue_data_table_row {
1.974     wenzelju 8326: 	my ($add_class, $id) = @_;
1.610     albertel 8327: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8328: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8329:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8330:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8331:     }
1.347     albertel 8332: 
                   8333:     sub end_data_table_row {
1.389     albertel 8334: 	return '</tr>'."\n";;
1.347     albertel 8335:     }
1.367     www      8336: 
1.421     albertel 8337:     sub start_data_table_empty_row {
1.707     bisitz   8338: #	$row_count[0]++;
1.421     albertel 8339: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8340:     }
                   8341: 
                   8342:     sub end_data_table_empty_row {
                   8343: 	return '</tr>'."\n";;
                   8344:     }
                   8345: 
1.367     www      8346:     sub start_data_table_header_row {
1.389     albertel 8347: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8348:     }
                   8349: 
                   8350:     sub end_data_table_header_row {
1.389     albertel 8351: 	return '</tr>'."\n";;
1.367     www      8352:     }
1.890     droeschl 8353: 
                   8354:     sub data_table_caption {
                   8355:         my $caption = shift;
                   8356:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8357:     }
1.347     albertel 8358: }
                   8359: 
1.548     albertel 8360: =pod
                   8361: 
                   8362: =item * &inhibit_menu_check($arg)
                   8363: 
                   8364: Checks for a inhibitmenu state and generates output to preserve it
                   8365: 
                   8366: Inputs:         $arg - can be any of
                   8367:                      - undef - in which case the return value is a string 
                   8368:                                to add  into arguments list of a uri
                   8369:                      - 'input' - in which case the return value is a HTML
                   8370:                                  <form> <input> field of type hidden to
                   8371:                                  preserve the value
                   8372:                      - a url - in which case the return value is the url with
                   8373:                                the neccesary cgi args added to preserve the
                   8374:                                inhibitmenu state
                   8375:                      - a ref to a url - no return value, but the string is
                   8376:                                         updated to include the neccessary cgi
                   8377:                                         args to preserve the inhibitmenu state
                   8378: 
                   8379: =cut
                   8380: 
                   8381: sub inhibit_menu_check {
                   8382:     my ($arg) = @_;
                   8383:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8384:     if ($arg eq 'input') {
                   8385: 	if ($env{'form.inhibitmenu'}) {
                   8386: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8387: 	} else {
                   8388: 	    return
                   8389: 	}
                   8390:     }
                   8391:     if ($env{'form.inhibitmenu'}) {
                   8392: 	if (ref($arg)) {
                   8393: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8394: 	} elsif ($arg eq '') {
                   8395: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8396: 	} else {
                   8397: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8398: 	}
                   8399:     }
                   8400:     if (!ref($arg)) {
                   8401: 	return $arg;
                   8402:     }
                   8403: }
                   8404: 
1.251     albertel 8405: ###############################################
1.182     matthew  8406: 
                   8407: =pod
                   8408: 
1.549     albertel 8409: =back
                   8410: 
                   8411: =head1 User Information Routines
                   8412: 
                   8413: =over 4
                   8414: 
1.405     albertel 8415: =item * &get_users_function()
1.182     matthew  8416: 
                   8417: Used by &bodytag to determine the current users primary role.
                   8418: Returns either 'student','coordinator','admin', or 'author'.
                   8419: 
                   8420: =cut
                   8421: 
                   8422: ###############################################
                   8423: sub get_users_function {
1.815     tempelho 8424:     my $function = 'norole';
1.818     tempelho 8425:     if ($env{'request.role'}=~/^(st)/) {
                   8426:         $function='student';
                   8427:     }
1.907     raeburn  8428:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8429:         $function='coordinator';
                   8430:     }
1.258     albertel 8431:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8432:         $function='admin';
                   8433:     }
1.826     bisitz   8434:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8435:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8436:         $function='author';
                   8437:     }
                   8438:     return $function;
1.54      www      8439: }
1.99      www      8440: 
                   8441: ###############################################
                   8442: 
1.233     raeburn  8443: =pod
                   8444: 
1.821     raeburn  8445: =item * &show_course()
                   8446: 
                   8447: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8448: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8449: 
                   8450: Inputs:
                   8451: None
                   8452: 
                   8453: Outputs:
                   8454: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8455: 
                   8456: =cut
                   8457: 
                   8458: ###############################################
                   8459: sub show_course {
                   8460:     my $course = !$env{'user.adv'};
                   8461:     if (!$env{'user.adv'}) {
                   8462:         foreach my $env (keys(%env)) {
                   8463:             next if ($env !~ m/^user\.priv\./);
                   8464:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8465:                 $course = 0;
                   8466:                 last;
                   8467:             }
                   8468:         }
                   8469:     }
                   8470:     return $course;
                   8471: }
                   8472: 
                   8473: ###############################################
                   8474: 
                   8475: =pod
                   8476: 
1.542     raeburn  8477: =item * &check_user_status()
1.274     raeburn  8478: 
                   8479: Determines current status of supplied role for a
                   8480: specific user. Roles can be active, previous or future.
                   8481: 
                   8482: Inputs: 
                   8483: user's domain, user's username, course's domain,
1.375     raeburn  8484: course's number, optional section ID.
1.274     raeburn  8485: 
                   8486: Outputs:
                   8487: role status: active, previous or future. 
                   8488: 
                   8489: =cut
                   8490: 
                   8491: sub check_user_status {
1.412     raeburn  8492:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8493:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8494:     my @uroles = keys(%userinfo);
1.274     raeburn  8495:     my $srchstr;
                   8496:     my $active_chk = 'none';
1.412     raeburn  8497:     my $now = time;
1.274     raeburn  8498:     if (@uroles > 0) {
1.908     raeburn  8499:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8500:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8501:         } else {
1.412     raeburn  8502:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8503:         }
                   8504:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8505:             my $role_end = 0;
                   8506:             my $role_start = 0;
                   8507:             $active_chk = 'active';
1.412     raeburn  8508:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8509:                 $role_end = $1;
                   8510:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8511:                     $role_start = $1;
1.274     raeburn  8512:                 }
                   8513:             }
                   8514:             if ($role_start > 0) {
1.412     raeburn  8515:                 if ($now < $role_start) {
1.274     raeburn  8516:                     $active_chk = 'future';
                   8517:                 }
                   8518:             }
                   8519:             if ($role_end > 0) {
1.412     raeburn  8520:                 if ($now > $role_end) {
1.274     raeburn  8521:                     $active_chk = 'previous';
                   8522:                 }
                   8523:             }
                   8524:         }
                   8525:     }
                   8526:     return $active_chk;
                   8527: }
                   8528: 
                   8529: ###############################################
                   8530: 
                   8531: =pod
                   8532: 
1.405     albertel 8533: =item * &get_sections()
1.233     raeburn  8534: 
                   8535: Determines all the sections for a course including
                   8536: sections with students and sections containing other roles.
1.419     raeburn  8537: Incoming parameters: 
                   8538: 
                   8539: 1. domain
                   8540: 2. course number 
                   8541: 3. reference to array containing roles for which sections should 
                   8542: be gathered (optional).
                   8543: 4. reference to array containing status types for which sections 
                   8544: should be gathered (optional).
                   8545: 
                   8546: If the third argument is undefined, sections are gathered for any role. 
                   8547: If the fourth argument is undefined, sections are gathered for any status.
                   8548: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8549:  
1.374     raeburn  8550: Returns section hash (keys are section IDs, values are
                   8551: number of users in each section), subject to the
1.419     raeburn  8552: optional roles filter, optional status filter 
1.233     raeburn  8553: 
                   8554: =cut
                   8555: 
                   8556: ###############################################
                   8557: sub get_sections {
1.419     raeburn  8558:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8559:     if (!defined($cdom) || !defined($cnum)) {
                   8560:         my $cid =  $env{'request.course.id'};
                   8561: 
                   8562: 	return if (!defined($cid));
                   8563: 
                   8564:         $cdom = $env{'course.'.$cid.'.domain'};
                   8565:         $cnum = $env{'course.'.$cid.'.num'};
                   8566:     }
                   8567: 
                   8568:     my %sectioncount;
1.419     raeburn  8569:     my $now = time;
1.240     albertel 8570: 
1.1075.2.33  raeburn  8571:     my $check_students = 1;
                   8572:     my $only_students = 0;
                   8573:     if (ref($possible_roles) eq 'ARRAY') {
                   8574:         if (grep(/^st$/,@{$possible_roles})) {
                   8575:             if (@{$possible_roles} == 1) {
                   8576:                 $only_students = 1;
                   8577:             }
                   8578:         } else {
                   8579:             $check_students = 0;
                   8580:         }
                   8581:     }
                   8582: 
                   8583:     if ($check_students) {
1.276     albertel 8584: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8585: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8586: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8587:         my $start_index = &Apache::loncoursedata::CL_START();
                   8588:         my $end_index = &Apache::loncoursedata::CL_END();
                   8589:         my $status;
1.366     albertel 8590: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8591: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8592: 				                     $data->[$status_index],
                   8593:                                                      $data->[$start_index],
                   8594:                                                      $data->[$end_index]);
                   8595:             if ($stu_status eq 'Active') {
                   8596:                 $status = 'active';
                   8597:             } elsif ($end < $now) {
                   8598:                 $status = 'previous';
                   8599:             } elsif ($start > $now) {
                   8600:                 $status = 'future';
                   8601:             } 
                   8602: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8603:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8604:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8605: 		    $sectioncount{$section}++;
                   8606:                 }
1.240     albertel 8607: 	    }
                   8608: 	}
                   8609:     }
1.1075.2.33  raeburn  8610:     if ($only_students) {
                   8611:         return %sectioncount;
                   8612:     }
1.240     albertel 8613:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8614:     foreach my $user (sort(keys(%courseroles))) {
                   8615: 	if ($user !~ /^(\w{2})/) { next; }
                   8616: 	my ($role) = ($user =~ /^(\w{2})/);
                   8617: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8618: 	my ($section,$status);
1.240     albertel 8619: 	if ($role eq 'cr' &&
                   8620: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8621: 	    $section=$1;
                   8622: 	}
                   8623: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8624: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8625:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8626:         if ($end == -1 && $start == -1) {
                   8627:             next; #deleted role
                   8628:         }
                   8629:         if (!defined($possible_status)) { 
                   8630:             $sectioncount{$section}++;
                   8631:         } else {
                   8632:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8633:                 $status = 'active';
                   8634:             } elsif ($end < $now) {
                   8635:                 $status = 'future';
                   8636:             } elsif ($start > $now) {
                   8637:                 $status = 'previous';
                   8638:             }
                   8639:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8640:                 $sectioncount{$section}++;
                   8641:             }
                   8642:         }
1.233     raeburn  8643:     }
1.366     albertel 8644:     return %sectioncount;
1.233     raeburn  8645: }
                   8646: 
1.274     raeburn  8647: ###############################################
1.294     raeburn  8648: 
                   8649: =pod
1.405     albertel 8650: 
                   8651: =item * &get_course_users()
                   8652: 
1.275     raeburn  8653: Retrieves usernames:domains for users in the specified course
                   8654: with specific role(s), and access status. 
                   8655: 
                   8656: Incoming parameters:
1.277     albertel 8657: 1. course domain
                   8658: 2. course number
                   8659: 3. access status: users must have - either active, 
1.275     raeburn  8660: previous, future, or all.
1.277     albertel 8661: 4. reference to array of permissible roles
1.288     raeburn  8662: 5. reference to array of section restrictions (optional)
                   8663: 6. reference to results object (hash of hashes).
                   8664: 7. reference to optional userdata hash
1.609     raeburn  8665: 8. reference to optional statushash
1.630     raeburn  8666: 9. flag if privileged users (except those set to unhide in
                   8667:    course settings) should be excluded    
1.609     raeburn  8668: Keys of top level results hash are roles.
1.275     raeburn  8669: Keys of inner hashes are username:domain, with 
                   8670: values set to access type.
1.288     raeburn  8671: Optional userdata hash returns an array with arguments in the 
                   8672: same order as loncoursedata::get_classlist() for student data.
                   8673: 
1.609     raeburn  8674: Optional statushash returns
                   8675: 
1.288     raeburn  8676: Entries for end, start, section and status are blank because
                   8677: of the possibility of multiple values for non-student roles.
                   8678: 
1.275     raeburn  8679: =cut
1.405     albertel 8680: 
1.275     raeburn  8681: ###############################################
1.405     albertel 8682: 
1.275     raeburn  8683: sub get_course_users {
1.630     raeburn  8684:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8685:     my %idx = ();
1.419     raeburn  8686:     my %seclists;
1.288     raeburn  8687: 
                   8688:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8689:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8690:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8691:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8692:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8693:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8694:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8695:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8696: 
1.290     albertel 8697:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8698:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8699:         my $now = time;
1.277     albertel 8700:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8701:             my $match = 0;
1.412     raeburn  8702:             my $secmatch = 0;
1.419     raeburn  8703:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8704:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8705:             if ($section eq '') {
                   8706:                 $section = 'none';
                   8707:             }
1.291     albertel 8708:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8709:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8710:                     $secmatch = 1;
                   8711:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8712:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8713:                         $secmatch = 1;
                   8714:                     }
                   8715:                 } else {  
1.419     raeburn  8716: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8717: 		        $secmatch = 1;
                   8718:                     }
1.290     albertel 8719: 		}
1.412     raeburn  8720:                 if (!$secmatch) {
                   8721:                     next;
                   8722:                 }
1.419     raeburn  8723:             }
1.275     raeburn  8724:             if (defined($$types{'active'})) {
1.288     raeburn  8725:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8726:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8727:                     $match = 1;
1.275     raeburn  8728:                 }
                   8729:             }
                   8730:             if (defined($$types{'previous'})) {
1.609     raeburn  8731:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8732:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8733:                     $match = 1;
1.275     raeburn  8734:                 }
                   8735:             }
                   8736:             if (defined($$types{'future'})) {
1.609     raeburn  8737:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8738:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8739:                     $match = 1;
1.275     raeburn  8740:                 }
                   8741:             }
1.609     raeburn  8742:             if ($match) {
                   8743:                 push(@{$seclists{$student}},$section);
                   8744:                 if (ref($userdata) eq 'HASH') {
                   8745:                     $$userdata{$student} = $$classlist{$student};
                   8746:                 }
                   8747:                 if (ref($statushash) eq 'HASH') {
                   8748:                     $statushash->{$student}{'st'}{$section} = $status;
                   8749:                 }
1.288     raeburn  8750:             }
1.275     raeburn  8751:         }
                   8752:     }
1.412     raeburn  8753:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8754:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8755:         my $now = time;
1.609     raeburn  8756:         my %displaystatus = ( previous => 'Expired',
                   8757:                               active   => 'Active',
                   8758:                               future   => 'Future',
                   8759:                             );
1.1075.2.36  raeburn  8760:         my (%nothide,@possdoms);
1.630     raeburn  8761:         if ($hidepriv) {
                   8762:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8763:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8764:                 if ($user !~ /:/) {
                   8765:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8766:                 } else {
                   8767:                     $nothide{$user} = 1;
                   8768:                 }
                   8769:             }
1.1075.2.36  raeburn  8770:             my @possdoms = ($cdom);
                   8771:             if ($coursehash{'checkforpriv'}) {
                   8772:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8773:             }
1.630     raeburn  8774:         }
1.439     raeburn  8775:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8776:             my $match = 0;
1.412     raeburn  8777:             my $secmatch = 0;
1.439     raeburn  8778:             my $status;
1.412     raeburn  8779:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8780:             $user =~ s/:$//;
1.439     raeburn  8781:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8782:             if ($end == -1 || $start == -1) {
                   8783:                 next;
                   8784:             }
                   8785:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8786:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8787:                 my ($uname,$udom) = split(/:/,$user);
                   8788:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8789:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8790:                         $secmatch = 1;
                   8791:                     } elsif ($usec eq '') {
1.420     albertel 8792:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8793:                             $secmatch = 1;
                   8794:                         }
                   8795:                     } else {
                   8796:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8797:                             $secmatch = 1;
                   8798:                         }
                   8799:                     }
                   8800:                     if (!$secmatch) {
                   8801:                         next;
                   8802:                     }
1.288     raeburn  8803:                 }
1.419     raeburn  8804:                 if ($usec eq '') {
                   8805:                     $usec = 'none';
                   8806:                 }
1.275     raeburn  8807:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8808:                     if ($hidepriv) {
1.1075.2.36  raeburn  8809:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8810:                             (!$nothide{$uname.':'.$udom})) {
                   8811:                             next;
                   8812:                         }
                   8813:                     }
1.503     raeburn  8814:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8815:                         $status = 'previous';
                   8816:                     } elsif ($start > $now) {
                   8817:                         $status = 'future';
                   8818:                     } else {
                   8819:                         $status = 'active';
                   8820:                     }
1.277     albertel 8821:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8822:                         if ($status eq $type) {
1.420     albertel 8823:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8824:                                 push(@{$$users{$role}{$user}},$type);
                   8825:                             }
1.288     raeburn  8826:                             $match = 1;
                   8827:                         }
                   8828:                     }
1.419     raeburn  8829:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8830:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8831: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8832:                         }
1.420     albertel 8833:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8834:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8835:                         }
1.609     raeburn  8836:                         if (ref($statushash) eq 'HASH') {
                   8837:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8838:                         }
1.275     raeburn  8839:                     }
                   8840:                 }
                   8841:             }
                   8842:         }
1.290     albertel 8843:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8844:             if ((defined($cdom)) && (defined($cnum))) {
                   8845:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8846:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8847:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8848:                     next if ($owner eq '');
                   8849:                     my ($ownername,$ownerdom);
                   8850:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8851:                         $ownername = $1;
                   8852:                         $ownerdom = $2;
                   8853:                     } else {
                   8854:                         $ownername = $owner;
                   8855:                         $ownerdom = $cdom;
                   8856:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8857:                     }
                   8858:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8859:                     if (defined($userdata) && 
1.609     raeburn  8860: 			!exists($$userdata{$owner})) {
                   8861: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8862:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8863:                             push(@{$seclists{$owner}},'none');
                   8864:                         }
                   8865:                         if (ref($statushash) eq 'HASH') {
                   8866:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8867:                         }
1.290     albertel 8868: 		    }
1.279     raeburn  8869:                 }
                   8870:             }
                   8871:         }
1.419     raeburn  8872:         foreach my $user (keys(%seclists)) {
                   8873:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8874:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8875:         }
1.275     raeburn  8876:     }
                   8877:     return;
                   8878: }
                   8879: 
1.288     raeburn  8880: sub get_user_info {
                   8881:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8882:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8883: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8884:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8885:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8886:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8887:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8888:     return;
                   8889: }
1.275     raeburn  8890: 
1.472     raeburn  8891: ###############################################
                   8892: 
                   8893: =pod
                   8894: 
                   8895: =item * &get_user_quota()
                   8896: 
1.1075.2.41  raeburn  8897: Retrieves quota assigned for storage of user files.
                   8898: Default is to report quota for portfolio files.
1.472     raeburn  8899: 
                   8900: Incoming parameters:
                   8901: 1. user's username
                   8902: 2. user's domain
1.1075.2.41  raeburn  8903: 3. quota name - portfolio, author, or course
                   8904:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  8905: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  8906:    course
1.472     raeburn  8907: 
                   8908: Returns:
1.1075.2.58  raeburn  8909: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  8910: 2. (Optional) Type of setting: custom or default
                   8911:    (individually assigned or default for user's 
                   8912:    institutional status).
                   8913: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8914:    or student - types as defined in localenroll::inst_usertypes 
                   8915:    for user's domain, which determines default quota for user.
                   8916: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8917: 
                   8918: If a value has been stored in the user's environment, 
1.536     raeburn  8919: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  8920: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8921: 
                   8922: =cut
                   8923: 
                   8924: ###############################################
                   8925: 
                   8926: 
                   8927: sub get_user_quota {
1.1075.2.42  raeburn  8928:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  8929:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8930:     if (!defined($udom)) {
                   8931:         $udom = $env{'user.domain'};
                   8932:     }
                   8933:     if (!defined($uname)) {
                   8934:         $uname = $env{'user.name'};
                   8935:     }
                   8936:     if (($udom eq '' || $uname eq '') ||
                   8937:         ($udom eq 'public') && ($uname eq 'public')) {
                   8938:         $quota = 0;
1.536     raeburn  8939:         $quotatype = 'default';
                   8940:         $defquota = 0; 
1.472     raeburn  8941:     } else {
1.536     raeburn  8942:         my $inststatus;
1.1075.2.41  raeburn  8943:         if ($quotaname eq 'course') {
                   8944:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   8945:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   8946:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   8947:             } else {
                   8948:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   8949:                 $quota = $cenv{'internal.uploadquota'};
                   8950:             }
1.536     raeburn  8951:         } else {
1.1075.2.41  raeburn  8952:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8953:                 if ($quotaname eq 'author') {
                   8954:                     $quota = $env{'environment.authorquota'};
                   8955:                 } else {
                   8956:                     $quota = $env{'environment.portfolioquota'};
                   8957:                 }
                   8958:                 $inststatus = $env{'environment.inststatus'};
                   8959:             } else {
                   8960:                 my %userenv = 
                   8961:                     &Apache::lonnet::get('environment',['portfolioquota',
                   8962:                                          'authorquota','inststatus'],$udom,$uname);
                   8963:                 my ($tmp) = keys(%userenv);
                   8964:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8965:                     if ($quotaname eq 'author') {
                   8966:                         $quota = $userenv{'authorquota'};
                   8967:                     } else {
                   8968:                         $quota = $userenv{'portfolioquota'};
                   8969:                     }
                   8970:                     $inststatus = $userenv{'inststatus'};
                   8971:                 } else {
                   8972:                     undef(%userenv);
                   8973:                 }
                   8974:             }
                   8975:         }
                   8976:         if ($quota eq '' || wantarray) {
                   8977:             if ($quotaname eq 'course') {
                   8978:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  8979:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   8980:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  8981:                     $defquota = $domdefs{$crstype.'quota'};
                   8982:                 }
                   8983:                 if ($defquota eq '') {
                   8984:                     $defquota = 500;
                   8985:                 }
1.1075.2.41  raeburn  8986:             } else {
                   8987:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   8988:             }
                   8989:             if ($quota eq '') {
                   8990:                 $quota = $defquota;
                   8991:                 $quotatype = 'default';
                   8992:             } else {
                   8993:                 $quotatype = 'custom';
                   8994:             }
1.472     raeburn  8995:         }
                   8996:     }
1.536     raeburn  8997:     if (wantarray) {
                   8998:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8999:     } else {
                   9000:         return $quota;
                   9001:     }
1.472     raeburn  9002: }
                   9003: 
                   9004: ###############################################
                   9005: 
                   9006: =pod
                   9007: 
                   9008: =item * &default_quota()
                   9009: 
1.536     raeburn  9010: Retrieves default quota assigned for storage of user portfolio files,
                   9011: given an (optional) user's institutional status.
1.472     raeburn  9012: 
                   9013: Incoming parameters:
1.1075.2.42  raeburn  9014: 
1.472     raeburn  9015: 1. domain
1.536     raeburn  9016: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9017:    status types (e.g., faculty, staff, student etc.)
                   9018:    which apply to the user for whom the default is being retrieved.
                   9019:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9020:    default quota will be returned.
                   9021: 3.  quota name - portfolio, author, or course
                   9022:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9023: 
                   9024: Returns:
1.1075.2.42  raeburn  9025: 
1.1075.2.58  raeburn  9026: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9027: 2. (Optional) institutional type which determined the value of the
                   9028:    default quota.
1.472     raeburn  9029: 
                   9030: If a value has been stored in the domain's configuration db,
                   9031: it will return that, otherwise it returns 20 (for backwards 
                   9032: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9033: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9034: 
1.536     raeburn  9035: If the user's status includes multiple types (e.g., staff and student),
                   9036: the largest default quota which applies to the user determines the
                   9037: default quota returned.
                   9038: 
1.472     raeburn  9039: =cut
                   9040: 
                   9041: ###############################################
                   9042: 
                   9043: 
                   9044: sub default_quota {
1.1075.2.41  raeburn  9045:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9046:     my ($defquota,$settingstatus);
                   9047:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9048:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9049:     my $key = 'defaultquota';
                   9050:     if ($quotaname eq 'author') {
                   9051:         $key = 'authorquota';
                   9052:     }
1.622     raeburn  9053:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9054:         if ($inststatus ne '') {
1.765     raeburn  9055:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9056:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9057:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9058:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9059:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9060:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9061:                             $settingstatus = $item;
1.1075.2.41  raeburn  9062:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9063:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9064:                             $settingstatus = $item;
                   9065:                         }
                   9066:                     }
1.1075.2.41  raeburn  9067:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9068:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9069:                         if ($defquota eq '') {
                   9070:                             $defquota = $quotahash{'quotas'}{$item};
                   9071:                             $settingstatus = $item;
                   9072:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9073:                             $defquota = $quotahash{'quotas'}{$item};
                   9074:                             $settingstatus = $item;
                   9075:                         }
1.536     raeburn  9076:                     }
                   9077:                 }
                   9078:             }
                   9079:         }
                   9080:         if ($defquota eq '') {
1.1075.2.41  raeburn  9081:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9082:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9083:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9084:                 $defquota = $quotahash{'quotas'}{'default'};
                   9085:             }
1.536     raeburn  9086:             $settingstatus = 'default';
1.1075.2.42  raeburn  9087:             if ($defquota eq '') {
                   9088:                 if ($quotaname eq 'author') {
                   9089:                     $defquota = 500;
                   9090:                 }
                   9091:             }
1.536     raeburn  9092:         }
                   9093:     } else {
                   9094:         $settingstatus = 'default';
1.1075.2.41  raeburn  9095:         if ($quotaname eq 'author') {
                   9096:             $defquota = 500;
                   9097:         } else {
                   9098:             $defquota = 20;
                   9099:         }
1.536     raeburn  9100:     }
                   9101:     if (wantarray) {
                   9102:         return ($defquota,$settingstatus);
1.472     raeburn  9103:     } else {
1.536     raeburn  9104:         return $defquota;
1.472     raeburn  9105:     }
                   9106: }
                   9107: 
1.1075.2.41  raeburn  9108: ###############################################
                   9109: 
                   9110: =pod
                   9111: 
1.1075.2.42  raeburn  9112: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9113: 
                   9114: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9115: of existing file within authoring space will cause quota for the authoring
                   9116: space to be exceeded.
                   9117: 
                   9118: Same, if upload of a file directly to a course/community via Course Editor
                   9119: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9120: 
1.1075.2.61  raeburn  9121: Inputs: 7 
1.1075.2.42  raeburn  9122: 1. username or coursenum
1.1075.2.41  raeburn  9123: 2. domain
1.1075.2.42  raeburn  9124: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9125: 4. filename of file for which action is being requested
                   9126: 5. filesize (kB) of file
                   9127: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9128: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9129: 
                   9130: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9131:          otherwise return null.
                   9132: 
1.1075.2.42  raeburn  9133: =back
                   9134: 
1.1075.2.41  raeburn  9135: =cut
                   9136: 
1.1075.2.42  raeburn  9137: sub excess_filesize_warning {
1.1075.2.59  raeburn  9138:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9139:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9140:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9141:     if ($context eq 'author') {
                   9142:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9143:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9144:     } else {
                   9145:         foreach my $subdir ('docs','supplemental') {
                   9146:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9147:         }
                   9148:     }
1.1075.2.41  raeburn  9149:     $disk_quota = int($disk_quota * 1000);
                   9150:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9151:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9152:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9153:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9154:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9155:                             $disk_quota,$current_disk_usage).
                   9156:                '</p>';
                   9157:     }
                   9158:     return;
                   9159: }
                   9160: 
                   9161: ###############################################
                   9162: 
                   9163: 
1.384     raeburn  9164: sub get_secgrprole_info {
                   9165:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9166:     my %sections_count = &get_sections($cdom,$cnum);
                   9167:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9168:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9169:     my @groups = sort(keys(%curr_groups));
                   9170:     my $allroles = [];
                   9171:     my $rolehash;
                   9172:     my $accesshash = {
                   9173:                      active => 'Currently has access',
                   9174:                      future => 'Will have future access',
                   9175:                      previous => 'Previously had access',
                   9176:                   };
                   9177:     if ($needroles) {
                   9178:         $rolehash = {'all' => 'all'};
1.385     albertel 9179:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9180: 	if (&Apache::lonnet::error(%user_roles)) {
                   9181: 	    undef(%user_roles);
                   9182: 	}
                   9183:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9184:             my ($role)=split(/\:/,$item,2);
                   9185:             if ($role eq 'cr') { next; }
                   9186:             if ($role =~ /^cr/) {
                   9187:                 $$rolehash{$role} = (split('/',$role))[3];
                   9188:             } else {
                   9189:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9190:             }
                   9191:         }
                   9192:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9193:             push(@{$allroles},$key);
                   9194:         }
                   9195:         push (@{$allroles},'st');
                   9196:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9197:     }
                   9198:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9199: }
                   9200: 
1.555     raeburn  9201: sub user_picker {
1.994     raeburn  9202:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9203:     my $currdom = $dom;
                   9204:     my %curr_selected = (
                   9205:                         srchin => 'dom',
1.580     raeburn  9206:                         srchby => 'lastname',
1.555     raeburn  9207:                       );
                   9208:     my $srchterm;
1.625     raeburn  9209:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9210:         if ($srch->{'srchby'} ne '') {
                   9211:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9212:         }
                   9213:         if ($srch->{'srchin'} ne '') {
                   9214:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9215:         }
                   9216:         if ($srch->{'srchtype'} ne '') {
                   9217:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9218:         }
                   9219:         if ($srch->{'srchdomain'} ne '') {
                   9220:             $currdom = $srch->{'srchdomain'};
                   9221:         }
                   9222:         $srchterm = $srch->{'srchterm'};
                   9223:     }
                   9224:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9225:                     'usr'       => 'Search criteria',
1.563     raeburn  9226:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9227:                     'uname'     => 'username',
                   9228:                     'lastname'  => 'last name',
1.555     raeburn  9229:                     'lastfirst' => 'last name, first name',
1.558     albertel 9230:                     'crs'       => 'in this course',
1.576     raeburn  9231:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9232:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9233:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9234:                     'exact'     => 'is',
                   9235:                     'contains'  => 'contains',
1.569     raeburn  9236:                     'begins'    => 'begins with',
1.571     raeburn  9237:                     'youm'      => "You must include some text to search for.",
                   9238:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9239:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9240:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9241:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9242:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9243:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9244:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9245:                                        );
1.563     raeburn  9246:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9247:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9248: 
                   9249:     my @srchins = ('crs','dom','alc','instd');
                   9250: 
                   9251:     foreach my $option (@srchins) {
                   9252:         # FIXME 'alc' option unavailable until 
                   9253:         #       loncreateuser::print_user_query_page()
                   9254:         #       has been completed.
                   9255:         next if ($option eq 'alc');
1.880     raeburn  9256:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9257:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9258:         if ($curr_selected{'srchin'} eq $option) {
                   9259:             $srchinsel .= ' 
                   9260:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9261:         } else {
                   9262:             $srchinsel .= '
                   9263:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9264:         }
1.555     raeburn  9265:     }
1.563     raeburn  9266:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9267: 
                   9268:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9269:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9270:         if ($curr_selected{'srchby'} eq $option) {
                   9271:             $srchbysel .= '
                   9272:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9273:         } else {
                   9274:             $srchbysel .= '
                   9275:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9276:          }
                   9277:     }
                   9278:     $srchbysel .= "\n  </select>\n";
                   9279: 
                   9280:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9281:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9282:         if ($curr_selected{'srchtype'} eq $option) {
                   9283:             $srchtypesel .= '
                   9284:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9285:         } else {
                   9286:             $srchtypesel .= '
                   9287:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9288:         }
                   9289:     }
                   9290:     $srchtypesel .= "\n  </select>\n";
                   9291: 
1.558     albertel 9292:     my ($newuserscript,$new_user_create);
1.994     raeburn  9293:     my $context_dom = $env{'request.role.domain'};
                   9294:     if ($context eq 'requestcrs') {
                   9295:         if ($env{'form.coursedom'} ne '') { 
                   9296:             $context_dom = $env{'form.coursedom'};
                   9297:         }
                   9298:     }
1.556     raeburn  9299:     if ($forcenewuser) {
1.576     raeburn  9300:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9301:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9302:                 if ($cancreate) {
                   9303:                     $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>';
                   9304:                 } else {
1.799     bisitz   9305:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9306:                     my %usertypetext = (
                   9307:                         official   => 'institutional',
                   9308:                         unofficial => 'non-institutional',
                   9309:                     );
1.799     bisitz   9310:                     $new_user_create = '<p class="LC_warning">'
                   9311:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9312:                                       .' '
                   9313:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9314:                                           ,'<a href="'.$helplink.'">','</a>')
                   9315:                                       .'</p><br />';
1.627     raeburn  9316:                 }
1.576     raeburn  9317:             }
                   9318:         }
                   9319: 
1.556     raeburn  9320:         $newuserscript = <<"ENDSCRIPT";
                   9321: 
1.570     raeburn  9322: function setSearch(createnew,callingForm) {
1.556     raeburn  9323:     if (createnew == 1) {
1.570     raeburn  9324:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9325:             if (callingForm.srchby.options[i].value == 'uname') {
                   9326:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9327:             }
                   9328:         }
1.570     raeburn  9329:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9330:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9331: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9332:             }
                   9333:         }
1.570     raeburn  9334:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9335:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9336:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9337:             }
                   9338:         }
1.570     raeburn  9339:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9340:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9341:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9342:             }
                   9343:         }
                   9344:     }
                   9345: }
                   9346: ENDSCRIPT
1.558     albertel 9347: 
1.556     raeburn  9348:     }
                   9349: 
1.555     raeburn  9350:     my $output = <<"END_BLOCK";
1.556     raeburn  9351: <script type="text/javascript">
1.824     bisitz   9352: // <![CDATA[
1.570     raeburn  9353: function validateEntry(callingForm) {
1.558     albertel 9354: 
1.556     raeburn  9355:     var checkok = 1;
1.558     albertel 9356:     var srchin;
1.570     raeburn  9357:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9358: 	if ( callingForm.srchin[i].checked ) {
                   9359: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9360: 	}
                   9361:     }
                   9362: 
1.570     raeburn  9363:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9364:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9365:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9366:     var srchterm =  callingForm.srchterm.value;
                   9367:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9368:     var msg = "";
                   9369: 
                   9370:     if (srchterm == "") {
                   9371:         checkok = 0;
1.571     raeburn  9372:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9373:     }
                   9374: 
1.569     raeburn  9375:     if (srchtype== 'begins') {
                   9376:         if (srchterm.length < 2) {
                   9377:             checkok = 0;
1.571     raeburn  9378:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9379:         }
                   9380:     }
                   9381: 
1.556     raeburn  9382:     if (srchtype== 'contains') {
                   9383:         if (srchterm.length < 3) {
                   9384:             checkok = 0;
1.571     raeburn  9385:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9386:         }
                   9387:     }
                   9388:     if (srchin == 'instd') {
                   9389:         if (srchdomain == '') {
                   9390:             checkok = 0;
1.571     raeburn  9391:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9392:         }
                   9393:     }
                   9394:     if (srchin == 'dom') {
                   9395:         if (srchdomain == '') {
                   9396:             checkok = 0;
1.571     raeburn  9397:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9398:         }
                   9399:     }
                   9400:     if (srchby == 'lastfirst') {
                   9401:         if (srchterm.indexOf(",") == -1) {
                   9402:             checkok = 0;
1.571     raeburn  9403:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9404:         }
                   9405:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9406:             checkok = 0;
1.571     raeburn  9407:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9408:         }
                   9409:     }
                   9410:     if (checkok == 0) {
1.571     raeburn  9411:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9412:         return;
                   9413:     }
                   9414:     if (checkok == 1) {
1.570     raeburn  9415:         callingForm.submit();
1.556     raeburn  9416:     }
                   9417: }
                   9418: 
                   9419: $newuserscript
                   9420: 
1.824     bisitz   9421: // ]]>
1.556     raeburn  9422: </script>
1.558     albertel 9423: 
                   9424: $new_user_create
                   9425: 
1.555     raeburn  9426: END_BLOCK
1.558     albertel 9427: 
1.876     raeburn  9428:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9429:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9430:                $domform.
                   9431:                &Apache::lonhtmlcommon::row_closure().
                   9432:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9433:                $srchbysel.
                   9434:                $srchtypesel. 
                   9435:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9436:                $srchinsel.
                   9437:                &Apache::lonhtmlcommon::row_closure(1). 
                   9438:                &Apache::lonhtmlcommon::end_pick_box().
                   9439:                '<br />';
1.555     raeburn  9440:     return $output;
                   9441: }
                   9442: 
1.612     raeburn  9443: sub user_rule_check {
1.615     raeburn  9444:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9445:     my $response;
                   9446:     if (ref($usershash) eq 'HASH') {
                   9447:         foreach my $user (keys(%{$usershash})) {
                   9448:             my ($uname,$udom) = split(/:/,$user);
                   9449:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9450:             my ($id,$newuser);
1.612     raeburn  9451:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9452:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9453:                 $id = $usershash->{$user}->{'id'};
                   9454:             }
                   9455:             my $inst_response;
                   9456:             if (ref($checks) eq 'HASH') {
                   9457:                 if (defined($checks->{'username'})) {
1.615     raeburn  9458:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9459:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9460:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9461:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9462:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9463:                 }
1.615     raeburn  9464:             } else {
                   9465:                 ($inst_response,%{$inst_results->{$user}}) =
                   9466:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9467:                 return;
1.612     raeburn  9468:             }
1.615     raeburn  9469:             if (!$got_rules->{$udom}) {
1.612     raeburn  9470:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9471:                                                   ['usercreation'],$udom);
                   9472:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9473:                     foreach my $item ('username','id') {
1.612     raeburn  9474:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9475:                             $$curr_rules{$udom}{$item} = 
                   9476:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9477:                         }
                   9478:                     }
                   9479:                 }
1.615     raeburn  9480:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9481:             }
1.612     raeburn  9482:             foreach my $item (keys(%{$checks})) {
                   9483:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9484:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9485:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9486:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9487:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9488:                                 if ($rule_check{$rule}) {
                   9489:                                     $$rulematch{$user}{$item} = $rule;
                   9490:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9491:                                         if (ref($inst_results) eq 'HASH') {
                   9492:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9493:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9494:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9495:                                                 }
1.612     raeburn  9496:                                             }
                   9497:                                         }
1.615     raeburn  9498:                                     }
                   9499:                                     last;
1.585     raeburn  9500:                                 }
                   9501:                             }
                   9502:                         }
                   9503:                     }
                   9504:                 }
                   9505:             }
                   9506:         }
                   9507:     }
1.612     raeburn  9508:     return;
                   9509: }
                   9510: 
                   9511: sub user_rule_formats {
                   9512:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9513:     my %text = ( 
                   9514:                  'username' => 'Usernames',
                   9515:                  'id'       => 'IDs',
                   9516:                );
                   9517:     my $output;
                   9518:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9519:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9520:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9521:             $output = '<br />'.
                   9522:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9523:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9524:                       ' <ul>';
1.612     raeburn  9525:             foreach my $rule (@{$ruleorder}) {
                   9526:                 if (ref($curr_rules) eq 'ARRAY') {
                   9527:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9528:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9529:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9530:                                         $rules->{$rule}{'desc'}.'</li>';
                   9531:                         }
                   9532:                     }
                   9533:                 }
                   9534:             }
                   9535:             $output .= '</ul>';
                   9536:         }
                   9537:     }
                   9538:     return $output;
                   9539: }
                   9540: 
                   9541: sub instrule_disallow_msg {
1.615     raeburn  9542:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9543:     my $response;
                   9544:     my %text = (
                   9545:                   item   => 'username',
                   9546:                   items  => 'usernames',
                   9547:                   match  => 'matches',
                   9548:                   do     => 'does',
                   9549:                   action => 'a username',
                   9550:                   one    => 'one',
                   9551:                );
                   9552:     if ($count > 1) {
                   9553:         $text{'item'} = 'usernames';
                   9554:         $text{'match'} ='match';
                   9555:         $text{'do'} = 'do';
                   9556:         $text{'action'} = 'usernames',
                   9557:         $text{'one'} = 'ones';
                   9558:     }
                   9559:     if ($checkitem eq 'id') {
                   9560:         $text{'items'} = 'IDs';
                   9561:         $text{'item'} = 'ID';
                   9562:         $text{'action'} = 'an ID';
1.615     raeburn  9563:         if ($count > 1) {
                   9564:             $text{'item'} = 'IDs';
                   9565:             $text{'action'} = 'IDs';
                   9566:         }
1.612     raeburn  9567:     }
1.674     bisitz   9568:     $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  9569:     if ($mode eq 'upload') {
                   9570:         if ($checkitem eq 'username') {
                   9571:             $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'}.");
                   9572:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9573:             $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  9574:         }
1.669     raeburn  9575:     } elsif ($mode eq 'selfcreate') {
                   9576:         if ($checkitem eq 'id') {
                   9577:             $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.");
                   9578:         }
1.615     raeburn  9579:     } else {
                   9580:         if ($checkitem eq 'username') {
                   9581:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9582:         } elsif ($checkitem eq 'id') {
                   9583:             $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.");
                   9584:         }
1.612     raeburn  9585:     }
                   9586:     return $response;
1.585     raeburn  9587: }
                   9588: 
1.624     raeburn  9589: sub personal_data_fieldtitles {
                   9590:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9591:                         id => 'Student/Employee ID',
                   9592:                         permanentemail => 'E-mail address',
                   9593:                         lastname => 'Last Name',
                   9594:                         firstname => 'First Name',
                   9595:                         middlename => 'Middle Name',
                   9596:                         generation => 'Generation',
                   9597:                         gen => 'Generation',
1.765     raeburn  9598:                         inststatus => 'Affiliation',
1.624     raeburn  9599:                    );
                   9600:     return %fieldtitles;
                   9601: }
                   9602: 
1.642     raeburn  9603: sub sorted_inst_types {
                   9604:     my ($dom) = @_;
1.1075.2.70  raeburn  9605:     my ($usertypes,$order);
                   9606:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9607:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9608:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9609:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9610:     } else {
                   9611:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9612:     }
1.642     raeburn  9613:     my $othertitle = &mt('All users');
                   9614:     if ($env{'request.course.id'}) {
1.668     raeburn  9615:         $othertitle  = &mt('Any users');
1.642     raeburn  9616:     }
                   9617:     my @types;
                   9618:     if (ref($order) eq 'ARRAY') {
                   9619:         @types = @{$order};
                   9620:     }
                   9621:     if (@types == 0) {
                   9622:         if (ref($usertypes) eq 'HASH') {
                   9623:             @types = sort(keys(%{$usertypes}));
                   9624:         }
                   9625:     }
                   9626:     if (keys(%{$usertypes}) > 0) {
                   9627:         $othertitle = &mt('Other users');
                   9628:     }
                   9629:     return ($othertitle,$usertypes,\@types);
                   9630: }
                   9631: 
1.645     raeburn  9632: sub get_institutional_codes {
                   9633:     my ($settings,$allcourses,$LC_code) = @_;
                   9634: # Get complete list of course sections to update
                   9635:     my @currsections = ();
                   9636:     my @currxlists = ();
                   9637:     my $coursecode = $$settings{'internal.coursecode'};
                   9638: 
                   9639:     if ($$settings{'internal.sectionnums'} ne '') {
                   9640:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9641:     }
                   9642: 
                   9643:     if ($$settings{'internal.crosslistings'} ne '') {
                   9644:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9645:     }
                   9646: 
                   9647:     if (@currxlists > 0) {
                   9648:         foreach (@currxlists) {
                   9649:             if (m/^([^:]+):(\w*)$/) {
                   9650:                 unless (grep/^$1$/,@{$allcourses}) {
                   9651:                     push @{$allcourses},$1;
                   9652:                     $$LC_code{$1} = $2;
                   9653:                 }
                   9654:             }
                   9655:         }
                   9656:     }
                   9657:  
                   9658:     if (@currsections > 0) {
                   9659:         foreach (@currsections) {
                   9660:             if (m/^(\w+):(\w*)$/) {
                   9661:                 my $sec = $coursecode.$1;
                   9662:                 my $lc_sec = $2;
                   9663:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9664:                     push @{$allcourses},$sec;
                   9665:                     $$LC_code{$sec} = $lc_sec;
                   9666:                 }
                   9667:             }
                   9668:         }
                   9669:     }
                   9670:     return;
                   9671: }
                   9672: 
1.971     raeburn  9673: sub get_standard_codeitems {
                   9674:     return ('Year','Semester','Department','Number','Section');
                   9675: }
                   9676: 
1.112     bowersj2 9677: =pod
                   9678: 
1.780     raeburn  9679: =head1 Slot Helpers
                   9680: 
                   9681: =over 4
                   9682: 
                   9683: =item * sorted_slots()
                   9684: 
1.1040    raeburn  9685: Sorts an array of slot names in order of an optional sort key,
                   9686: default sort is by slot start time (earliest first). 
1.780     raeburn  9687: 
                   9688: Inputs:
                   9689: 
                   9690: =over 4
                   9691: 
                   9692: slotsarr  - Reference to array of unsorted slot names.
                   9693: 
                   9694: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9695: 
1.1040    raeburn  9696: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9697: 
1.549     albertel 9698: =back
                   9699: 
1.780     raeburn  9700: Returns:
                   9701: 
                   9702: =over 4
                   9703: 
1.1040    raeburn  9704: sorted   - An array of slot names sorted by a specified sort key 
                   9705:            (default sort key is start time of the slot).
1.780     raeburn  9706: 
                   9707: =back
                   9708: 
                   9709: =cut
                   9710: 
                   9711: 
                   9712: sub sorted_slots {
1.1040    raeburn  9713:     my ($slotsarr,$slots,$sortkey) = @_;
                   9714:     if ($sortkey eq '') {
                   9715:         $sortkey = 'starttime';
                   9716:     }
1.780     raeburn  9717:     my @sorted;
                   9718:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9719:         @sorted =
                   9720:             sort {
                   9721:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9722:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9723:                      }
                   9724:                      if (ref($slots->{$a})) { return -1;}
                   9725:                      if (ref($slots->{$b})) { return 1;}
                   9726:                      return 0;
                   9727:                  } @{$slotsarr};
                   9728:     }
                   9729:     return @sorted;
                   9730: }
                   9731: 
1.1040    raeburn  9732: =pod
                   9733: 
                   9734: =item * get_future_slots()
                   9735: 
                   9736: Inputs:
                   9737: 
                   9738: =over 4
                   9739: 
                   9740: cnum - course number
                   9741: 
                   9742: cdom - course domain
                   9743: 
                   9744: now - current UNIX time
                   9745: 
                   9746: symb - optional symb
                   9747: 
                   9748: =back
                   9749: 
                   9750: Returns:
                   9751: 
                   9752: =over 4
                   9753: 
                   9754: sorted_reservable - ref to array of student_schedulable slots currently 
                   9755:                     reservable, ordered by end date of reservation period.
                   9756: 
                   9757: reservable_now - ref to hash of student_schedulable slots currently
                   9758:                  reservable.
                   9759: 
                   9760:     Keys in inner hash are:
                   9761:     (a) symb: either blank or symb to which slot use is restricted.
                   9762:     (b) endreserve: end date of reservation period. 
                   9763: 
                   9764: sorted_future - ref to array of student_schedulable slots reservable in
                   9765:                 the future, ordered by start date of reservation period.
                   9766: 
                   9767: future_reservable - ref to hash of student_schedulable slots reservable
                   9768:                     in the future.
                   9769: 
                   9770:     Keys in inner hash are:
                   9771:     (a) symb: either blank or symb to which slot use is restricted.
                   9772:     (b) startreserve:  start date of reservation period.
                   9773: 
                   9774: =back
                   9775: 
                   9776: =cut
                   9777: 
                   9778: sub get_future_slots {
                   9779:     my ($cnum,$cdom,$now,$symb) = @_;
                   9780:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9781:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9782:     foreach my $slot (keys(%slots)) {
                   9783:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9784:         if ($symb) {
                   9785:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9786:                      ($slots{$slot}->{'symb'} ne $symb));
                   9787:         }
                   9788:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9789:             ($slots{$slot}->{'endtime'} > $now)) {
                   9790:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9791:                 my $userallowed = 0;
                   9792:                 if ($slots{$slot}->{'allowedsections'}) {
                   9793:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9794:                     if (!defined($env{'request.role.sec'})
                   9795:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9796:                         $userallowed=1;
                   9797:                     } else {
                   9798:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9799:                             $userallowed=1;
                   9800:                         }
                   9801:                     }
                   9802:                     unless ($userallowed) {
                   9803:                         if (defined($env{'request.course.groups'})) {
                   9804:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9805:                             foreach my $group (@groups) {
                   9806:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9807:                                     $userallowed=1;
                   9808:                                     last;
                   9809:                                 }
                   9810:                             }
                   9811:                         }
                   9812:                     }
                   9813:                 }
                   9814:                 if ($slots{$slot}->{'allowedusers'}) {
                   9815:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9816:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9817:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9818:                         $userallowed = 1;
                   9819:                     }
                   9820:                 }
                   9821:                 next unless($userallowed);
                   9822:             }
                   9823:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9824:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9825:             my $symb = $slots{$slot}->{'symb'};
                   9826:             if (($startreserve < $now) &&
                   9827:                 (!$endreserve || $endreserve > $now)) {
                   9828:                 my $lastres = $endreserve;
                   9829:                 if (!$lastres) {
                   9830:                     $lastres = $slots{$slot}->{'starttime'};
                   9831:                 }
                   9832:                 $reservable_now{$slot} = {
                   9833:                                            symb       => $symb,
                   9834:                                            endreserve => $lastres
                   9835:                                          };
                   9836:             } elsif (($startreserve > $now) &&
                   9837:                      (!$endreserve || $endreserve > $startreserve)) {
                   9838:                 $future_reservable{$slot} = {
                   9839:                                               symb         => $symb,
                   9840:                                               startreserve => $startreserve
                   9841:                                             };
                   9842:             }
                   9843:         }
                   9844:     }
                   9845:     my @unsorted_reservable = keys(%reservable_now);
                   9846:     if (@unsorted_reservable > 0) {
                   9847:         @sorted_reservable = 
                   9848:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9849:     }
                   9850:     my @unsorted_future = keys(%future_reservable);
                   9851:     if (@unsorted_future > 0) {
                   9852:         @sorted_future =
                   9853:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9854:     }
                   9855:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9856: }
1.780     raeburn  9857: 
                   9858: =pod
                   9859: 
1.1057    foxr     9860: =back
                   9861: 
1.549     albertel 9862: =head1 HTTP Helpers
                   9863: 
                   9864: =over 4
                   9865: 
1.648     raeburn  9866: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9867: 
1.258     albertel 9868: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9869: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9870: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9871: 
                   9872: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9873: $possible_names is an ref to an array of form element names.  As an example:
                   9874: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9875: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9876: 
                   9877: =cut
1.1       albertel 9878: 
1.6       albertel 9879: sub get_unprocessed_cgi {
1.25      albertel 9880:   my ($query,$possible_names)= @_;
1.26      matthew  9881:   # $Apache::lonxml::debug=1;
1.356     albertel 9882:   foreach my $pair (split(/&/,$query)) {
                   9883:     my ($name, $value) = split(/=/,$pair);
1.369     www      9884:     $name = &unescape($name);
1.25      albertel 9885:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9886:       $value =~ tr/+/ /;
                   9887:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9888:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9889:     }
1.16      harris41 9890:   }
1.6       albertel 9891: }
                   9892: 
1.112     bowersj2 9893: =pod
                   9894: 
1.648     raeburn  9895: =item * &cacheheader() 
1.112     bowersj2 9896: 
                   9897: returns cache-controlling header code
                   9898: 
                   9899: =cut
                   9900: 
1.7       albertel 9901: sub cacheheader {
1.258     albertel 9902:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9903:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9904:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9905:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9906:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9907:     return $output;
1.7       albertel 9908: }
                   9909: 
1.112     bowersj2 9910: =pod
                   9911: 
1.648     raeburn  9912: =item * &no_cache($r) 
1.112     bowersj2 9913: 
                   9914: specifies header code to not have cache
                   9915: 
                   9916: =cut
                   9917: 
1.9       albertel 9918: sub no_cache {
1.216     albertel 9919:     my ($r) = @_;
                   9920:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9921: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9922:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9923:     $r->no_cache(1);
                   9924:     $r->header_out("Expires" => $date);
                   9925:     $r->header_out("Pragma" => "no-cache");
1.123     www      9926: }
                   9927: 
                   9928: sub content_type {
1.181     albertel 9929:     my ($r,$type,$charset) = @_;
1.299     foxr     9930:     if ($r) {
                   9931: 	#  Note that printout.pl calls this with undef for $r.
                   9932: 	&no_cache($r);
                   9933:     }
1.258     albertel 9934:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9935:     unless ($charset) {
                   9936: 	$charset=&Apache::lonlocal::current_encoding;
                   9937:     }
                   9938:     if ($charset) { $type.='; charset='.$charset; }
                   9939:     if ($r) {
                   9940: 	$r->content_type($type);
                   9941:     } else {
                   9942: 	print("Content-type: $type\n\n");
                   9943:     }
1.9       albertel 9944: }
1.25      albertel 9945: 
1.112     bowersj2 9946: =pod
                   9947: 
1.648     raeburn  9948: =item * &add_to_env($name,$value) 
1.112     bowersj2 9949: 
1.258     albertel 9950: adds $name to the %env hash with value
1.112     bowersj2 9951: $value, if $name already exists, the entry is converted to an array
                   9952: reference and $value is added to the array.
                   9953: 
                   9954: =cut
                   9955: 
1.25      albertel 9956: sub add_to_env {
                   9957:   my ($name,$value)=@_;
1.258     albertel 9958:   if (defined($env{$name})) {
                   9959:     if (ref($env{$name})) {
1.25      albertel 9960:       #already have multiple values
1.258     albertel 9961:       push(@{ $env{$name} },$value);
1.25      albertel 9962:     } else {
                   9963:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9964:       my $first=$env{$name};
                   9965:       undef($env{$name});
                   9966:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9967:     }
                   9968:   } else {
1.258     albertel 9969:     $env{$name}=$value;
1.25      albertel 9970:   }
1.31      albertel 9971: }
1.149     albertel 9972: 
                   9973: =pod
                   9974: 
1.648     raeburn  9975: =item * &get_env_multiple($name) 
1.149     albertel 9976: 
1.258     albertel 9977: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9978: values may be defined and end up as an array ref.
                   9979: 
                   9980: returns an array of values
                   9981: 
                   9982: =cut
                   9983: 
                   9984: sub get_env_multiple {
                   9985:     my ($name) = @_;
                   9986:     my @values;
1.258     albertel 9987:     if (defined($env{$name})) {
1.149     albertel 9988:         # exists is it an array
1.258     albertel 9989:         if (ref($env{$name})) {
                   9990:             @values=@{ $env{$name} };
1.149     albertel 9991:         } else {
1.258     albertel 9992:             $values[0]=$env{$name};
1.149     albertel 9993:         }
                   9994:     }
                   9995:     return(@values);
                   9996: }
                   9997: 
1.660     raeburn  9998: sub ask_for_embedded_content {
                   9999:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10000:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10001:         %currsubfile,%unused,$rem);
1.1071    raeburn  10002:     my $counter = 0;
                   10003:     my $numnew = 0;
1.987     raeburn  10004:     my $numremref = 0;
                   10005:     my $numinvalid = 0;
                   10006:     my $numpathchg = 0;
                   10007:     my $numexisting = 0;
1.1071    raeburn  10008:     my $numunused = 0;
                   10009:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10010:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10011:     my $heading = &mt('Upload embedded files');
                   10012:     my $buttontext = &mt('Upload');
                   10013: 
1.1075.2.11  raeburn  10014:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10015:         if ($actionurl eq '/adm/dependencies') {
                   10016:             $navmap = Apache::lonnavmaps::navmap->new();
                   10017:         }
                   10018:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10019:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10020:     }
1.1075.2.35  raeburn  10021:     if (($actionurl eq '/adm/portfolio') ||
                   10022:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10023:         my $current_path='/';
                   10024:         if ($env{'form.currentpath'}) {
                   10025:             $current_path = $env{'form.currentpath'};
                   10026:         }
                   10027:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10028:             $udom = $cdom;
                   10029:             $uname = $cnum;
1.984     raeburn  10030:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10031:         } else {
                   10032:             $udom = $env{'user.domain'};
                   10033:             $uname = $env{'user.name'};
                   10034:             $url = '/userfiles/portfolio';
                   10035:         }
1.987     raeburn  10036:         $toplevel = $url.'/';
1.984     raeburn  10037:         $url .= $current_path;
                   10038:         $getpropath = 1;
1.987     raeburn  10039:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10040:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10041:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10042:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10043:         $toplevel = $url;
1.984     raeburn  10044:         if ($rest ne '') {
1.987     raeburn  10045:             $url .= $rest;
                   10046:         }
                   10047:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10048:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10049:             $url = $args->{'docs_url'};
                   10050:             $toplevel = $url;
1.1075.2.11  raeburn  10051:             if ($args->{'context'} eq 'paste') {
                   10052:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10053:                 ($path) =
                   10054:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10055:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10056:                 $fileloc =~ s{^/}{};
                   10057:             }
1.1071    raeburn  10058:         }
                   10059:     } elsif ($actionurl eq '/adm/dependencies') {
                   10060:         if ($env{'request.course.id'} ne '') {
                   10061:             if (ref($args) eq 'HASH') {
                   10062:                 $url = $args->{'docs_url'};
                   10063:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10064:                 $toplevel = $url;
                   10065:                 unless ($toplevel =~ m{^/}) {
                   10066:                     $toplevel = "/$url";
                   10067:                 }
1.1075.2.11  raeburn  10068:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10069:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10070:                     $path = $1;
                   10071:                 } else {
                   10072:                     ($path) =
                   10073:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10074:                 }
1.1075.2.79  raeburn  10075:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10076:                     $fileloc = $toplevel;
                   10077:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10078:                     my ($udom,$uname,$fname) =
                   10079:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10080:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10081:                 } else {
                   10082:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10083:                 }
1.1071    raeburn  10084:                 $fileloc =~ s{^/}{};
                   10085:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10086:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10087:             }
1.987     raeburn  10088:         }
1.1075.2.35  raeburn  10089:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10090:         $udom = $cdom;
                   10091:         $uname = $cnum;
                   10092:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10093:         $toplevel = $url;
                   10094:         $path = $url;
                   10095:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10096:         $fileloc =~ s{^/}{};
                   10097:     }
                   10098:     foreach my $file (keys(%{$allfiles})) {
                   10099:         my $embed_file;
                   10100:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10101:             $embed_file = $1;
                   10102:         } else {
                   10103:             $embed_file = $file;
                   10104:         }
1.1075.2.55  raeburn  10105:         my ($absolutepath,$cleaned_file);
                   10106:         if ($embed_file =~ m{^\w+://}) {
                   10107:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10108:             $newfiles{$cleaned_file} = 1;
                   10109:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10110:         } else {
1.1075.2.55  raeburn  10111:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10112:             if ($embed_file =~ m{^/}) {
                   10113:                 $absolutepath = $embed_file;
                   10114:             }
1.1075.2.47  raeburn  10115:             if ($cleaned_file =~ m{/}) {
                   10116:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10117:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10118:                 my $item = $fname;
                   10119:                 if ($path ne '') {
                   10120:                     $item = $path.'/'.$fname;
                   10121:                     $subdependencies{$path}{$fname} = 1;
                   10122:                 } else {
                   10123:                     $dependencies{$item} = 1;
                   10124:                 }
                   10125:                 if ($absolutepath) {
                   10126:                     $mapping{$item} = $absolutepath;
                   10127:                 } else {
                   10128:                     $mapping{$item} = $embed_file;
                   10129:                 }
                   10130:             } else {
                   10131:                 $dependencies{$embed_file} = 1;
                   10132:                 if ($absolutepath) {
1.1075.2.47  raeburn  10133:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10134:                 } else {
1.1075.2.47  raeburn  10135:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10136:                 }
                   10137:             }
1.984     raeburn  10138:         }
                   10139:     }
1.1071    raeburn  10140:     my $dirptr = 16384;
1.984     raeburn  10141:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10142:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10143:         if (($actionurl eq '/adm/portfolio') ||
                   10144:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10145:             my ($sublistref,$listerror) =
                   10146:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10147:             if (ref($sublistref) eq 'ARRAY') {
                   10148:                 foreach my $line (@{$sublistref}) {
                   10149:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10150:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10151:                 }
1.984     raeburn  10152:             }
1.987     raeburn  10153:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10154:             if (opendir(my $dir,$url.'/'.$path)) {
                   10155:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10156:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10157:             }
1.1075.2.11  raeburn  10158:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10159:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10160:                   ($args->{'context'} eq 'paste')) ||
                   10161:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10162:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10163:                 my $dir;
                   10164:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10165:                     $dir = $fileloc;
                   10166:                 } else {
                   10167:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10168:                 }
1.1071    raeburn  10169:                 if ($dir ne '') {
                   10170:                     my ($sublistref,$listerror) =
                   10171:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10172:                     if (ref($sublistref) eq 'ARRAY') {
                   10173:                         foreach my $line (@{$sublistref}) {
                   10174:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10175:                                 undef,$mtime)=split(/\&/,$line,12);
                   10176:                             unless (($testdir&$dirptr) ||
                   10177:                                     ($file_name =~ /^\.\.?$/)) {
                   10178:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10179:                             }
                   10180:                         }
                   10181:                     }
                   10182:                 }
1.984     raeburn  10183:             }
                   10184:         }
                   10185:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10186:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10187:                 my $item = $path.'/'.$file;
                   10188:                 unless ($mapping{$item} eq $item) {
                   10189:                     $pathchanges{$item} = 1;
                   10190:                 }
                   10191:                 $existing{$item} = 1;
                   10192:                 $numexisting ++;
                   10193:             } else {
                   10194:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10195:             }
                   10196:         }
1.1071    raeburn  10197:         if ($actionurl eq '/adm/dependencies') {
                   10198:             foreach my $path (keys(%currsubfile)) {
                   10199:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10200:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10201:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10202:                              next if (($rem ne '') &&
                   10203:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10204:                                        (ref($navmap) &&
                   10205:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10206:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10207:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10208:                              $unused{$path.'/'.$file} = 1; 
                   10209:                          }
                   10210:                     }
                   10211:                 }
                   10212:             }
                   10213:         }
1.984     raeburn  10214:     }
1.987     raeburn  10215:     my %currfile;
1.1075.2.35  raeburn  10216:     if (($actionurl eq '/adm/portfolio') ||
                   10217:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10218:         my ($dirlistref,$listerror) =
                   10219:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10220:         if (ref($dirlistref) eq 'ARRAY') {
                   10221:             foreach my $line (@{$dirlistref}) {
                   10222:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10223:                 $currfile{$file_name} = 1;
                   10224:             }
1.984     raeburn  10225:         }
1.987     raeburn  10226:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10227:         if (opendir(my $dir,$url)) {
1.987     raeburn  10228:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10229:             map {$currfile{$_} = 1;} @dir_list;
                   10230:         }
1.1075.2.11  raeburn  10231:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10232:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10233:               ($args->{'context'} eq 'paste')) ||
                   10234:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10235:         if ($env{'request.course.id'} ne '') {
                   10236:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10237:             if ($dir ne '') {
                   10238:                 my ($dirlistref,$listerror) =
                   10239:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10240:                 if (ref($dirlistref) eq 'ARRAY') {
                   10241:                     foreach my $line (@{$dirlistref}) {
                   10242:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10243:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10244:                         unless (($testdir&$dirptr) ||
                   10245:                                 ($file_name =~ /^\.\.?$/)) {
                   10246:                             $currfile{$file_name} = [$size,$mtime];
                   10247:                         }
                   10248:                     }
                   10249:                 }
                   10250:             }
                   10251:         }
1.984     raeburn  10252:     }
                   10253:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10254:         if (exists($currfile{$file})) {
1.987     raeburn  10255:             unless ($mapping{$file} eq $file) {
                   10256:                 $pathchanges{$file} = 1;
                   10257:             }
                   10258:             $existing{$file} = 1;
                   10259:             $numexisting ++;
                   10260:         } else {
1.984     raeburn  10261:             $newfiles{$file} = 1;
                   10262:         }
                   10263:     }
1.1071    raeburn  10264:     foreach my $file (keys(%currfile)) {
                   10265:         unless (($file eq $filename) ||
                   10266:                 ($file eq $filename.'.bak') ||
                   10267:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10268:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10269:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10270:                     next if (($rem ne '') &&
                   10271:                              (($env{"httpref.$rem".$file} ne '') ||
                   10272:                               (ref($navmap) &&
                   10273:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10274:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10275:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10276:                 }
1.1075.2.11  raeburn  10277:             }
1.1071    raeburn  10278:             $unused{$file} = 1;
                   10279:         }
                   10280:     }
1.1075.2.11  raeburn  10281:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10282:         ($args->{'context'} eq 'paste')) {
                   10283:         $counter = scalar(keys(%existing));
                   10284:         $numpathchg = scalar(keys(%pathchanges));
                   10285:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10286:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10287:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10288:         $counter = scalar(keys(%existing));
                   10289:         $numpathchg = scalar(keys(%pathchanges));
                   10290:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10291:     }
1.984     raeburn  10292:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10293:         if ($actionurl eq '/adm/dependencies') {
                   10294:             next if ($embed_file =~ m{^\w+://});
                   10295:         }
1.660     raeburn  10296:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10297:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10298:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10299:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10300:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10301:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10302:         }
1.1075.2.35  raeburn  10303:         $upload_output .= '</td>';
1.1071    raeburn  10304:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10305:             $upload_output.='<td align="right">'.
                   10306:                             '<span class="LC_info LC_fontsize_medium">'.
                   10307:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10308:             $numremref++;
1.660     raeburn  10309:         } elsif ($args->{'error_on_invalid_names'}
                   10310:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10311:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10312:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10313:             $numinvalid++;
1.660     raeburn  10314:         } else {
1.1075.2.35  raeburn  10315:             $upload_output .= '<td>'.
                   10316:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10317:                                                      $embed_file,\%mapping,
1.1071    raeburn  10318:                                                      $allfiles,$codebase,'upload');
                   10319:             $counter ++;
                   10320:             $numnew ++;
1.987     raeburn  10321:         }
                   10322:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10323:     }
                   10324:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10325:         if ($actionurl eq '/adm/dependencies') {
                   10326:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10327:             $modify_output .= &start_data_table_row().
                   10328:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10329:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10330:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10331:                               '<td>'.$size.'</td>'.
                   10332:                               '<td>'.$mtime.'</td>'.
                   10333:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10334:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10335:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10336:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10337:                               &embedded_file_element('upload_embedded',$counter,
                   10338:                                                      $embed_file,\%mapping,
                   10339:                                                      $allfiles,$codebase,'modify').
                   10340:                               '</div></td>'.
                   10341:                               &end_data_table_row()."\n";
                   10342:             $counter ++;
                   10343:         } else {
                   10344:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10345:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10346:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10347:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10348:                               &Apache::loncommon::end_data_table_row()."\n";
                   10349:         }
                   10350:     }
                   10351:     my $delidx = $counter;
                   10352:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10353:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10354:         $delete_output .= &start_data_table_row().
                   10355:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10356:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10357:                           '<td>'.$size.'</td>'.
                   10358:                           '<td>'.$mtime.'</td>'.
                   10359:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10360:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10361:                           &embedded_file_element('upload_embedded',$delidx,
                   10362:                                                  $oldfile,\%mapping,$allfiles,
                   10363:                                                  $codebase,'delete').'</td>'.
                   10364:                           &end_data_table_row()."\n"; 
                   10365:         $numunused ++;
                   10366:         $delidx ++;
1.987     raeburn  10367:     }
                   10368:     if ($upload_output) {
                   10369:         $upload_output = &start_data_table().
                   10370:                          $upload_output.
                   10371:                          &end_data_table()."\n";
                   10372:     }
1.1071    raeburn  10373:     if ($modify_output) {
                   10374:         $modify_output = &start_data_table().
                   10375:                          &start_data_table_header_row().
                   10376:                          '<th>'.&mt('File').'</th>'.
                   10377:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10378:                          '<th>'.&mt('Modified').'</th>'.
                   10379:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10380:                          &end_data_table_header_row().
                   10381:                          $modify_output.
                   10382:                          &end_data_table()."\n";
                   10383:     }
                   10384:     if ($delete_output) {
                   10385:         $delete_output = &start_data_table().
                   10386:                          &start_data_table_header_row().
                   10387:                          '<th>'.&mt('File').'</th>'.
                   10388:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10389:                          '<th>'.&mt('Modified').'</th>'.
                   10390:                          '<th>'.&mt('Delete?').'</th>'.
                   10391:                          &end_data_table_header_row().
                   10392:                          $delete_output.
                   10393:                          &end_data_table()."\n";
                   10394:     }
1.987     raeburn  10395:     my $applies = 0;
                   10396:     if ($numremref) {
                   10397:         $applies ++;
                   10398:     }
                   10399:     if ($numinvalid) {
                   10400:         $applies ++;
                   10401:     }
                   10402:     if ($numexisting) {
                   10403:         $applies ++;
                   10404:     }
1.1071    raeburn  10405:     if ($counter || $numunused) {
1.987     raeburn  10406:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10407:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10408:                   $state.'<h3>'.$heading.'</h3>'; 
                   10409:         if ($actionurl eq '/adm/dependencies') {
                   10410:             if ($numnew) {
                   10411:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10412:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10413:                            $upload_output.'<br />'."\n";
                   10414:             }
                   10415:             if ($numexisting) {
                   10416:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10417:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10418:                            $modify_output.'<br />'."\n";
                   10419:                            $buttontext = &mt('Save changes');
                   10420:             }
                   10421:             if ($numunused) {
                   10422:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10423:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10424:                            $delete_output.'<br />'."\n";
                   10425:                            $buttontext = &mt('Save changes');
                   10426:             }
                   10427:         } else {
                   10428:             $output .= $upload_output.'<br />'."\n";
                   10429:         }
                   10430:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10431:                    $counter.'" />'."\n";
                   10432:         if ($actionurl eq '/adm/dependencies') { 
                   10433:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10434:                        $numnew.'" />'."\n";
                   10435:         } elsif ($actionurl eq '') {
1.987     raeburn  10436:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10437:         }
                   10438:     } elsif ($applies) {
                   10439:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10440:         if ($applies > 1) {
                   10441:             $output .=  
1.1075.2.35  raeburn  10442:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10443:             if ($numremref) {
                   10444:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10445:             }
                   10446:             if ($numinvalid) {
                   10447:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10448:             }
                   10449:             if ($numexisting) {
                   10450:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10451:             }
                   10452:             $output .= '</ul><br />';
                   10453:         } elsif ($numremref) {
                   10454:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10455:         } elsif ($numinvalid) {
                   10456:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10457:         } elsif ($numexisting) {
                   10458:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10459:         }
                   10460:         $output .= $upload_output.'<br />';
                   10461:     }
                   10462:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10463:     $chgcount = $counter;
1.987     raeburn  10464:     if (keys(%pathchanges) > 0) {
                   10465:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10466:             if ($counter) {
1.987     raeburn  10467:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10468:                                                   $embed_file,\%mapping,
1.1071    raeburn  10469:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10470:             } else {
                   10471:                 $pathchange_output .= 
                   10472:                     &start_data_table_row().
                   10473:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10474:                     $chgcount.'" checked="checked" /></td>'.
                   10475:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10476:                     '<td>'.$embed_file.
                   10477:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10478:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10479:                     '</td>'.&end_data_table_row();
1.660     raeburn  10480:             }
1.987     raeburn  10481:             $numpathchg ++;
                   10482:             $chgcount ++;
1.660     raeburn  10483:         }
                   10484:     }
1.1075.2.35  raeburn  10485:     if (($counter) || ($numunused)) {
1.987     raeburn  10486:         if ($numpathchg) {
                   10487:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10488:                        $numpathchg.'" />'."\n";
                   10489:         }
                   10490:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10491:             ($actionurl eq '/adm/imsimport')) {
                   10492:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10493:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10494:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10495:         } elsif ($actionurl eq '/adm/dependencies') {
                   10496:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10497:         }
1.1075.2.35  raeburn  10498:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10499:     } elsif ($numpathchg) {
                   10500:         my %pathchange = ();
                   10501:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10502:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10503:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10504:         }
1.987     raeburn  10505:     }
1.1071    raeburn  10506:     return ($output,$counter,$numpathchg);
1.987     raeburn  10507: }
                   10508: 
1.1075.2.47  raeburn  10509: =pod
                   10510: 
                   10511: =item * clean_path($name)
                   10512: 
                   10513: Performs clean-up of directories, subdirectories and filename in an
                   10514: embedded object, referenced in an HTML file which is being uploaded
                   10515: to a course or portfolio, where
                   10516: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10517: checked.
                   10518: 
                   10519: Clean-up is similar to replacements in lonnet::clean_filename()
                   10520: except each / between sub-directory and next level is preserved.
                   10521: 
                   10522: =cut
                   10523: 
                   10524: sub clean_path {
                   10525:     my ($embed_file) = @_;
                   10526:     $embed_file =~s{^/+}{};
                   10527:     my @contents;
                   10528:     if ($embed_file =~ m{/}) {
                   10529:         @contents = split(/\//,$embed_file);
                   10530:     } else {
                   10531:         @contents = ($embed_file);
                   10532:     }
                   10533:     my $lastidx = scalar(@contents)-1;
                   10534:     for (my $i=0; $i<=$lastidx; $i++) {
                   10535:         $contents[$i]=~s{\\}{/}g;
                   10536:         $contents[$i]=~s/\s+/\_/g;
                   10537:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10538:         if ($i == $lastidx) {
                   10539:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10540:         }
                   10541:     }
                   10542:     if ($lastidx > 0) {
                   10543:         return join('/',@contents);
                   10544:     } else {
                   10545:         return $contents[0];
                   10546:     }
                   10547: }
                   10548: 
1.987     raeburn  10549: sub embedded_file_element {
1.1071    raeburn  10550:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10551:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10552:                    (ref($codebase) eq 'HASH'));
                   10553:     my $output;
1.1071    raeburn  10554:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10555:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10556:     }
                   10557:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10558:                &escape($embed_file).'" />';
                   10559:     unless (($context eq 'upload_embedded') && 
                   10560:             ($mapping->{$embed_file} eq $embed_file)) {
                   10561:         $output .='
                   10562:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10563:     }
                   10564:     my $attrib;
                   10565:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10566:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10567:     }
                   10568:     $output .=
                   10569:         "\n\t\t".
                   10570:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10571:         $attrib.'" />';
                   10572:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10573:         $output .=
                   10574:             "\n\t\t".
                   10575:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10576:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10577:     }
1.987     raeburn  10578:     return $output;
1.660     raeburn  10579: }
                   10580: 
1.1071    raeburn  10581: sub get_dependency_details {
                   10582:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10583:     my ($size,$mtime,$showsize,$showmtime);
                   10584:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10585:         if ($embed_file =~ m{/}) {
                   10586:             my ($path,$fname) = split(/\//,$embed_file);
                   10587:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10588:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10589:             }
                   10590:         } else {
                   10591:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10592:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10593:             }
                   10594:         }
                   10595:         $showsize = $size/1024.0;
                   10596:         $showsize = sprintf("%.1f",$showsize);
                   10597:         if ($mtime > 0) {
                   10598:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10599:         }
                   10600:     }
                   10601:     return ($showsize,$showmtime);
                   10602: }
                   10603: 
                   10604: sub ask_embedded_js {
                   10605:     return <<"END";
                   10606: <script type="text/javascript"">
                   10607: // <![CDATA[
                   10608: function toggleBrowse(counter) {
                   10609:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10610:     var fileid = document.getElementById('embedded_item_'+counter);
                   10611:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10612:     if (chkboxid.checked == true) {
                   10613:         uploaddivid.style.display='block';
                   10614:     } else {
                   10615:         uploaddivid.style.display='none';
                   10616:         fileid.value = '';
                   10617:     }
                   10618: }
                   10619: // ]]>
                   10620: </script>
                   10621: 
                   10622: END
                   10623: }
                   10624: 
1.661     raeburn  10625: sub upload_embedded {
                   10626:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10627:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10628:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10629:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10630:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10631:         my $orig_uploaded_filename =
                   10632:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10633:         foreach my $type ('orig','ref','attrib','codebase') {
                   10634:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10635:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10636:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10637:             }
                   10638:         }
1.661     raeburn  10639:         my ($path,$fname) =
                   10640:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10641:         # no path, whole string is fname
                   10642:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10643:         $fname = &Apache::lonnet::clean_filename($fname);
                   10644:         # See if there is anything left
                   10645:         next if ($fname eq '');
                   10646: 
                   10647:         # Check if file already exists as a file or directory.
                   10648:         my ($state,$msg);
                   10649:         if ($context eq 'portfolio') {
                   10650:             my $port_path = $dirpath;
                   10651:             if ($group ne '') {
                   10652:                 $port_path = "groups/$group/$port_path";
                   10653:             }
1.987     raeburn  10654:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10655:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10656:                                               $dir_root,$port_path,$disk_quota,
                   10657:                                               $current_disk_usage,$uname,$udom);
                   10658:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10659:                 || $state eq 'file_locked') {
1.661     raeburn  10660:                 $output .= $msg;
                   10661:                 next;
                   10662:             }
                   10663:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10664:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10665:             if ($state eq 'exists') {
                   10666:                 $output .= $msg;
                   10667:                 next;
                   10668:             }
                   10669:         }
                   10670:         # Check if extension is valid
                   10671:         if (($fname =~ /\.(\w+)$/) &&
                   10672:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  10673:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10674:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10675:             next;
                   10676:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10677:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10678:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10679:             next;
                   10680:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  10681:             $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  10682:             next;
                   10683:         }
                   10684:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  10685:         my $subdir = $path;
                   10686:         $subdir =~ s{/+$}{};
1.661     raeburn  10687:         if ($context eq 'portfolio') {
1.984     raeburn  10688:             my $result;
                   10689:             if ($state eq 'existingfile') {
                   10690:                 $result=
                   10691:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  10692:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10693:             } else {
1.984     raeburn  10694:                 $result=
                   10695:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10696:                                                     $dirpath.
1.1075.2.35  raeburn  10697:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10698:                 if ($result !~ m|^/uploaded/|) {
                   10699:                     $output .= '<span class="LC_error">'
                   10700:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10701:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10702:                                .'</span><br />';
                   10703:                     next;
                   10704:                 } else {
1.987     raeburn  10705:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10706:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10707:                 }
1.661     raeburn  10708:             }
1.1075.2.35  raeburn  10709:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   10710:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10711:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10712:             my $result =
1.1075.2.35  raeburn  10713:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10714:             if ($result !~ m|^/uploaded/|) {
                   10715:                 $output .= '<span class="LC_error">'
                   10716:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10717:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10718:                            .'</span><br />';
                   10719:                     next;
                   10720:             } else {
                   10721:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10722:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  10723:                 if ($context eq 'syllabus') {
                   10724:                     &Apache::lonnet::make_public_indefinitely($result);
                   10725:                 }
1.987     raeburn  10726:             }
1.661     raeburn  10727:         } else {
                   10728: # Save the file
                   10729:             my $target = $env{'form.embedded_item_'.$i};
                   10730:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10731:             my $dest = $fullpath.$fname;
                   10732:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10733:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10734:             my $count;
                   10735:             my $filepath = $dir_root;
1.1027    raeburn  10736:             foreach my $subdir (@parts) {
                   10737:                 $filepath .= "/$subdir";
                   10738:                 if (!-e $filepath) {
1.661     raeburn  10739:                     mkdir($filepath,0770);
                   10740:                 }
                   10741:             }
                   10742:             my $fh;
                   10743:             if (!open($fh,'>'.$dest)) {
                   10744:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10745:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10746:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10747:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10748:                            '</span><br />';
                   10749:             } else {
                   10750:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10751:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10752:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10753:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10754:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10755:                               '</span><br />';
                   10756:                 } else {
1.987     raeburn  10757:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10758:                                $url.'</span>').'<br />';
                   10759:                     unless ($context eq 'testbank') {
                   10760:                         $footer .= &mt('View embedded file: [_1]',
                   10761:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10762:                     }
                   10763:                 }
                   10764:                 close($fh);
                   10765:             }
                   10766:         }
                   10767:         if ($env{'form.embedded_ref_'.$i}) {
                   10768:             $pathchange{$i} = 1;
                   10769:         }
                   10770:     }
                   10771:     if ($output) {
                   10772:         $output = '<p>'.$output.'</p>';
                   10773:     }
                   10774:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10775:     $returnflag = 'ok';
1.1071    raeburn  10776:     my $numpathchgs = scalar(keys(%pathchange));
                   10777:     if ($numpathchgs > 0) {
1.987     raeburn  10778:         if ($context eq 'portfolio') {
                   10779:             $output .= '<p>'.&mt('or').'</p>';
                   10780:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10781:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10782:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10783:             $returnflag = 'modify_orightml';
                   10784:         }
                   10785:     }
1.1071    raeburn  10786:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10787: }
                   10788: 
                   10789: sub modify_html_form {
                   10790:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10791:     my $end = 0;
                   10792:     my $modifyform;
                   10793:     if ($context eq 'upload_embedded') {
                   10794:         return unless (ref($pathchange) eq 'HASH');
                   10795:         if ($env{'form.number_embedded_items'}) {
                   10796:             $end += $env{'form.number_embedded_items'};
                   10797:         }
                   10798:         if ($env{'form.number_pathchange_items'}) {
                   10799:             $end += $env{'form.number_pathchange_items'};
                   10800:         }
                   10801:         if ($end) {
                   10802:             for (my $i=0; $i<$end; $i++) {
                   10803:                 if ($i < $env{'form.number_embedded_items'}) {
                   10804:                     next unless($pathchange->{$i});
                   10805:                 }
                   10806:                 $modifyform .=
                   10807:                     &start_data_table_row().
                   10808:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10809:                     'checked="checked" /></td>'.
                   10810:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10811:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10812:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10813:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10814:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10815:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10816:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10817:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10818:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10819:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10820:                     &end_data_table_row();
1.1071    raeburn  10821:             }
1.987     raeburn  10822:         }
                   10823:     } else {
                   10824:         $modifyform = $pathchgtable;
                   10825:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10826:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10827:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10828:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10829:         }
                   10830:     }
                   10831:     if ($modifyform) {
1.1071    raeburn  10832:         if ($actionurl eq '/adm/dependencies') {
                   10833:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10834:         }
1.987     raeburn  10835:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10836:                '<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".
                   10837:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10838:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10839:                '</ol></p>'."\n".'<p>'.
                   10840:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10841:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10842:                &start_data_table()."\n".
                   10843:                &start_data_table_header_row().
                   10844:                '<th>'.&mt('Change?').'</th>'.
                   10845:                '<th>'.&mt('Current reference').'</th>'.
                   10846:                '<th>'.&mt('Required reference').'</th>'.
                   10847:                &end_data_table_header_row()."\n".
                   10848:                $modifyform.
                   10849:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10850:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10851:                '</form>'."\n";
                   10852:     }
                   10853:     return;
                   10854: }
                   10855: 
                   10856: sub modify_html_refs {
1.1075.2.35  raeburn  10857:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10858:     my $container;
                   10859:     if ($context eq 'portfolio') {
                   10860:         $container = $env{'form.container'};
                   10861:     } elsif ($context eq 'coursedoc') {
                   10862:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10863:     } elsif ($context eq 'manage_dependencies') {
                   10864:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10865:         $container = "/$container";
1.1075.2.35  raeburn  10866:     } elsif ($context eq 'syllabus') {
                   10867:         $container = $url;
1.987     raeburn  10868:     } else {
1.1027    raeburn  10869:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10870:     }
                   10871:     my (%allfiles,%codebase,$output,$content);
                   10872:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  10873:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  10874:         if (wantarray) {
                   10875:             return ('',0,0); 
                   10876:         } else {
                   10877:             return;
                   10878:         }
                   10879:     }
                   10880:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10881:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10882:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10883:             if (wantarray) {
                   10884:                 return ('',0,0);
                   10885:             } else {
                   10886:                 return;
                   10887:             }
                   10888:         } 
1.987     raeburn  10889:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10890:         if ($content eq '-1') {
                   10891:             if (wantarray) {
                   10892:                 return ('',0,0);
                   10893:             } else {
                   10894:                 return;
                   10895:             }
                   10896:         }
1.987     raeburn  10897:     } else {
1.1071    raeburn  10898:         unless ($container =~ /^\Q$dir_root\E/) {
                   10899:             if (wantarray) {
                   10900:                 return ('',0,0);
                   10901:             } else {
                   10902:                 return;
                   10903:             }
                   10904:         } 
1.987     raeburn  10905:         if (open(my $fh,"<$container")) {
                   10906:             $content = join('', <$fh>);
                   10907:             close($fh);
                   10908:         } else {
1.1071    raeburn  10909:             if (wantarray) {
                   10910:                 return ('',0,0);
                   10911:             } else {
                   10912:                 return;
                   10913:             }
1.987     raeburn  10914:         }
                   10915:     }
                   10916:     my ($count,$codebasecount) = (0,0);
                   10917:     my $mm = new File::MMagic;
                   10918:     my $mime_type = $mm->checktype_contents($content);
                   10919:     if ($mime_type eq 'text/html') {
                   10920:         my $parse_result = 
                   10921:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10922:                                                     \%codebase,\$content);
                   10923:         if ($parse_result eq 'ok') {
                   10924:             foreach my $i (@changes) {
                   10925:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10926:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10927:                 if ($allfiles{$ref}) {
                   10928:                     my $newname =  $orig;
                   10929:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10930:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10931:                     if ($attrib_regexp =~ /:/) {
                   10932:                         $attrib_regexp =~ s/\:/|/g;
                   10933:                     }
                   10934:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10935:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10936:                         $count += $numchg;
1.1075.2.35  raeburn  10937:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  10938:                         delete($allfiles{$ref});
1.987     raeburn  10939:                     }
                   10940:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10941:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10942:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10943:                         $codebasecount ++;
                   10944:                     }
                   10945:                 }
                   10946:             }
1.1075.2.35  raeburn  10947:             my $skiprewrites;
1.987     raeburn  10948:             if ($count || $codebasecount) {
                   10949:                 my $saveresult;
1.1071    raeburn  10950:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10951:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10952:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10953:                     if ($url eq $container) {
                   10954:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10955:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10956:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10957:                                             $fname.'</span>').'</p>';
1.987     raeburn  10958:                     } else {
                   10959:                          $output = '<p class="LC_error">'.
                   10960:                                    &mt('Error: update failed for: [_1].',
                   10961:                                    '<span class="LC_filename">'.
                   10962:                                    $container.'</span>').'</p>';
                   10963:                     }
1.1075.2.35  raeburn  10964:                     if ($context eq 'syllabus') {
                   10965:                         unless ($saveresult eq 'ok') {
                   10966:                             $skiprewrites = 1;
                   10967:                         }
                   10968:                     }
1.987     raeburn  10969:                 } else {
                   10970:                     if (open(my $fh,">$container")) {
                   10971:                         print $fh $content;
                   10972:                         close($fh);
                   10973:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10974:                                   $count,'<span class="LC_filename">'.
                   10975:                                   $container.'</span>').'</p>';
1.661     raeburn  10976:                     } else {
1.987     raeburn  10977:                          $output = '<p class="LC_error">'.
                   10978:                                    &mt('Error: could not update [_1].',
                   10979:                                    '<span class="LC_filename">'.
                   10980:                                    $container.'</span>').'</p>';
1.661     raeburn  10981:                     }
                   10982:                 }
                   10983:             }
1.1075.2.35  raeburn  10984:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10985:                 my ($actionurl,$state);
                   10986:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10987:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10988:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10989:                                               \%codebase,
                   10990:                                               {'context' => 'rewrites',
                   10991:                                                'ignore_remote_references' => 1,});
                   10992:                 if (ref($mapping) eq 'HASH') {
                   10993:                     my $rewrites = 0;
                   10994:                     foreach my $key (keys(%{$mapping})) {
                   10995:                         next if ($key =~ m{^https?://});
                   10996:                         my $ref = $mapping->{$key};
                   10997:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10998:                         my $attrib;
                   10999:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11000:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11001:                         }
                   11002:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11003:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11004:                             $rewrites += $numchg;
                   11005:                         }
                   11006:                     }
                   11007:                     if ($rewrites) {
                   11008:                         my $saveresult;
                   11009:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11010:                         if ($url eq $container) {
                   11011:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11012:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11013:                                             $count,'<span class="LC_filename">'.
                   11014:                                             $fname.'</span>').'</p>';
                   11015:                         } else {
                   11016:                             $output .= '<p class="LC_error">'.
                   11017:                                        &mt('Error: could not update links in [_1].',
                   11018:                                        '<span class="LC_filename">'.
                   11019:                                        $container.'</span>').'</p>';
                   11020: 
                   11021:                         }
                   11022:                     }
                   11023:                 }
                   11024:             }
1.987     raeburn  11025:         } else {
                   11026:             &logthis('Failed to parse '.$container.
                   11027:                      ' to modify references: '.$parse_result);
1.661     raeburn  11028:         }
                   11029:     }
1.1071    raeburn  11030:     if (wantarray) {
                   11031:         return ($output,$count,$codebasecount);
                   11032:     } else {
                   11033:         return $output;
                   11034:     }
1.661     raeburn  11035: }
                   11036: 
                   11037: sub check_for_existing {
                   11038:     my ($path,$fname,$element) = @_;
                   11039:     my ($state,$msg);
                   11040:     if (-d $path.'/'.$fname) {
                   11041:         $state = 'exists';
                   11042:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11043:     } elsif (-e $path.'/'.$fname) {
                   11044:         $state = 'exists';
                   11045:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11046:     }
                   11047:     if ($state eq 'exists') {
                   11048:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11049:     }
                   11050:     return ($state,$msg);
                   11051: }
                   11052: 
                   11053: sub check_for_upload {
                   11054:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11055:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11056:     my $filesize = length($env{'form.'.$element});
                   11057:     if (!$filesize) {
                   11058:         my $msg = '<span class="LC_error">'.
                   11059:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11060:                       '<span class="LC_filename">'.$fname.'</span>',
                   11061:                       $filesize).'<br />'.
1.1007    raeburn  11062:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11063:                   '</span>';
                   11064:         return ('zero_bytes',$msg);
                   11065:     }
                   11066:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11067:     my $getpropath = 1;
1.1021    raeburn  11068:     my ($dirlistref,$listerror) =
                   11069:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11070:     my $found_file = 0;
                   11071:     my $locked_file = 0;
1.991     raeburn  11072:     my @lockers;
                   11073:     my $navmap;
                   11074:     if ($env{'request.course.id'}) {
                   11075:         $navmap = Apache::lonnavmaps::navmap->new();
                   11076:     }
1.1021    raeburn  11077:     if (ref($dirlistref) eq 'ARRAY') {
                   11078:         foreach my $line (@{$dirlistref}) {
                   11079:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11080:             if ($file_name eq $fname){
                   11081:                 $file_name = $path.$file_name;
                   11082:                 if ($group ne '') {
                   11083:                     $file_name = $group.$file_name;
                   11084:                 }
                   11085:                 $found_file = 1;
                   11086:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11087:                     foreach my $lock (@lockers) {
                   11088:                         if (ref($lock) eq 'ARRAY') {
                   11089:                             my ($symb,$crsid) = @{$lock};
                   11090:                             if ($crsid eq $env{'request.course.id'}) {
                   11091:                                 if (ref($navmap)) {
                   11092:                                     my $res = $navmap->getBySymb($symb);
                   11093:                                     foreach my $part (@{$res->parts()}) { 
                   11094:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11095:                                         unless (($slot_status == $res->RESERVED) ||
                   11096:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11097:                                             $locked_file = 1;
                   11098:                                         }
1.991     raeburn  11099:                                     }
1.1021    raeburn  11100:                                 } else {
                   11101:                                     $locked_file = 1;
1.991     raeburn  11102:                                 }
                   11103:                             } else {
                   11104:                                 $locked_file = 1;
                   11105:                             }
                   11106:                         }
1.1021    raeburn  11107:                    }
                   11108:                 } else {
                   11109:                     my @info = split(/\&/,$rest);
                   11110:                     my $currsize = $info[6]/1000;
                   11111:                     if ($currsize < $filesize) {
                   11112:                         my $extra = $filesize - $currsize;
                   11113:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11114:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11115:                                       &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  11116:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11117:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11118:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11119:                             return ('will_exceed_quota',$msg);
                   11120:                         }
1.984     raeburn  11121:                     }
                   11122:                 }
1.661     raeburn  11123:             }
                   11124:         }
                   11125:     }
                   11126:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11127:         my $msg = '<p class="LC_warning">'.
                   11128:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11129:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11130:         return ('will_exceed_quota',$msg);
                   11131:     } elsif ($found_file) {
                   11132:         if ($locked_file) {
1.1075.2.69  raeburn  11133:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11134:             $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  11135:             $msg .= '</p>';
1.661     raeburn  11136:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11137:             return ('file_locked',$msg);
                   11138:         } else {
1.1075.2.69  raeburn  11139:             my $msg = '<p class="LC_error">';
1.984     raeburn  11140:             $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  11141:             $msg .= '</p>';
1.984     raeburn  11142:             return ('existingfile',$msg);
1.661     raeburn  11143:         }
                   11144:     }
                   11145: }
                   11146: 
1.987     raeburn  11147: sub check_for_traversal {
                   11148:     my ($path,$url,$toplevel) = @_;
                   11149:     my @parts=split(/\//,$path);
                   11150:     my $cleanpath;
                   11151:     my $fullpath = $url;
                   11152:     for (my $i=0;$i<@parts;$i++) {
                   11153:         next if ($parts[$i] eq '.');
                   11154:         if ($parts[$i] eq '..') {
                   11155:             $fullpath =~ s{([^/]+/)$}{};
                   11156:         } else {
                   11157:             $fullpath .= $parts[$i].'/';
                   11158:         }
                   11159:     }
                   11160:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11161:         $cleanpath = $1;
                   11162:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11163:         my $curr_toprel = $1;
                   11164:         my @parts = split(/\//,$curr_toprel);
                   11165:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11166:         my @urlparts = split(/\//,$url_toprel);
                   11167:         my $doubledots;
                   11168:         my $startdiff = -1;
                   11169:         for (my $i=0; $i<@urlparts; $i++) {
                   11170:             if ($startdiff == -1) {
                   11171:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11172:                     $startdiff = $i;
                   11173:                     $doubledots .= '../';
                   11174:                 }
                   11175:             } else {
                   11176:                 $doubledots .= '../';
                   11177:             }
                   11178:         }
                   11179:         if ($startdiff > -1) {
                   11180:             $cleanpath = $doubledots;
                   11181:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11182:                 $cleanpath .= $parts[$i].'/';
                   11183:             }
                   11184:         }
                   11185:     }
                   11186:     $cleanpath =~ s{(/)$}{};
                   11187:     return $cleanpath;
                   11188: }
1.31      albertel 11189: 
1.1053    raeburn  11190: sub is_archive_file {
                   11191:     my ($mimetype) = @_;
                   11192:     if (($mimetype eq 'application/octet-stream') ||
                   11193:         ($mimetype eq 'application/x-stuffit') ||
                   11194:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11195:         return 1;
                   11196:     }
                   11197:     return;
                   11198: }
                   11199: 
                   11200: sub decompress_form {
1.1065    raeburn  11201:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11202:     my %lt = &Apache::lonlocal::texthash (
                   11203:         this => 'This file is an archive file.',
1.1067    raeburn  11204:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11205:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11206:         youm => 'You may wish to extract its contents.',
                   11207:         extr => 'Extract contents',
1.1067    raeburn  11208:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11209:         proa => 'Process automatically?',
1.1053    raeburn  11210:         yes  => 'Yes',
                   11211:         no   => 'No',
1.1067    raeburn  11212:         fold => 'Title for folder containing movie',
                   11213:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11214:     );
1.1065    raeburn  11215:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11216:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11217:     my $info = &list_archive_contents($fileloc,\@paths);
                   11218:     if (@paths) {
                   11219:         foreach my $path (@paths) {
                   11220:             $path =~ s{^/}{};
1.1067    raeburn  11221:             if ($path =~ m{^([^/]+)/$}) {
                   11222:                 $topdir = $1;
                   11223:             }
1.1065    raeburn  11224:             if ($path =~ m{^([^/]+)/}) {
                   11225:                 $toplevel{$1} = $path;
                   11226:             } else {
                   11227:                 $toplevel{$path} = $path;
                   11228:             }
                   11229:         }
                   11230:     }
1.1067    raeburn  11231:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11232:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11233:                         "$topdir/media/",
                   11234:                         "$topdir/media/$topdir.mp4",
                   11235:                         "$topdir/media/FirstFrame.png",
                   11236:                         "$topdir/media/player.swf",
                   11237:                         "$topdir/media/swfobject.js",
                   11238:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11239:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11240:                          "$topdir/$topdir.mp4",
                   11241:                          "$topdir/$topdir\_config.xml",
                   11242:                          "$topdir/$topdir\_controller.swf",
                   11243:                          "$topdir/$topdir\_embed.css",
                   11244:                          "$topdir/$topdir\_First_Frame.png",
                   11245:                          "$topdir/$topdir\_player.html",
                   11246:                          "$topdir/$topdir\_Thumbnails.png",
                   11247:                          "$topdir/playerProductInstall.swf",
                   11248:                          "$topdir/scripts/",
                   11249:                          "$topdir/scripts/config_xml.js",
                   11250:                          "$topdir/scripts/handlebars.js",
                   11251:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11252:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11253:                          "$topdir/scripts/modernizr.js",
                   11254:                          "$topdir/scripts/player-min.js",
                   11255:                          "$topdir/scripts/swfobject.js",
                   11256:                          "$topdir/skins/",
                   11257:                          "$topdir/skins/configuration_express.xml",
                   11258:                          "$topdir/skins/express_show/",
                   11259:                          "$topdir/skins/express_show/player-min.css",
                   11260:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11261:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11262:                          "$topdir/$topdir.mp4",
                   11263:                          "$topdir/$topdir\_config.xml",
                   11264:                          "$topdir/$topdir\_controller.swf",
                   11265:                          "$topdir/$topdir\_embed.css",
                   11266:                          "$topdir/$topdir\_First_Frame.png",
                   11267:                          "$topdir/$topdir\_player.html",
                   11268:                          "$topdir/$topdir\_Thumbnails.png",
                   11269:                          "$topdir/playerProductInstall.swf",
                   11270:                          "$topdir/scripts/",
                   11271:                          "$topdir/scripts/config_xml.js",
                   11272:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11273:                          "$topdir/skins/",
                   11274:                          "$topdir/skins/configuration_express.xml",
                   11275:                          "$topdir/skins/express_show/",
                   11276:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11277:                          "$topdir/skins/express_show/spritesheet.png",
                   11278:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11279:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11280:         if (@diffs == 0) {
1.1075.2.59  raeburn  11281:             $is_camtasia = 6;
                   11282:         } else {
1.1075.2.81  raeburn  11283:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11284:             if (@diffs == 0) {
                   11285:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11286:             } else {
                   11287:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11288:                 if (@diffs == 0) {
                   11289:                     $is_camtasia = 8;
                   11290:                 }
1.1075.2.59  raeburn  11291:             }
1.1067    raeburn  11292:         }
                   11293:     }
                   11294:     my $output;
                   11295:     if ($is_camtasia) {
                   11296:         $output = <<"ENDCAM";
                   11297: <script type="text/javascript" language="Javascript">
                   11298: // <![CDATA[
                   11299: 
                   11300: function camtasiaToggle() {
                   11301:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11302:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11303:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11304:                 document.getElementById('camtasia_titles').style.display='block';
                   11305:             } else {
                   11306:                 document.getElementById('camtasia_titles').style.display='none';
                   11307:             }
                   11308:         }
                   11309:     }
                   11310:     return;
                   11311: }
                   11312: 
                   11313: // ]]>
                   11314: </script>
                   11315: <p>$lt{'camt'}</p>
                   11316: ENDCAM
1.1065    raeburn  11317:     } else {
1.1067    raeburn  11318:         $output = '<p>'.$lt{'this'};
                   11319:         if ($info eq '') {
                   11320:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11321:         } else {
                   11322:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11323:                        '<div><pre>'.$info.'</pre></div>';
                   11324:         }
1.1065    raeburn  11325:     }
1.1067    raeburn  11326:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11327:     my $duplicates;
                   11328:     my $num = 0;
                   11329:     if (ref($dirlist) eq 'ARRAY') {
                   11330:         foreach my $item (@{$dirlist}) {
                   11331:             if (ref($item) eq 'ARRAY') {
                   11332:                 if (exists($toplevel{$item->[0]})) {
                   11333:                     $duplicates .= 
                   11334:                         &start_data_table_row().
                   11335:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11336:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11337:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11338:                         'value="1" />'.&mt('Yes').'</label>'.
                   11339:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11340:                         '<td>'.$item->[0].'</td>';
                   11341:                     if ($item->[2]) {
                   11342:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11343:                     } else {
                   11344:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11345:                     }
                   11346:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11347:                                    '<td>'.
                   11348:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11349:                                    '</td>'.
                   11350:                                    &end_data_table_row();
                   11351:                     $num ++;
                   11352:                 }
                   11353:             }
                   11354:         }
                   11355:     }
                   11356:     my $itemcount;
                   11357:     if (@paths > 0) {
                   11358:         $itemcount = scalar(@paths);
                   11359:     } else {
                   11360:         $itemcount = 1;
                   11361:     }
1.1067    raeburn  11362:     if ($is_camtasia) {
                   11363:         $output .= $lt{'auto'}.'<br />'.
                   11364:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11365:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11366:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11367:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11368:                    $lt{'no'}.'</label></span><br />'.
                   11369:                    '<div id="camtasia_titles" style="display:block">'.
                   11370:                    &Apache::lonhtmlcommon::start_pick_box().
                   11371:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11372:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11373:                    &Apache::lonhtmlcommon::row_closure().
                   11374:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11375:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11376:                    &Apache::lonhtmlcommon::row_closure(1).
                   11377:                    &Apache::lonhtmlcommon::end_pick_box().
                   11378:                    '</div>';
                   11379:     }
1.1065    raeburn  11380:     $output .= 
                   11381:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11382:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11383:         "\n";
1.1065    raeburn  11384:     if ($duplicates ne '') {
                   11385:         $output .= '<p><span class="LC_warning">'.
                   11386:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11387:                    &start_data_table().
                   11388:                    &start_data_table_header_row().
                   11389:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11390:                    '<th>'.&mt('Name').'</th>'.
                   11391:                    '<th>'.&mt('Type').'</th>'.
                   11392:                    '<th>'.&mt('Size').'</th>'.
                   11393:                    '<th>'.&mt('Last modified').'</th>'.
                   11394:                    &end_data_table_header_row().
                   11395:                    $duplicates.
                   11396:                    &end_data_table().
                   11397:                    '</p>';
                   11398:     }
1.1067    raeburn  11399:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11400:     if (ref($hiddenelements) eq 'HASH') {
                   11401:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11402:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11403:         }
                   11404:     }
                   11405:     $output .= <<"END";
1.1067    raeburn  11406: <br />
1.1053    raeburn  11407: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11408: </form>
                   11409: $noextract
                   11410: END
                   11411:     return $output;
                   11412: }
                   11413: 
1.1065    raeburn  11414: sub decompression_utility {
                   11415:     my ($program) = @_;
                   11416:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11417:     my $location;
                   11418:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11419:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11420:                          '/usr/sbin/') {
                   11421:             if (-x $dir.$program) {
                   11422:                 $location = $dir.$program;
                   11423:                 last;
                   11424:             }
                   11425:         }
                   11426:     }
                   11427:     return $location;
                   11428: }
                   11429: 
                   11430: sub list_archive_contents {
                   11431:     my ($file,$pathsref) = @_;
                   11432:     my (@cmd,$output);
                   11433:     my $needsregexp;
                   11434:     if ($file =~ /\.zip$/) {
                   11435:         @cmd = (&decompression_utility('unzip'),"-l");
                   11436:         $needsregexp = 1;
                   11437:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11438:              ($file =~ /\.tgz$/)) {
                   11439:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11440:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11441:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11442:     } elsif ($file =~ m|\.tar$|) {
                   11443:         @cmd = (&decompression_utility('tar'),"-tf");
                   11444:     }
                   11445:     if (@cmd) {
                   11446:         undef($!);
                   11447:         undef($@);
                   11448:         if (open(my $fh,"-|", @cmd, $file)) {
                   11449:             while (my $line = <$fh>) {
                   11450:                 $output .= $line;
                   11451:                 chomp($line);
                   11452:                 my $item;
                   11453:                 if ($needsregexp) {
                   11454:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11455:                 } else {
                   11456:                     $item = $line;
                   11457:                 }
                   11458:                 if ($item ne '') {
                   11459:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11460:                         push(@{$pathsref},$item);
                   11461:                     } 
                   11462:                 }
                   11463:             }
                   11464:             close($fh);
                   11465:         }
                   11466:     }
                   11467:     return $output;
                   11468: }
                   11469: 
1.1053    raeburn  11470: sub decompress_uploaded_file {
                   11471:     my ($file,$dir) = @_;
                   11472:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11473:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11474:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11475:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11476:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11477:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11478:     my $decompressed = $env{'cgi.decompressed'};
                   11479:     &Apache::lonnet::delenv('cgi.file');
                   11480:     &Apache::lonnet::delenv('cgi.dir');
                   11481:     &Apache::lonnet::delenv('cgi.decompressed');
                   11482:     return ($decompressed,$result);
                   11483: }
                   11484: 
1.1055    raeburn  11485: sub process_decompression {
                   11486:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11487:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  11488:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  11489:         $error = &mt('Filename not a supported archive file type.').
                   11490:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11491:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11492:     } else {
                   11493:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11494:         if ($docuhome eq 'no_host') {
                   11495:             $error = &mt('Could not determine home server for course.');
                   11496:         } else {
                   11497:             my @ids=&Apache::lonnet::current_machine_ids();
                   11498:             my $currdir = "$dir_root/$destination";
                   11499:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11500:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11501:                        "$dir_root/$destination";
                   11502:             } else {
                   11503:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11504:                        "$dir_root/$docudom/$docuname/$destination";
                   11505:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11506:                     $error = &mt('Archive file not found.');
                   11507:                 }
                   11508:             }
1.1065    raeburn  11509:             my (@to_overwrite,@to_skip);
                   11510:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11511:                 my $total = $env{'form.archive_overwrite_total'};
                   11512:                 for (my $i=0; $i<$total; $i++) {
                   11513:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11514:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11515:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11516:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11517:                     }
                   11518:                 }
                   11519:             }
                   11520:             my $numskip = scalar(@to_skip);
                   11521:             if (($numskip > 0) && 
                   11522:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11523:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11524:             } elsif ($dir eq '') {
1.1055    raeburn  11525:                 $error = &mt('Directory containing archive file unavailable.');
                   11526:             } elsif (!$error) {
1.1065    raeburn  11527:                 my ($decompressed,$display);
                   11528:                 if ($numskip > 0) {
                   11529:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11530:                     mkdir("$dir/$tempdir",0755);
                   11531:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11532:                     ($decompressed,$display) = 
                   11533:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11534:                     foreach my $item (@to_skip) {
                   11535:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11536:                             if (-f "$dir/$tempdir/$item") { 
                   11537:                                 unlink("$dir/$tempdir/$item");
                   11538:                             } elsif (-d "$dir/$tempdir/$item") {
                   11539:                                 system("rm -rf $dir/$tempdir/$item");
                   11540:                             }
                   11541:                         }
                   11542:                     }
                   11543:                     system("mv $dir/$tempdir/* $dir");
                   11544:                     rmdir("$dir/$tempdir");   
                   11545:                 } else {
                   11546:                     ($decompressed,$display) = 
                   11547:                         &decompress_uploaded_file($file,$dir);
                   11548:                 }
1.1055    raeburn  11549:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11550:                     $output = '<p class="LC_info">'.
                   11551:                               &mt('Files extracted successfully from archive.').
                   11552:                               '</p>'."\n";
1.1055    raeburn  11553:                     my ($warning,$result,@contents);
                   11554:                     my ($newdirlistref,$newlisterror) =
                   11555:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11556:                                                  $docuname,1);
                   11557:                     my (%is_dir,%changes,@newitems);
                   11558:                     my $dirptr = 16384;
1.1065    raeburn  11559:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11560:                         foreach my $dir_line (@{$newdirlistref}) {
                   11561:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11562:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11563:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11564:                                 push(@newitems,$item);
                   11565:                                 if ($dirptr&$testdir) {
                   11566:                                     $is_dir{$item} = 1;
                   11567:                                 }
                   11568:                                 $changes{$item} = 1;
                   11569:                             }
                   11570:                         }
                   11571:                     }
                   11572:                     if (keys(%changes) > 0) {
                   11573:                         foreach my $item (sort(@newitems)) {
                   11574:                             if ($changes{$item}) {
                   11575:                                 push(@contents,$item);
                   11576:                             }
                   11577:                         }
                   11578:                     }
                   11579:                     if (@contents > 0) {
1.1067    raeburn  11580:                         my $wantform;
                   11581:                         unless ($env{'form.autoextract_camtasia'}) {
                   11582:                             $wantform = 1;
                   11583:                         }
1.1056    raeburn  11584:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11585:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11586:                                                                 $currdir,\%is_dir,
                   11587:                                                                 \%children,\%parent,
1.1056    raeburn  11588:                                                                 \@contents,\%dirorder,
                   11589:                                                                 \%titles,$wantform);
1.1055    raeburn  11590:                         if ($datatable ne '') {
                   11591:                             $output .= &archive_options_form('decompressed',$datatable,
                   11592:                                                              $count,$hiddenelem);
1.1065    raeburn  11593:                             my $startcount = 6;
1.1055    raeburn  11594:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11595:                                                            \%titles,\%children);
1.1055    raeburn  11596:                         }
1.1067    raeburn  11597:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  11598:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11599:                             my %displayed;
                   11600:                             my $total = 1;
                   11601:                             $env{'form.archive_directory'} = [];
                   11602:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11603:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11604:                                 $path =~ s{/$}{};
                   11605:                                 my $item;
                   11606:                                 if ($path ne '') {
                   11607:                                     $item = "$path/$titles{$i}";
                   11608:                                 } else {
                   11609:                                     $item = $titles{$i};
                   11610:                                 }
                   11611:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11612:                                 if ($item eq $contents[0]) {
                   11613:                                     push(@{$env{'form.archive_directory'}},$i);
                   11614:                                     $env{'form.archive_'.$i} = 'display';
                   11615:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11616:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  11617:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11618:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  11619:                                     $env{'form.archive_'.$i} = 'display';
                   11620:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11621:                                     $displayed{'web'} = $i;
                   11622:                                 } else {
1.1075.2.59  raeburn  11623:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11624:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11625:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11626:                                         push(@{$env{'form.archive_directory'}},$i);
                   11627:                                     }
                   11628:                                     $env{'form.archive_'.$i} = 'dependency';
                   11629:                                 }
                   11630:                                 $total ++;
                   11631:                             }
                   11632:                             for (my $i=1; $i<$total; $i++) {
                   11633:                                 next if ($i == $displayed{'web'});
                   11634:                                 next if ($i == $displayed{'folder'});
                   11635:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11636:                             }
                   11637:                             $env{'form.phase'} = 'decompress_cleanup';
                   11638:                             $env{'form.archivedelete'} = 1;
                   11639:                             $env{'form.archive_count'} = $total-1;
                   11640:                             $output .=
                   11641:                                 &process_extracted_files('coursedocs',$docudom,
                   11642:                                                          $docuname,$destination,
                   11643:                                                          $dir_root,$hiddenelem);
                   11644:                         }
1.1055    raeburn  11645:                     } else {
                   11646:                         $warning = &mt('No new items extracted from archive file.');
                   11647:                     }
                   11648:                 } else {
                   11649:                     $output = $display;
                   11650:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11651:                 }
                   11652:             }
                   11653:         }
                   11654:     }
                   11655:     if ($error) {
                   11656:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11657:                    $error.'</p>'."\n";
                   11658:     }
                   11659:     if ($warning) {
                   11660:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11661:     }
                   11662:     return $output;
                   11663: }
                   11664: 
                   11665: sub get_extracted {
1.1056    raeburn  11666:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11667:         $titles,$wantform) = @_;
1.1055    raeburn  11668:     my $count = 0;
                   11669:     my $depth = 0;
                   11670:     my $datatable;
1.1056    raeburn  11671:     my @hierarchy;
1.1055    raeburn  11672:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11673:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11674:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11675:     foreach my $item (@{$contents}) {
                   11676:         $count ++;
1.1056    raeburn  11677:         @{$dirorder->{$count}} = @hierarchy;
                   11678:         $titles->{$count} = $item;
1.1055    raeburn  11679:         &archive_hierarchy($depth,$count,$parent,$children);
                   11680:         if ($wantform) {
                   11681:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11682:                                        $currdir,$depth,$count);
                   11683:         }
                   11684:         if ($is_dir->{$item}) {
                   11685:             $depth ++;
1.1056    raeburn  11686:             push(@hierarchy,$count);
                   11687:             $parent->{$depth} = $count;
1.1055    raeburn  11688:             $datatable .=
                   11689:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11690:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11691:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11692:             $depth --;
1.1056    raeburn  11693:             pop(@hierarchy);
1.1055    raeburn  11694:         }
                   11695:     }
                   11696:     return ($count,$datatable);
                   11697: }
                   11698: 
                   11699: sub recurse_extracted_archive {
1.1056    raeburn  11700:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11701:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11702:     my $result='';
1.1056    raeburn  11703:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11704:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11705:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11706:         return $result;
                   11707:     }
                   11708:     my $dirptr = 16384;
                   11709:     my ($newdirlistref,$newlisterror) =
                   11710:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11711:     if (ref($newdirlistref) eq 'ARRAY') {
                   11712:         foreach my $dir_line (@{$newdirlistref}) {
                   11713:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11714:             unless ($item =~ /^\.+$/) {
                   11715:                 $$count ++;
1.1056    raeburn  11716:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11717:                 $titles->{$$count} = $item;
1.1055    raeburn  11718:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11719: 
1.1055    raeburn  11720:                 my $is_dir;
                   11721:                 if ($dirptr&$testdir) {
                   11722:                     $is_dir = 1;
                   11723:                 }
                   11724:                 if ($wantform) {
                   11725:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11726:                 }
                   11727:                 if ($is_dir) {
                   11728:                     $$depth ++;
1.1056    raeburn  11729:                     push(@{$hierarchy},$$count);
                   11730:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11731:                     $result .=
                   11732:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11733:                                                    $docuname,$depth,$count,
1.1056    raeburn  11734:                                                    $hierarchy,$dirorder,$children,
                   11735:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11736:                     $$depth --;
1.1056    raeburn  11737:                     pop(@{$hierarchy});
1.1055    raeburn  11738:                 }
                   11739:             }
                   11740:         }
                   11741:     }
                   11742:     return $result;
                   11743: }
                   11744: 
                   11745: sub archive_hierarchy {
                   11746:     my ($depth,$count,$parent,$children) =@_;
                   11747:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11748:         if (exists($parent->{$depth})) {
                   11749:              $children->{$parent->{$depth}} .= $count.':';
                   11750:         }
                   11751:     }
                   11752:     return;
                   11753: }
                   11754: 
                   11755: sub archive_row {
                   11756:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11757:     my ($name) = ($item =~ m{([^/]+)$});
                   11758:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11759:                                        'display'    => 'Add as file',
1.1055    raeburn  11760:                                        'dependency' => 'Include as dependency',
                   11761:                                        'discard'    => 'Discard',
                   11762:                                       );
                   11763:     if ($is_dir) {
1.1059    raeburn  11764:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11765:     }
1.1056    raeburn  11766:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11767:     my $offset = 0;
1.1055    raeburn  11768:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11769:         $offset ++;
1.1065    raeburn  11770:         if ($action ne 'display') {
                   11771:             $offset ++;
                   11772:         }  
1.1055    raeburn  11773:         $output .= '<td><span class="LC_nobreak">'.
                   11774:                    '<label><input type="radio" name="archive_'.$count.
                   11775:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11776:         my $text = $choices{$action};
                   11777:         if ($is_dir) {
                   11778:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11779:             if ($action eq 'display') {
1.1059    raeburn  11780:                 $text = &mt('Add as folder');
1.1055    raeburn  11781:             }
1.1056    raeburn  11782:         } else {
                   11783:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11784: 
                   11785:         }
                   11786:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11787:         if ($action eq 'dependency') {
                   11788:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11789:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11790:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11791:                        '<option value=""></option>'."\n".
                   11792:                        '</select>'."\n".
                   11793:                        '</div>';
1.1059    raeburn  11794:         } elsif ($action eq 'display') {
                   11795:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11796:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11797:                        '</div>';
1.1055    raeburn  11798:         }
1.1056    raeburn  11799:         $output .= '</td>';
1.1055    raeburn  11800:     }
                   11801:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11802:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11803:     for (my $i=0; $i<$depth; $i++) {
                   11804:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11805:     }
                   11806:     if ($is_dir) {
                   11807:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11808:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11809:     } else {
                   11810:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11811:     }
                   11812:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11813:                &end_data_table_row();
                   11814:     return $output;
                   11815: }
                   11816: 
                   11817: sub archive_options_form {
1.1065    raeburn  11818:     my ($form,$display,$count,$hiddenelem) = @_;
                   11819:     my %lt = &Apache::lonlocal::texthash(
                   11820:                perm => 'Permanently remove archive file?',
                   11821:                hows => 'How should each extracted item be incorporated in the course?',
                   11822:                cont => 'Content actions for all',
                   11823:                addf => 'Add as folder/file',
                   11824:                incd => 'Include as dependency for a displayed file',
                   11825:                disc => 'Discard',
                   11826:                no   => 'No',
                   11827:                yes  => 'Yes',
                   11828:                save => 'Save',
                   11829:     );
                   11830:     my $output = <<"END";
                   11831: <form name="$form" method="post" action="">
                   11832: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11833: <label>
                   11834:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11835: </label>
                   11836: &nbsp;
                   11837: <label>
                   11838:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11839: </span>
                   11840: </p>
                   11841: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11842: <br />$lt{'hows'}
                   11843: <div class="LC_columnSection">
                   11844:   <fieldset>
                   11845:     <legend>$lt{'cont'}</legend>
                   11846:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11847:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11848:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11849:   </fieldset>
                   11850: </div>
                   11851: END
                   11852:     return $output.
1.1055    raeburn  11853:            &start_data_table()."\n".
1.1065    raeburn  11854:            $display."\n".
1.1055    raeburn  11855:            &end_data_table()."\n".
                   11856:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11857:            $hiddenelem.
1.1065    raeburn  11858:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11859:            '</form>';
                   11860: }
                   11861: 
                   11862: sub archive_javascript {
1.1056    raeburn  11863:     my ($startcount,$numitems,$titles,$children) = @_;
                   11864:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11865:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11866:     my $scripttag = <<START;
                   11867: <script type="text/javascript">
                   11868: // <![CDATA[
                   11869: 
                   11870: function checkAll(form,prefix) {
                   11871:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11872:     for (var i=0; i < form.elements.length; i++) {
                   11873:         var id = form.elements[i].id;
                   11874:         if ((id != '') && (id != undefined)) {
                   11875:             if (idstr.test(id)) {
                   11876:                 if (form.elements[i].type == 'radio') {
                   11877:                     form.elements[i].checked = true;
1.1056    raeburn  11878:                     var nostart = i-$startcount;
1.1059    raeburn  11879:                     var offset = nostart%7;
                   11880:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11881:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11882:                 }
                   11883:             }
                   11884:         }
                   11885:     }
                   11886: }
                   11887: 
                   11888: function propagateCheck(form,count) {
                   11889:     if (count > 0) {
1.1059    raeburn  11890:         var startelement = $startcount + ((count-1) * 7);
                   11891:         for (var j=1; j<6; j++) {
                   11892:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11893:                 var item = startelement + j; 
                   11894:                 if (form.elements[item].type == 'radio') {
                   11895:                     if (form.elements[item].checked) {
                   11896:                         containerCheck(form,count,j);
                   11897:                         break;
                   11898:                     }
1.1055    raeburn  11899:                 }
                   11900:             }
                   11901:         }
                   11902:     }
                   11903: }
                   11904: 
                   11905: numitems = $numitems
1.1056    raeburn  11906: var titles = new Array(numitems);
                   11907: var parents = new Array(numitems);
1.1055    raeburn  11908: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11909:     parents[i] = new Array;
1.1055    raeburn  11910: }
1.1059    raeburn  11911: var maintitle = '$maintitle';
1.1055    raeburn  11912: 
                   11913: START
                   11914: 
1.1056    raeburn  11915:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11916:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11917:         for (my $i=0; $i<@contents; $i ++) {
                   11918:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11919:         }
                   11920:     }
                   11921: 
1.1056    raeburn  11922:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11923:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11924:     }
                   11925: 
1.1055    raeburn  11926:     $scripttag .= <<END;
                   11927: 
                   11928: function containerCheck(form,count,offset) {
                   11929:     if (count > 0) {
1.1056    raeburn  11930:         dependencyCheck(form,count,offset);
1.1059    raeburn  11931:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11932:         form.elements[item].checked = true;
                   11933:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11934:             if (parents[count].length > 0) {
                   11935:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11936:                     containerCheck(form,parents[count][j],offset);
                   11937:                 }
                   11938:             }
                   11939:         }
                   11940:     }
                   11941: }
                   11942: 
                   11943: function dependencyCheck(form,count,offset) {
                   11944:     if (count > 0) {
1.1059    raeburn  11945:         var chosen = (offset+$startcount)+7*(count-1);
                   11946:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11947:         var currtype = form.elements[depitem].type;
                   11948:         if (form.elements[chosen].value == 'dependency') {
                   11949:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11950:             form.elements[depitem].options.length = 0;
                   11951:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  11952:             for (var i=1; i<=numitems; i++) {
                   11953:                 if (i == count) {
                   11954:                     continue;
                   11955:                 }
1.1059    raeburn  11956:                 var startelement = $startcount + (i-1) * 7;
                   11957:                 for (var j=1; j<6; j++) {
                   11958:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11959:                         var item = startelement + j;
                   11960:                         if (form.elements[item].type == 'radio') {
                   11961:                             if (form.elements[item].checked) {
                   11962:                                 if (form.elements[item].value == 'display') {
                   11963:                                     var n = form.elements[depitem].options.length;
                   11964:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11965:                                 }
                   11966:                             }
                   11967:                         }
                   11968:                     }
                   11969:                 }
                   11970:             }
                   11971:         } else {
                   11972:             document.getElementById('arc_depon_'+count).style.display='none';
                   11973:             form.elements[depitem].options.length = 0;
                   11974:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11975:         }
1.1059    raeburn  11976:         titleCheck(form,count,offset);
1.1056    raeburn  11977:     }
                   11978: }
                   11979: 
                   11980: function propagateSelect(form,count,offset) {
                   11981:     if (count > 0) {
1.1065    raeburn  11982:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11983:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11984:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11985:             if (parents[count].length > 0) {
                   11986:                 for (var j=0; j<parents[count].length; j++) {
                   11987:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11988:                 }
                   11989:             }
                   11990:         }
                   11991:     }
                   11992: }
1.1056    raeburn  11993: 
                   11994: function containerSelect(form,count,offset,picked) {
                   11995:     if (count > 0) {
1.1065    raeburn  11996:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11997:         if (form.elements[item].type == 'radio') {
                   11998:             if (form.elements[item].value == 'dependency') {
                   11999:                 if (form.elements[item+1].type == 'select-one') {
                   12000:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12001:                         if (form.elements[item+1].options[i].value == picked) {
                   12002:                             form.elements[item+1].selectedIndex = i;
                   12003:                             break;
                   12004:                         }
                   12005:                     }
                   12006:                 }
                   12007:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12008:                     if (parents[count].length > 0) {
                   12009:                         for (var j=0; j<parents[count].length; j++) {
                   12010:                             containerSelect(form,parents[count][j],offset,picked);
                   12011:                         }
                   12012:                     }
                   12013:                 }
                   12014:             }
                   12015:         }
                   12016:     }
                   12017: }
                   12018: 
1.1059    raeburn  12019: function titleCheck(form,count,offset) {
                   12020:     if (count > 0) {
                   12021:         var chosen = (offset+$startcount)+7*(count-1);
                   12022:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12023:         var currtype = form.elements[depitem].type;
                   12024:         if (form.elements[chosen].value == 'display') {
                   12025:             document.getElementById('arc_title_'+count).style.display='block';
                   12026:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12027:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12028:             }
                   12029:         } else {
                   12030:             document.getElementById('arc_title_'+count).style.display='none';
                   12031:             if (currtype == 'text') { 
                   12032:                 document.getElementById('archive_title_'+count).value='';
                   12033:             }
                   12034:         }
                   12035:     }
                   12036:     return;
                   12037: }
                   12038: 
1.1055    raeburn  12039: // ]]>
                   12040: </script>
                   12041: END
                   12042:     return $scripttag;
                   12043: }
                   12044: 
                   12045: sub process_extracted_files {
1.1067    raeburn  12046:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12047:     my $numitems = $env{'form.archive_count'};
                   12048:     return unless ($numitems);
                   12049:     my @ids=&Apache::lonnet::current_machine_ids();
                   12050:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12051:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12052:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12053:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12054:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12055:         $pathtocheck = "$dir_root/$destination";
                   12056:         $dir = $dir_root;
                   12057:         $ishome = 1;
                   12058:     } else {
                   12059:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12060:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12061:         $dir = "$dir_root/$docudom/$docuname";    
                   12062:     }
                   12063:     my $currdir = "$dir_root/$destination";
                   12064:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12065:     if ($env{'form.folderpath'}) {
                   12066:         my @items = split('&',$env{'form.folderpath'});
                   12067:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12068:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12069:             $containers{'0'}='page';
                   12070:         } else {
                   12071:             $containers{'0'}='sequence';
                   12072:         }
1.1055    raeburn  12073:     }
                   12074:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12075:     if ($numitems) {
                   12076:         for (my $i=1; $i<=$numitems; $i++) {
                   12077:             my $path = $env{'form.archive_content_'.$i};
                   12078:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12079:                 my $item = $1;
                   12080:                 $toplevelitems{$item} = $i;
                   12081:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12082:                     $is_dir{$item} = 1;
                   12083:                 }
                   12084:             }
                   12085:         }
                   12086:     }
1.1067    raeburn  12087:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12088:     if (keys(%toplevelitems) > 0) {
                   12089:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12090:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12091:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12092:     }
1.1066    raeburn  12093:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12094:     if ($numitems) {
                   12095:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12096:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12097:             my $path = $env{'form.archive_content_'.$i};
                   12098:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12099:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12100:                     if ($prefix ne '' && $path ne '') {
                   12101:                         if (-e $prefix.$path) {
1.1066    raeburn  12102:                             if ((@archdirs > 0) && 
                   12103:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12104:                                 $todeletedir{$prefix.$path} = 1;
                   12105:                             } else {
                   12106:                                 $todelete{$prefix.$path} = 1;
                   12107:                             }
1.1055    raeburn  12108:                         }
                   12109:                     }
                   12110:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12111:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12112:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12113:                     $docstitle = $env{'form.archive_title_'.$i};
                   12114:                     if ($docstitle eq '') {
                   12115:                         $docstitle = $title;
                   12116:                     }
1.1055    raeburn  12117:                     $outer = 0;
1.1056    raeburn  12118:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12119:                         if (@{$dirorder{$i}} > 0) {
                   12120:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12121:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12122:                                     $outer = $item;
                   12123:                                     last;
                   12124:                                 }
                   12125:                             }
                   12126:                         }
                   12127:                     }
                   12128:                     my ($errtext,$fatal) = 
                   12129:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12130:                                                '/'.$folders{$outer}.'.'.
                   12131:                                                $containers{$outer});
                   12132:                     next if ($fatal);
                   12133:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12134:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12135:                             $mapinner{$i} = time;
1.1055    raeburn  12136:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12137:                             $containers{$i} = 'sequence';
                   12138:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12139:                                       $folders{$i}.'.'.$containers{$i};
                   12140:                             my $newidx = &LONCAPA::map::getresidx();
                   12141:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12142:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12143:                             push(@LONCAPA::map::order,$newidx);
                   12144:                             my ($outtext,$errtext) =
                   12145:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12146:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12147:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12148:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12149:                             unless ($errtext) {
                   12150:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12151:                             }
1.1055    raeburn  12152:                         }
                   12153:                     } else {
                   12154:                         if ($context eq 'coursedocs') {
                   12155:                             my $newidx=&LONCAPA::map::getresidx();
                   12156:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12157:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12158:                                       $title;
                   12159:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12160:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12161:                             }
                   12162:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12163:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12164:                             }
                   12165:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12166:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12167:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12168:                                 unless ($ishome) {
                   12169:                                     my $fetch = "$newdest{$i}/$title";
                   12170:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12171:                                     $prompttofetch{$fetch} = 1;
                   12172:                                 }
1.1055    raeburn  12173:                             }
                   12174:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12175:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12176:                             push(@LONCAPA::map::order, $newidx);
                   12177:                             my ($outtext,$errtext)=
                   12178:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12179:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12180:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12181:                             unless ($errtext) {
                   12182:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12183:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12184:                                 }
                   12185:                             }
1.1055    raeburn  12186:                         }
                   12187:                     }
1.1075.2.11  raeburn  12188:                 }
                   12189:             } else {
                   12190:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12191:             }
                   12192:         }
                   12193:         for (my $i=1; $i<=$numitems; $i++) {
                   12194:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12195:             my $path = $env{'form.archive_content_'.$i};
                   12196:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12197:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12198:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12199:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12200:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12201:                         my ($itemidx,$fullpath,$relpath);
                   12202:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12203:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12204:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12205:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12206:                                     $itemidx = $j;
1.1056    raeburn  12207:                                 }
                   12208:                             }
1.1075.2.11  raeburn  12209:                         }
                   12210:                         if ($itemidx eq '') {
                   12211:                             $itemidx =  0;
                   12212:                         }
                   12213:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12214:                             if ($mapinner{$referrer{$i}}) {
                   12215:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12216:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12217:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12218:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12219:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12220:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12221:                                             if (!-e $fullpath) {
                   12222:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12223:                                             }
                   12224:                                         }
1.1075.2.11  raeburn  12225:                                     } else {
                   12226:                                         last;
1.1056    raeburn  12227:                                     }
1.1075.2.11  raeburn  12228:                                 }
                   12229:                             }
                   12230:                         } elsif ($newdest{$referrer{$i}}) {
                   12231:                             $fullpath = $newdest{$referrer{$i}};
                   12232:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12233:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12234:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12235:                                     last;
                   12236:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12237:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12238:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12239:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12240:                                         if (!-e $fullpath) {
                   12241:                                             mkdir($fullpath,0755);
1.1056    raeburn  12242:                                         }
                   12243:                                     }
1.1075.2.11  raeburn  12244:                                 } else {
                   12245:                                     last;
1.1056    raeburn  12246:                                 }
1.1075.2.11  raeburn  12247:                             }
                   12248:                         }
                   12249:                         if ($fullpath ne '') {
                   12250:                             if (-e "$prefix$path") {
                   12251:                                 system("mv $prefix$path $fullpath/$title");
                   12252:                             }
                   12253:                             if (-e "$fullpath/$title") {
                   12254:                                 my $showpath;
                   12255:                                 if ($relpath ne '') {
                   12256:                                     $showpath = "$relpath/$title";
                   12257:                                 } else {
                   12258:                                     $showpath = "/$title";
1.1056    raeburn  12259:                                 }
1.1075.2.11  raeburn  12260:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12261:                             }
                   12262:                             unless ($ishome) {
                   12263:                                 my $fetch = "$fullpath/$title";
                   12264:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12265:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12266:                             }
                   12267:                         }
                   12268:                     }
1.1075.2.11  raeburn  12269:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12270:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12271:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12272:                 }
                   12273:             } else {
1.1075.2.11  raeburn  12274:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12275:             }
                   12276:         }
                   12277:         if (keys(%todelete)) {
                   12278:             foreach my $key (keys(%todelete)) {
                   12279:                 unlink($key);
1.1066    raeburn  12280:             }
                   12281:         }
                   12282:         if (keys(%todeletedir)) {
                   12283:             foreach my $key (keys(%todeletedir)) {
                   12284:                 rmdir($key);
                   12285:             }
                   12286:         }
                   12287:         foreach my $dir (sort(keys(%is_dir))) {
                   12288:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12289:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12290:             }
                   12291:         }
1.1067    raeburn  12292:         if ($result ne '') {
                   12293:             $output .= '<ul>'."\n".
                   12294:                        $result."\n".
                   12295:                        '</ul>';
                   12296:         }
                   12297:         unless ($ishome) {
                   12298:             my $replicationfail;
                   12299:             foreach my $item (keys(%prompttofetch)) {
                   12300:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12301:                 unless ($fetchresult eq 'ok') {
                   12302:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12303:                 }
                   12304:             }
                   12305:             if ($replicationfail) {
                   12306:                 $output .= '<p class="LC_error">'.
                   12307:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12308:                            $replicationfail.
                   12309:                            '</ul></p>';
                   12310:             }
                   12311:         }
1.1055    raeburn  12312:     } else {
                   12313:         $warning = &mt('No items found in archive.');
                   12314:     }
                   12315:     if ($error) {
                   12316:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12317:                    $error.'</p>'."\n";
                   12318:     }
                   12319:     if ($warning) {
                   12320:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12321:     }
                   12322:     return $output;
                   12323: }
                   12324: 
1.1066    raeburn  12325: sub cleanup_empty_dirs {
                   12326:     my ($path) = @_;
                   12327:     if (($path ne '') && (-d $path)) {
                   12328:         if (opendir(my $dirh,$path)) {
                   12329:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12330:             my $numitems = 0;
                   12331:             foreach my $item (@dircontents) {
                   12332:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12333:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12334:                     if (-e "$path/$item") {
                   12335:                         $numitems ++;
                   12336:                     }
                   12337:                 } else {
                   12338:                     $numitems ++;
                   12339:                 }
                   12340:             }
                   12341:             if ($numitems == 0) {
                   12342:                 rmdir($path);
                   12343:             }
                   12344:             closedir($dirh);
                   12345:         }
                   12346:     }
                   12347:     return;
                   12348: }
                   12349: 
1.41      ng       12350: =pod
1.45      matthew  12351: 
1.1075.2.56  raeburn  12352: =item * &get_folder_hierarchy()
1.1068    raeburn  12353: 
                   12354: Provides hierarchy of names of folders/sub-folders containing the current
                   12355: item,
                   12356: 
                   12357: Inputs: 3
                   12358:      - $navmap - navmaps object
                   12359: 
                   12360:      - $map - url for map (either the trigger itself, or map containing
                   12361:                            the resource, which is the trigger).
                   12362: 
                   12363:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12364: 
                   12365: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12366: 
                   12367: =cut
                   12368: 
                   12369: sub get_folder_hierarchy {
                   12370:     my ($navmap,$map,$showitem) = @_;
                   12371:     my @pathitems;
                   12372:     if (ref($navmap)) {
                   12373:         my $mapres = $navmap->getResourceByUrl($map);
                   12374:         if (ref($mapres)) {
                   12375:             my $pcslist = $mapres->map_hierarchy();
                   12376:             if ($pcslist ne '') {
                   12377:                 my @pcs = split(/,/,$pcslist);
                   12378:                 foreach my $pc (@pcs) {
                   12379:                     if ($pc == 1) {
1.1075.2.38  raeburn  12380:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12381:                     } else {
                   12382:                         my $res = $navmap->getByMapPc($pc);
                   12383:                         if (ref($res)) {
                   12384:                             my $title = $res->compTitle();
                   12385:                             $title =~ s/\W+/_/g;
                   12386:                             if ($title ne '') {
                   12387:                                 push(@pathitems,$title);
                   12388:                             }
                   12389:                         }
                   12390:                     }
                   12391:                 }
                   12392:             }
1.1071    raeburn  12393:             if ($showitem) {
                   12394:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12395:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12396:                 } else {
                   12397:                     my $maptitle = $mapres->compTitle();
                   12398:                     $maptitle =~ s/\W+/_/g;
                   12399:                     if ($maptitle ne '') {
                   12400:                         push(@pathitems,$maptitle);
                   12401:                     }
1.1068    raeburn  12402:                 }
                   12403:             }
                   12404:         }
                   12405:     }
                   12406:     return @pathitems;
                   12407: }
                   12408: 
                   12409: =pod
                   12410: 
1.1015    raeburn  12411: =item * &get_turnedin_filepath()
                   12412: 
                   12413: Determines path in a user's portfolio file for storage of files uploaded
                   12414: to a specific essayresponse or dropbox item.
                   12415: 
                   12416: Inputs: 3 required + 1 optional.
                   12417: $symb is symb for resource, $uname and $udom are for current user (required).
                   12418: $caller is optional (can be "submission", if routine is called when storing
                   12419: an upoaded file when "Submit Answer" button was pressed).
                   12420: 
                   12421: Returns array containing $path and $multiresp. 
                   12422: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12423: than one file upload item.  Callers of routine should append partid as a 
                   12424: subdirectory to $path in cases where $multiresp is 1.
                   12425: 
                   12426: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12427: 
                   12428: =cut
                   12429: 
                   12430: sub get_turnedin_filepath {
                   12431:     my ($symb,$uname,$udom,$caller) = @_;
                   12432:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12433:     my $turnindir;
                   12434:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12435:     $turnindir = $userhash{'turnindir'};
                   12436:     my ($path,$multiresp);
                   12437:     if ($turnindir eq '') {
                   12438:         if ($caller eq 'submission') {
                   12439:             $turnindir = &mt('turned in');
                   12440:             $turnindir =~ s/\W+/_/g;
                   12441:             my %newhash = (
                   12442:                             'turnindir' => $turnindir,
                   12443:                           );
                   12444:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12445:         }
                   12446:     }
                   12447:     if ($turnindir ne '') {
                   12448:         $path = '/'.$turnindir.'/';
                   12449:         my ($multipart,$turnin,@pathitems);
                   12450:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12451:         if (defined($navmap)) {
                   12452:             my $mapres = $navmap->getResourceByUrl($map);
                   12453:             if (ref($mapres)) {
                   12454:                 my $pcslist = $mapres->map_hierarchy();
                   12455:                 if ($pcslist ne '') {
                   12456:                     foreach my $pc (split(/,/,$pcslist)) {
                   12457:                         my $res = $navmap->getByMapPc($pc);
                   12458:                         if (ref($res)) {
                   12459:                             my $title = $res->compTitle();
                   12460:                             $title =~ s/\W+/_/g;
                   12461:                             if ($title ne '') {
1.1075.2.48  raeburn  12462:                                 if (($pc > 1) && (length($title) > 12)) {
                   12463:                                     $title = substr($title,0,12);
                   12464:                                 }
1.1015    raeburn  12465:                                 push(@pathitems,$title);
                   12466:                             }
                   12467:                         }
                   12468:                     }
                   12469:                 }
                   12470:                 my $maptitle = $mapres->compTitle();
                   12471:                 $maptitle =~ s/\W+/_/g;
                   12472:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12473:                     if (length($maptitle) > 12) {
                   12474:                         $maptitle = substr($maptitle,0,12);
                   12475:                     }
1.1015    raeburn  12476:                     push(@pathitems,$maptitle);
                   12477:                 }
                   12478:                 unless ($env{'request.state'} eq 'construct') {
                   12479:                     my $res = $navmap->getBySymb($symb);
                   12480:                     if (ref($res)) {
                   12481:                         my $partlist = $res->parts();
                   12482:                         my $totaluploads = 0;
                   12483:                         if (ref($partlist) eq 'ARRAY') {
                   12484:                             foreach my $part (@{$partlist}) {
                   12485:                                 my @types = $res->responseType($part);
                   12486:                                 my @ids = $res->responseIds($part);
                   12487:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12488:                                     if ($types[$i] eq 'essay') {
                   12489:                                         my $partid = $part.'_'.$ids[$i];
                   12490:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12491:                                             $totaluploads ++;
                   12492:                                         }
                   12493:                                     }
                   12494:                                 }
                   12495:                             }
                   12496:                             if ($totaluploads > 1) {
                   12497:                                 $multiresp = 1;
                   12498:                             }
                   12499:                         }
                   12500:                     }
                   12501:                 }
                   12502:             } else {
                   12503:                 return;
                   12504:             }
                   12505:         } else {
                   12506:             return;
                   12507:         }
                   12508:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12509:         $restitle =~ s/\W+/_/g;
                   12510:         if ($restitle eq '') {
                   12511:             $restitle = ($resurl =~ m{/[^/]+$});
                   12512:             if ($restitle eq '') {
                   12513:                 $restitle = time;
                   12514:             }
                   12515:         }
1.1075.2.48  raeburn  12516:         if (length($restitle) > 12) {
                   12517:             $restitle = substr($restitle,0,12);
                   12518:         }
1.1015    raeburn  12519:         push(@pathitems,$restitle);
                   12520:         $path .= join('/',@pathitems);
                   12521:     }
                   12522:     return ($path,$multiresp);
                   12523: }
                   12524: 
                   12525: =pod
                   12526: 
1.464     albertel 12527: =back
1.41      ng       12528: 
1.112     bowersj2 12529: =head1 CSV Upload/Handling functions
1.38      albertel 12530: 
1.41      ng       12531: =over 4
                   12532: 
1.648     raeburn  12533: =item * &upfile_store($r)
1.41      ng       12534: 
                   12535: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12536: needs $env{'form.upfile'}
1.41      ng       12537: returns $datatoken to be put into hidden field
                   12538: 
                   12539: =cut
1.31      albertel 12540: 
                   12541: sub upfile_store {
                   12542:     my $r=shift;
1.258     albertel 12543:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12544:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12545:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12546:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12547: 
1.258     albertel 12548:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12549: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12550:     {
1.158     raeburn  12551:         my $datafile = $r->dir_config('lonDaemons').
                   12552:                            '/tmp/'.$datatoken.'.tmp';
                   12553:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12554:             print $fh $env{'form.upfile'};
1.158     raeburn  12555:             close($fh);
                   12556:         }
1.31      albertel 12557:     }
                   12558:     return $datatoken;
                   12559: }
                   12560: 
1.56      matthew  12561: =pod
                   12562: 
1.648     raeburn  12563: =item * &load_tmp_file($r)
1.41      ng       12564: 
                   12565: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12566: needs $env{'form.datatoken'},
                   12567: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12568: 
                   12569: =cut
1.31      albertel 12570: 
                   12571: sub load_tmp_file {
                   12572:     my $r=shift;
                   12573:     my @studentdata=();
                   12574:     {
1.158     raeburn  12575:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12576:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12577:         if ( open(my $fh,"<$studentfile") ) {
                   12578:             @studentdata=<$fh>;
                   12579:             close($fh);
                   12580:         }
1.31      albertel 12581:     }
1.258     albertel 12582:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12583: }
                   12584: 
1.56      matthew  12585: =pod
                   12586: 
1.648     raeburn  12587: =item * &upfile_record_sep()
1.41      ng       12588: 
                   12589: Separate uploaded file into records
                   12590: returns array of records,
1.258     albertel 12591: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12592: 
                   12593: =cut
1.31      albertel 12594: 
                   12595: sub upfile_record_sep {
1.258     albertel 12596:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12597:     } else {
1.248     albertel 12598: 	my @records;
1.258     albertel 12599: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12600: 	    if ($line=~/^\s*$/) { next; }
                   12601: 	    push(@records,$line);
                   12602: 	}
                   12603: 	return @records;
1.31      albertel 12604:     }
                   12605: }
                   12606: 
1.56      matthew  12607: =pod
                   12608: 
1.648     raeburn  12609: =item * &record_sep($record)
1.41      ng       12610: 
1.258     albertel 12611: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12612: 
                   12613: =cut
                   12614: 
1.263     www      12615: sub takeleft {
                   12616:     my $index=shift;
                   12617:     return substr('0000'.$index,-4,4);
                   12618: }
                   12619: 
1.31      albertel 12620: sub record_sep {
                   12621:     my $record=shift;
                   12622:     my %components=();
1.258     albertel 12623:     if ($env{'form.upfiletype'} eq 'xml') {
                   12624:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12625:         my $i=0;
1.356     albertel 12626:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12627:             $field=~s/^(\"|\')//;
                   12628:             $field=~s/(\"|\')$//;
1.263     www      12629:             $components{&takeleft($i)}=$field;
1.31      albertel 12630:             $i++;
                   12631:         }
1.258     albertel 12632:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12633:         my $i=0;
1.356     albertel 12634:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12635:             $field=~s/^(\"|\')//;
                   12636:             $field=~s/(\"|\')$//;
1.263     www      12637:             $components{&takeleft($i)}=$field;
1.31      albertel 12638:             $i++;
                   12639:         }
                   12640:     } else {
1.561     www      12641:         my $separator=',';
1.480     banghart 12642:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12643:             $separator=';';
1.480     banghart 12644:         }
1.31      albertel 12645:         my $i=0;
1.561     www      12646: # the character we are looking for to indicate the end of a quote or a record 
                   12647:         my $looking_for=$separator;
                   12648: # do not add the characters to the fields
                   12649:         my $ignore=0;
                   12650: # we just encountered a separator (or the beginning of the record)
                   12651:         my $just_found_separator=1;
                   12652: # store the field we are working on here
                   12653:         my $field='';
                   12654: # work our way through all characters in record
                   12655:         foreach my $character ($record=~/(.)/g) {
                   12656:             if ($character eq $looking_for) {
                   12657:                if ($character ne $separator) {
                   12658: # Found the end of a quote, again looking for separator
                   12659:                   $looking_for=$separator;
                   12660:                   $ignore=1;
                   12661:                } else {
                   12662: # Found a separator, store away what we got
                   12663:                   $components{&takeleft($i)}=$field;
                   12664: 	          $i++;
                   12665:                   $just_found_separator=1;
                   12666:                   $ignore=0;
                   12667:                   $field='';
                   12668:                }
                   12669:                next;
                   12670:             }
                   12671: # single or double quotation marks after a separator indicate beginning of a quote
                   12672: # we are now looking for the end of the quote and need to ignore separators
                   12673:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12674:                $looking_for=$character;
                   12675:                next;
                   12676:             }
                   12677: # ignore would be true after we reached the end of a quote
                   12678:             if ($ignore) { next; }
                   12679:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12680:             $field.=$character;
                   12681:             $just_found_separator=0; 
1.31      albertel 12682:         }
1.561     www      12683: # catch the very last entry, since we never encountered the separator
                   12684:         $components{&takeleft($i)}=$field;
1.31      albertel 12685:     }
                   12686:     return %components;
                   12687: }
                   12688: 
1.144     matthew  12689: ######################################################
                   12690: ######################################################
                   12691: 
1.56      matthew  12692: =pod
                   12693: 
1.648     raeburn  12694: =item * &upfile_select_html()
1.41      ng       12695: 
1.144     matthew  12696: Return HTML code to select a file from the users machine and specify 
                   12697: the file type.
1.41      ng       12698: 
                   12699: =cut
                   12700: 
1.144     matthew  12701: ######################################################
                   12702: ######################################################
1.31      albertel 12703: sub upfile_select_html {
1.144     matthew  12704:     my %Types = (
                   12705:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12706:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12707:                  space => &mt('Space separated'),
                   12708:                  tab   => &mt('Tabulator separated'),
                   12709: #                 xml   => &mt('HTML/XML'),
                   12710:                  );
                   12711:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12712:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12713:     foreach my $type (sort(keys(%Types))) {
                   12714:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12715:     }
                   12716:     $Str .= "</select>\n";
                   12717:     return $Str;
1.31      albertel 12718: }
                   12719: 
1.301     albertel 12720: sub get_samples {
                   12721:     my ($records,$toget) = @_;
                   12722:     my @samples=({});
                   12723:     my $got=0;
                   12724:     foreach my $rec (@$records) {
                   12725: 	my %temp = &record_sep($rec);
                   12726: 	if (! grep(/\S/, values(%temp))) { next; }
                   12727: 	if (%temp) {
                   12728: 	    $samples[$got]=\%temp;
                   12729: 	    $got++;
                   12730: 	    if ($got == $toget) { last; }
                   12731: 	}
                   12732:     }
                   12733:     return \@samples;
                   12734: }
                   12735: 
1.144     matthew  12736: ######################################################
                   12737: ######################################################
                   12738: 
1.56      matthew  12739: =pod
                   12740: 
1.648     raeburn  12741: =item * &csv_print_samples($r,$records)
1.41      ng       12742: 
                   12743: Prints a table of sample values from each column uploaded $r is an
                   12744: Apache Request ref, $records is an arrayref from
                   12745: &Apache::loncommon::upfile_record_sep
                   12746: 
                   12747: =cut
                   12748: 
1.144     matthew  12749: ######################################################
                   12750: ######################################################
1.31      albertel 12751: sub csv_print_samples {
                   12752:     my ($r,$records) = @_;
1.662     bisitz   12753:     my $samples = &get_samples($records,5);
1.301     albertel 12754: 
1.594     raeburn  12755:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12756:               &start_data_table_header_row());
1.356     albertel 12757:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12758:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12759:     $r->print(&end_data_table_header_row());
1.301     albertel 12760:     foreach my $hash (@$samples) {
1.594     raeburn  12761: 	$r->print(&start_data_table_row());
1.356     albertel 12762: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12763: 	    $r->print('<td>');
1.356     albertel 12764: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12765: 	    $r->print('</td>');
                   12766: 	}
1.594     raeburn  12767: 	$r->print(&end_data_table_row());
1.31      albertel 12768:     }
1.594     raeburn  12769:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12770: }
                   12771: 
1.144     matthew  12772: ######################################################
                   12773: ######################################################
                   12774: 
1.56      matthew  12775: =pod
                   12776: 
1.648     raeburn  12777: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12778: 
                   12779: Prints a table to create associations between values and table columns.
1.144     matthew  12780: 
1.41      ng       12781: $r is an Apache Request ref,
                   12782: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12783: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12784: 
                   12785: =cut
                   12786: 
1.144     matthew  12787: ######################################################
                   12788: ######################################################
1.31      albertel 12789: sub csv_print_select_table {
                   12790:     my ($r,$records,$d) = @_;
1.301     albertel 12791:     my $i=0;
                   12792:     my $samples = &get_samples($records,1);
1.144     matthew  12793:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12794: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12795:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12796:               '<th>'.&mt('Column').'</th>'.
                   12797:               &end_data_table_header_row()."\n");
1.356     albertel 12798:     foreach my $array_ref (@$d) {
                   12799: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12800: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12801: 
1.875     bisitz   12802: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12803: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12804: 	$r->print('<option value="none"></option>');
1.356     albertel 12805: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12806: 	    $r->print('<option value="'.$sample.'"'.
                   12807:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12808:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12809: 	}
1.594     raeburn  12810: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12811: 	$i++;
                   12812:     }
1.594     raeburn  12813:     $r->print(&end_data_table());
1.31      albertel 12814:     $i--;
                   12815:     return $i;
                   12816: }
1.56      matthew  12817: 
1.144     matthew  12818: ######################################################
                   12819: ######################################################
                   12820: 
1.56      matthew  12821: =pod
1.31      albertel 12822: 
1.648     raeburn  12823: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12824: 
                   12825: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12826: 
                   12827: $r is an Apache Request ref,
                   12828: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12829: $d is an array of 2 element arrays (internal name, displayed name)
                   12830: 
                   12831: =cut
                   12832: 
1.144     matthew  12833: ######################################################
                   12834: ######################################################
1.31      albertel 12835: sub csv_samples_select_table {
                   12836:     my ($r,$records,$d) = @_;
                   12837:     my $i=0;
1.144     matthew  12838:     #
1.662     bisitz   12839:     my $max_samples = 5;
                   12840:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12841:     $r->print(&start_data_table().
                   12842:               &start_data_table_header_row().'<th>'.
                   12843:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12844:               &end_data_table_header_row());
1.301     albertel 12845: 
                   12846:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12847: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12848: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12849: 	foreach my $option (@$d) {
                   12850: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12851: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12852:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12853:                       $display.'</option>');
1.31      albertel 12854: 	}
                   12855: 	$r->print('</select></td><td>');
1.662     bisitz   12856: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12857: 	    if (defined($samples->[$line]{$key})) { 
                   12858: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12859: 	    }
                   12860: 	}
1.594     raeburn  12861: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12862: 	$i++;
                   12863:     }
1.594     raeburn  12864:     $r->print(&end_data_table());
1.31      albertel 12865:     $i--;
                   12866:     return($i);
1.115     matthew  12867: }
                   12868: 
1.144     matthew  12869: ######################################################
                   12870: ######################################################
                   12871: 
1.115     matthew  12872: =pod
                   12873: 
1.648     raeburn  12874: =item * &clean_excel_name($name)
1.115     matthew  12875: 
                   12876: Returns a replacement for $name which does not contain any illegal characters.
                   12877: 
                   12878: =cut
                   12879: 
1.144     matthew  12880: ######################################################
                   12881: ######################################################
1.115     matthew  12882: sub clean_excel_name {
                   12883:     my ($name) = @_;
                   12884:     $name =~ s/[:\*\?\/\\]//g;
                   12885:     if (length($name) > 31) {
                   12886:         $name = substr($name,0,31);
                   12887:     }
                   12888:     return $name;
1.25      albertel 12889: }
1.84      albertel 12890: 
1.85      albertel 12891: =pod
                   12892: 
1.648     raeburn  12893: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12894: 
                   12895: Returns either 1 or undef
                   12896: 
                   12897: 1 if the part is to be hidden, undef if it is to be shown
                   12898: 
                   12899: Arguments are:
                   12900: 
                   12901: $id the id of the part to be checked
                   12902: $symb, optional the symb of the resource to check
                   12903: $udom, optional the domain of the user to check for
                   12904: $uname, optional the username of the user to check for
                   12905: 
                   12906: =cut
1.84      albertel 12907: 
                   12908: sub check_if_partid_hidden {
                   12909:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12910:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12911: 					 $symb,$udom,$uname);
1.141     albertel 12912:     my $truth=1;
                   12913:     #if the string starts with !, then the list is the list to show not hide
                   12914:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12915:     my @hiddenlist=split(/,/,$hiddenparts);
                   12916:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12917: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12918:     }
1.141     albertel 12919:     return !$truth;
1.84      albertel 12920: }
1.127     matthew  12921: 
1.138     matthew  12922: 
                   12923: ############################################################
                   12924: ############################################################
                   12925: 
                   12926: =pod
                   12927: 
1.157     matthew  12928: =back 
                   12929: 
1.138     matthew  12930: =head1 cgi-bin script and graphing routines
                   12931: 
1.157     matthew  12932: =over 4
                   12933: 
1.648     raeburn  12934: =item * &get_cgi_id()
1.138     matthew  12935: 
                   12936: Inputs: none
                   12937: 
                   12938: Returns an id which can be used to pass environment variables
                   12939: to various cgi-bin scripts.  These environment variables will
                   12940: be removed from the users environment after a given time by
                   12941: the routine &Apache::lonnet::transfer_profile_to_env.
                   12942: 
                   12943: =cut
                   12944: 
                   12945: ############################################################
                   12946: ############################################################
1.152     albertel 12947: my $uniq=0;
1.136     matthew  12948: sub get_cgi_id {
1.154     albertel 12949:     $uniq=($uniq+1)%100000;
1.280     albertel 12950:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12951: }
                   12952: 
1.127     matthew  12953: ############################################################
                   12954: ############################################################
                   12955: 
                   12956: =pod
                   12957: 
1.648     raeburn  12958: =item * &DrawBarGraph()
1.127     matthew  12959: 
1.138     matthew  12960: Facilitates the plotting of data in a (stacked) bar graph.
                   12961: Puts plot definition data into the users environment in order for 
                   12962: graph.png to plot it.  Returns an <img> tag for the plot.
                   12963: The bars on the plot are labeled '1','2',...,'n'.
                   12964: 
                   12965: Inputs:
                   12966: 
                   12967: =over 4
                   12968: 
                   12969: =item $Title: string, the title of the plot
                   12970: 
                   12971: =item $xlabel: string, text describing the X-axis of the plot
                   12972: 
                   12973: =item $ylabel: string, text describing the Y-axis of the plot
                   12974: 
                   12975: =item $Max: scalar, the maximum Y value to use in the plot
                   12976: If $Max is < any data point, the graph will not be rendered.
                   12977: 
1.140     matthew  12978: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12979: they are plotted.  If undefined, default values will be used.
                   12980: 
1.178     matthew  12981: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12982: 
1.138     matthew  12983: =item @Values: An array of array references.  Each array reference holds data
                   12984: to be plotted in a stacked bar chart.
                   12985: 
1.239     matthew  12986: =item If the final element of @Values is a hash reference the key/value
                   12987: pairs will be added to the graph definition.
                   12988: 
1.138     matthew  12989: =back
                   12990: 
                   12991: Returns:
                   12992: 
                   12993: An <img> tag which references graph.png and the appropriate identifying
                   12994: information for the plot.
                   12995: 
1.127     matthew  12996: =cut
                   12997: 
                   12998: ############################################################
                   12999: ############################################################
1.134     matthew  13000: sub DrawBarGraph {
1.178     matthew  13001:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13002:     #
                   13003:     if (! defined($colors)) {
                   13004:         $colors = ['#33ff00', 
                   13005:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13006:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13007:                   ]; 
                   13008:     }
1.228     matthew  13009:     my $extra_settings = {};
                   13010:     if (ref($Values[-1]) eq 'HASH') {
                   13011:         $extra_settings = pop(@Values);
                   13012:     }
1.127     matthew  13013:     #
1.136     matthew  13014:     my $identifier = &get_cgi_id();
                   13015:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13016:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13017:         return '';
                   13018:     }
1.225     matthew  13019:     #
                   13020:     my @Labels;
                   13021:     if (defined($labels)) {
                   13022:         @Labels = @$labels;
                   13023:     } else {
                   13024:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13025:             push (@Labels,$i+1);
                   13026:         }
                   13027:     }
                   13028:     #
1.129     matthew  13029:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13030:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13031:     my %ValuesHash;
                   13032:     my $NumSets=1;
                   13033:     foreach my $array (@Values) {
                   13034:         next if (! ref($array));
1.136     matthew  13035:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13036:             join(',',@$array);
1.129     matthew  13037:     }
1.127     matthew  13038:     #
1.136     matthew  13039:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13040:     if ($NumBars < 3) {
                   13041:         $width = 120+$NumBars*32;
1.220     matthew  13042:         $xskip = 1;
1.225     matthew  13043:         $bar_width = 30;
                   13044:     } elsif ($NumBars < 5) {
                   13045:         $width = 120+$NumBars*20;
                   13046:         $xskip = 1;
                   13047:         $bar_width = 20;
1.220     matthew  13048:     } elsif ($NumBars < 10) {
1.136     matthew  13049:         $width = 120+$NumBars*15;
                   13050:         $xskip = 1;
                   13051:         $bar_width = 15;
                   13052:     } elsif ($NumBars <= 25) {
                   13053:         $width = 120+$NumBars*11;
                   13054:         $xskip = 5;
                   13055:         $bar_width = 8;
                   13056:     } elsif ($NumBars <= 50) {
                   13057:         $width = 120+$NumBars*8;
                   13058:         $xskip = 5;
                   13059:         $bar_width = 4;
                   13060:     } else {
                   13061:         $width = 120+$NumBars*8;
                   13062:         $xskip = 5;
                   13063:         $bar_width = 4;
                   13064:     }
                   13065:     #
1.137     matthew  13066:     $Max = 1 if ($Max < 1);
                   13067:     if ( int($Max) < $Max ) {
                   13068:         $Max++;
                   13069:         $Max = int($Max);
                   13070:     }
1.127     matthew  13071:     $Title  = '' if (! defined($Title));
                   13072:     $xlabel = '' if (! defined($xlabel));
                   13073:     $ylabel = '' if (! defined($ylabel));
1.369     www      13074:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13075:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13076:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13077:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13078:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13079:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13080:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13081:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13082:     $ValuesHash{$id.'.height'}   = $height;
                   13083:     $ValuesHash{$id.'.width'}    = $width;
                   13084:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13085:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13086:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13087:     #
1.228     matthew  13088:     # Deal with other parameters
                   13089:     while (my ($key,$value) = each(%$extra_settings)) {
                   13090:         $ValuesHash{$id.'.'.$key} = $value;
                   13091:     }
                   13092:     #
1.646     raeburn  13093:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13094:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13095: }
                   13096: 
                   13097: ############################################################
                   13098: ############################################################
                   13099: 
                   13100: =pod
                   13101: 
1.648     raeburn  13102: =item * &DrawXYGraph()
1.137     matthew  13103: 
1.138     matthew  13104: Facilitates the plotting of data in an XY graph.
                   13105: Puts plot definition data into the users environment in order for 
                   13106: graph.png to plot it.  Returns an <img> tag for the plot.
                   13107: 
                   13108: Inputs:
                   13109: 
                   13110: =over 4
                   13111: 
                   13112: =item $Title: string, the title of the plot
                   13113: 
                   13114: =item $xlabel: string, text describing the X-axis of the plot
                   13115: 
                   13116: =item $ylabel: string, text describing the Y-axis of the plot
                   13117: 
                   13118: =item $Max: scalar, the maximum Y value to use in the plot
                   13119: If $Max is < any data point, the graph will not be rendered.
                   13120: 
                   13121: =item $colors: Array ref containing the hex color codes for the data to be 
                   13122: plotted in.  If undefined, default values will be used.
                   13123: 
                   13124: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13125: 
                   13126: =item $Ydata: Array ref containing Array refs.  
1.185     www      13127: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13128: 
                   13129: =item %Values: hash indicating or overriding any default values which are 
                   13130: passed to graph.png.  
                   13131: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13132: 
                   13133: =back
                   13134: 
                   13135: Returns:
                   13136: 
                   13137: An <img> tag which references graph.png and the appropriate identifying
                   13138: information for the plot.
                   13139: 
1.137     matthew  13140: =cut
                   13141: 
                   13142: ############################################################
                   13143: ############################################################
                   13144: sub DrawXYGraph {
                   13145:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13146:     #
                   13147:     # Create the identifier for the graph
                   13148:     my $identifier = &get_cgi_id();
                   13149:     my $id = 'cgi.'.$identifier;
                   13150:     #
                   13151:     $Title  = '' if (! defined($Title));
                   13152:     $xlabel = '' if (! defined($xlabel));
                   13153:     $ylabel = '' if (! defined($ylabel));
                   13154:     my %ValuesHash = 
                   13155:         (
1.369     www      13156:          $id.'.title'  => &escape($Title),
                   13157:          $id.'.xlabel' => &escape($xlabel),
                   13158:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13159:          $id.'.y_max_value'=> $Max,
                   13160:          $id.'.labels'     => join(',',@$Xlabels),
                   13161:          $id.'.PlotType'   => 'XY',
                   13162:          );
                   13163:     #
                   13164:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13165:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13166:     }
                   13167:     #
                   13168:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13169:         return '';
                   13170:     }
                   13171:     my $NumSets=1;
1.138     matthew  13172:     foreach my $array (@{$Ydata}){
1.137     matthew  13173:         next if (! ref($array));
                   13174:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13175:     }
1.138     matthew  13176:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13177:     #
                   13178:     # Deal with other parameters
                   13179:     while (my ($key,$value) = each(%Values)) {
                   13180:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13181:     }
                   13182:     #
1.646     raeburn  13183:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13184:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13185: }
                   13186: 
                   13187: ############################################################
                   13188: ############################################################
                   13189: 
                   13190: =pod
                   13191: 
1.648     raeburn  13192: =item * &DrawXYYGraph()
1.138     matthew  13193: 
                   13194: Facilitates the plotting of data in an XY graph with two Y axes.
                   13195: Puts plot definition data into the users environment in order for 
                   13196: graph.png to plot it.  Returns an <img> tag for the plot.
                   13197: 
                   13198: Inputs:
                   13199: 
                   13200: =over 4
                   13201: 
                   13202: =item $Title: string, the title of the plot
                   13203: 
                   13204: =item $xlabel: string, text describing the X-axis of the plot
                   13205: 
                   13206: =item $ylabel: string, text describing the Y-axis of the plot
                   13207: 
                   13208: =item $colors: Array ref containing the hex color codes for the data to be 
                   13209: plotted in.  If undefined, default values will be used.
                   13210: 
                   13211: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13212: 
                   13213: =item $Ydata1: The first data set
                   13214: 
                   13215: =item $Min1: The minimum value of the left Y-axis
                   13216: 
                   13217: =item $Max1: The maximum value of the left Y-axis
                   13218: 
                   13219: =item $Ydata2: The second data set
                   13220: 
                   13221: =item $Min2: The minimum value of the right Y-axis
                   13222: 
                   13223: =item $Max2: The maximum value of the left Y-axis
                   13224: 
                   13225: =item %Values: hash indicating or overriding any default values which are 
                   13226: passed to graph.png.  
                   13227: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13228: 
                   13229: =back
                   13230: 
                   13231: Returns:
                   13232: 
                   13233: An <img> tag which references graph.png and the appropriate identifying
                   13234: information for the plot.
1.136     matthew  13235: 
                   13236: =cut
                   13237: 
                   13238: ############################################################
                   13239: ############################################################
1.137     matthew  13240: sub DrawXYYGraph {
                   13241:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13242:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13243:     #
                   13244:     # Create the identifier for the graph
                   13245:     my $identifier = &get_cgi_id();
                   13246:     my $id = 'cgi.'.$identifier;
                   13247:     #
                   13248:     $Title  = '' if (! defined($Title));
                   13249:     $xlabel = '' if (! defined($xlabel));
                   13250:     $ylabel = '' if (! defined($ylabel));
                   13251:     my %ValuesHash = 
                   13252:         (
1.369     www      13253:          $id.'.title'  => &escape($Title),
                   13254:          $id.'.xlabel' => &escape($xlabel),
                   13255:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13256:          $id.'.labels' => join(',',@$Xlabels),
                   13257:          $id.'.PlotType' => 'XY',
                   13258:          $id.'.NumSets' => 2,
1.137     matthew  13259:          $id.'.two_axes' => 1,
                   13260:          $id.'.y1_max_value' => $Max1,
                   13261:          $id.'.y1_min_value' => $Min1,
                   13262:          $id.'.y2_max_value' => $Max2,
                   13263:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13264:          );
                   13265:     #
1.137     matthew  13266:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13267:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13268:     }
                   13269:     #
                   13270:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13271:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13272:         return '';
                   13273:     }
                   13274:     my $NumSets=1;
1.137     matthew  13275:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13276:         next if (! ref($array));
                   13277:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13278:     }
                   13279:     #
                   13280:     # Deal with other parameters
                   13281:     while (my ($key,$value) = each(%Values)) {
                   13282:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13283:     }
                   13284:     #
1.646     raeburn  13285:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13286:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13287: }
                   13288: 
                   13289: ############################################################
                   13290: ############################################################
                   13291: 
                   13292: =pod
                   13293: 
1.157     matthew  13294: =back 
                   13295: 
1.139     matthew  13296: =head1 Statistics helper routines?  
                   13297: 
                   13298: Bad place for them but what the hell.
                   13299: 
1.157     matthew  13300: =over 4
                   13301: 
1.648     raeburn  13302: =item * &chartlink()
1.139     matthew  13303: 
                   13304: Returns a link to the chart for a specific student.  
                   13305: 
                   13306: Inputs:
                   13307: 
                   13308: =over 4
                   13309: 
                   13310: =item $linktext: The text of the link
                   13311: 
                   13312: =item $sname: The students username
                   13313: 
                   13314: =item $sdomain: The students domain
                   13315: 
                   13316: =back
                   13317: 
1.157     matthew  13318: =back
                   13319: 
1.139     matthew  13320: =cut
                   13321: 
                   13322: ############################################################
                   13323: ############################################################
                   13324: sub chartlink {
                   13325:     my ($linktext, $sname, $sdomain) = @_;
                   13326:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13327:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13328:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13329:        '">'.$linktext.'</a>';
1.153     matthew  13330: }
                   13331: 
                   13332: #######################################################
                   13333: #######################################################
                   13334: 
                   13335: =pod
                   13336: 
                   13337: =head1 Course Environment Routines
1.157     matthew  13338: 
                   13339: =over 4
1.153     matthew  13340: 
1.648     raeburn  13341: =item * &restore_course_settings()
1.153     matthew  13342: 
1.648     raeburn  13343: =item * &store_course_settings()
1.153     matthew  13344: 
                   13345: Restores/Store indicated form parameters from the course environment.
                   13346: Will not overwrite existing values of the form parameters.
                   13347: 
                   13348: Inputs: 
                   13349: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13350: 
                   13351: a hash ref describing the data to be stored.  For example:
                   13352:    
                   13353: %Save_Parameters = ('Status' => 'scalar',
                   13354:     'chartoutputmode' => 'scalar',
                   13355:     'chartoutputdata' => 'scalar',
                   13356:     'Section' => 'array',
1.373     raeburn  13357:     'Group' => 'array',
1.153     matthew  13358:     'StudentData' => 'array',
                   13359:     'Maps' => 'array');
                   13360: 
                   13361: Returns: both routines return nothing
                   13362: 
1.631     raeburn  13363: =back
                   13364: 
1.153     matthew  13365: =cut
                   13366: 
                   13367: #######################################################
                   13368: #######################################################
                   13369: sub store_course_settings {
1.496     albertel 13370:     return &store_settings($env{'request.course.id'},@_);
                   13371: }
                   13372: 
                   13373: sub store_settings {
1.153     matthew  13374:     # save to the environment
                   13375:     # appenv the same items, just to be safe
1.300     albertel 13376:     my $udom  = $env{'user.domain'};
                   13377:     my $uname = $env{'user.name'};
1.496     albertel 13378:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13379:     my %SaveHash;
                   13380:     my %AppHash;
                   13381:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13382:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13383:         my $envname = 'environment.'.$basename;
1.258     albertel 13384:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13385:             # Save this value away
                   13386:             if ($type eq 'scalar' &&
1.258     albertel 13387:                 (! exists($env{$envname}) || 
                   13388:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13389:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13390:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13391:             } elsif ($type eq 'array') {
                   13392:                 my $stored_form;
1.258     albertel 13393:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13394:                     $stored_form = join(',',
                   13395:                                         map {
1.369     www      13396:                                             &escape($_);
1.258     albertel 13397:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13398:                 } else {
                   13399:                     $stored_form = 
1.369     www      13400:                         &escape($env{'form.'.$setting});
1.153     matthew  13401:                 }
                   13402:                 # Determine if the array contents are the same.
1.258     albertel 13403:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13404:                     $SaveHash{$basename} = $stored_form;
                   13405:                     $AppHash{$envname}   = $stored_form;
                   13406:                 }
                   13407:             }
                   13408:         }
                   13409:     }
                   13410:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13411:                                           $udom,$uname);
1.153     matthew  13412:     if ($put_result !~ /^(ok|delayed)/) {
                   13413:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13414:                                  'got error:'.$put_result);
                   13415:     }
                   13416:     # Make sure these settings stick around in this session, too
1.646     raeburn  13417:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13418:     return;
                   13419: }
                   13420: 
                   13421: sub restore_course_settings {
1.499     albertel 13422:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13423: }
                   13424: 
                   13425: sub restore_settings {
                   13426:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13427:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13428:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13429:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13430:             '.'.$setting;
1.258     albertel 13431:         if (exists($env{$envname})) {
1.153     matthew  13432:             if ($type eq 'scalar') {
1.258     albertel 13433:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13434:             } elsif ($type eq 'array') {
1.258     albertel 13435:                 $env{'form.'.$setting} = [ 
1.153     matthew  13436:                                            map { 
1.369     www      13437:                                                &unescape($_); 
1.258     albertel 13438:                                            } split(',',$env{$envname})
1.153     matthew  13439:                                            ];
                   13440:             }
                   13441:         }
                   13442:     }
1.127     matthew  13443: }
                   13444: 
1.618     raeburn  13445: #######################################################
                   13446: #######################################################
                   13447: 
                   13448: =pod
                   13449: 
                   13450: =head1 Domain E-mail Routines  
                   13451: 
                   13452: =over 4
                   13453: 
1.648     raeburn  13454: =item * &build_recipient_list()
1.618     raeburn  13455: 
1.1075.2.44  raeburn  13456: Build recipient lists for following types of e-mail:
1.766     raeburn  13457: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13458: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13459: module change checking, student/employee ID conflict checks, as
                   13460: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13461: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13462: 
                   13463: Inputs:
1.1075.2.44  raeburn  13464: defmail (scalar - email address of default recipient),
                   13465: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13466: requestsmail, updatesmail, or idconflictsmail).
                   13467: 
1.619     raeburn  13468: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13469: 
                   13470: origmail (scalar - email address of recipient from loncapa.conf,
                   13471: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13472: 
1.655     raeburn  13473: Returns: comma separated list of addresses to which to send e-mail.
                   13474: 
                   13475: =back
1.618     raeburn  13476: 
                   13477: =cut
                   13478: 
                   13479: ############################################################
                   13480: ############################################################
                   13481: sub build_recipient_list {
1.619     raeburn  13482:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13483:     my @recipients;
                   13484:     my $otheremails;
                   13485:     my %domconfig =
                   13486:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13487:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13488:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13489:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13490:                 my @contacts = ('adminemail','supportemail');
                   13491:                 foreach my $item (@contacts) {
                   13492:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13493:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13494:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13495:                             push(@recipients,$addr);
                   13496:                         }
1.619     raeburn  13497:                     }
1.766     raeburn  13498:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13499:                 }
                   13500:             }
1.766     raeburn  13501:         } elsif ($origmail ne '') {
                   13502:             push(@recipients,$origmail);
1.618     raeburn  13503:         }
1.619     raeburn  13504:     } elsif ($origmail ne '') {
                   13505:         push(@recipients,$origmail);
1.618     raeburn  13506:     }
1.688     raeburn  13507:     if (defined($defmail)) {
                   13508:         if ($defmail ne '') {
                   13509:             push(@recipients,$defmail);
                   13510:         }
1.618     raeburn  13511:     }
                   13512:     if ($otheremails) {
1.619     raeburn  13513:         my @others;
                   13514:         if ($otheremails =~ /,/) {
                   13515:             @others = split(/,/,$otheremails);
1.618     raeburn  13516:         } else {
1.619     raeburn  13517:             push(@others,$otheremails);
                   13518:         }
                   13519:         foreach my $addr (@others) {
                   13520:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13521:                 push(@recipients,$addr);
                   13522:             }
1.618     raeburn  13523:         }
                   13524:     }
1.619     raeburn  13525:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13526:     return $recipientlist;
                   13527: }
                   13528: 
1.127     matthew  13529: ############################################################
                   13530: ############################################################
1.154     albertel 13531: 
1.655     raeburn  13532: =pod
                   13533: 
                   13534: =head1 Course Catalog Routines
                   13535: 
                   13536: =over 4
                   13537: 
                   13538: =item * &gather_categories()
                   13539: 
                   13540: Converts category definitions - keys of categories hash stored in  
                   13541: coursecategories in configuration.db on the primary library server in a 
                   13542: domain - to an array.  Also generates javascript and idx hash used to 
                   13543: generate Domain Coordinator interface for editing Course Categories.
                   13544: 
                   13545: Inputs:
1.663     raeburn  13546: 
1.655     raeburn  13547: categories (reference to hash of category definitions).
1.663     raeburn  13548: 
1.655     raeburn  13549: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13550:       categories and subcategories).
1.663     raeburn  13551: 
1.655     raeburn  13552: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13553:       editing Course Categories).
1.663     raeburn  13554: 
1.655     raeburn  13555: jsarray (reference to array of categories used to create Javascript arrays for
                   13556:          Domain Coordinator interface for editing Course Categories).
                   13557: 
                   13558: Returns: nothing
                   13559: 
                   13560: Side effects: populates cats, idx and jsarray. 
                   13561: 
                   13562: =cut
                   13563: 
                   13564: sub gather_categories {
                   13565:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13566:     my %counters;
                   13567:     my $num = 0;
                   13568:     foreach my $item (keys(%{$categories})) {
                   13569:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13570:         if ($container eq '' && $depth == 0) {
                   13571:             $cats->[$depth][$categories->{$item}] = $cat;
                   13572:         } else {
                   13573:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13574:         }
                   13575:         my ($escitem,$tail) = split(/:/,$item,2);
                   13576:         if ($counters{$tail} eq '') {
                   13577:             $counters{$tail} = $num;
                   13578:             $num ++;
                   13579:         }
                   13580:         if (ref($idx) eq 'HASH') {
                   13581:             $idx->{$item} = $counters{$tail};
                   13582:         }
                   13583:         if (ref($jsarray) eq 'ARRAY') {
                   13584:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13585:         }
                   13586:     }
                   13587:     return;
                   13588: }
                   13589: 
                   13590: =pod
                   13591: 
                   13592: =item * &extract_categories()
                   13593: 
                   13594: Used to generate breadcrumb trails for course categories.
                   13595: 
                   13596: Inputs:
1.663     raeburn  13597: 
1.655     raeburn  13598: categories (reference to hash of category definitions).
1.663     raeburn  13599: 
1.655     raeburn  13600: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13601:       categories and subcategories).
1.663     raeburn  13602: 
1.655     raeburn  13603: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13604: 
1.655     raeburn  13605: allitems (reference to hash - key is category key 
                   13606:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13607: 
1.655     raeburn  13608: idx (reference to hash of counters used in Domain Coordinator interface for
                   13609:       editing Course Categories).
1.663     raeburn  13610: 
1.655     raeburn  13611: jsarray (reference to array of categories used to create Javascript arrays for
                   13612:          Domain Coordinator interface for editing Course Categories).
                   13613: 
1.665     raeburn  13614: subcats (reference to hash of arrays containing all subcategories within each 
                   13615:          category, -recursive)
                   13616: 
1.655     raeburn  13617: Returns: nothing
                   13618: 
                   13619: Side effects: populates trails and allitems hash references.
                   13620: 
                   13621: =cut
                   13622: 
                   13623: sub extract_categories {
1.665     raeburn  13624:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13625:     if (ref($categories) eq 'HASH') {
                   13626:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13627:         if (ref($cats->[0]) eq 'ARRAY') {
                   13628:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13629:                 my $name = $cats->[0][$i];
                   13630:                 my $item = &escape($name).'::0';
                   13631:                 my $trailstr;
                   13632:                 if ($name eq 'instcode') {
                   13633:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13634:                 } elsif ($name eq 'communities') {
                   13635:                     $trailstr = &mt('Communities');
1.655     raeburn  13636:                 } else {
                   13637:                     $trailstr = $name;
                   13638:                 }
                   13639:                 if ($allitems->{$item} eq '') {
                   13640:                     push(@{$trails},$trailstr);
                   13641:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13642:                 }
                   13643:                 my @parents = ($name);
                   13644:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13645:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13646:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13647:                         if (ref($subcats) eq 'HASH') {
                   13648:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13649:                         }
                   13650:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13651:                     }
                   13652:                 } else {
                   13653:                     if (ref($subcats) eq 'HASH') {
                   13654:                         $subcats->{$item} = [];
1.655     raeburn  13655:                     }
                   13656:                 }
                   13657:             }
                   13658:         }
                   13659:     }
                   13660:     return;
                   13661: }
                   13662: 
                   13663: =pod
                   13664: 
1.1075.2.56  raeburn  13665: =item * &recurse_categories()
1.655     raeburn  13666: 
                   13667: Recursively used to generate breadcrumb trails for course categories.
                   13668: 
                   13669: Inputs:
1.663     raeburn  13670: 
1.655     raeburn  13671: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13672:       categories and subcategories).
1.663     raeburn  13673: 
1.655     raeburn  13674: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13675: 
                   13676: category (current course category, for which breadcrumb trail is being generated).
                   13677: 
                   13678: trails (reference to array of breadcrumb trails for each category).
                   13679: 
1.655     raeburn  13680: allitems (reference to hash - key is category key
                   13681:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13682: 
1.655     raeburn  13683: parents (array containing containers directories for current category, 
                   13684:          back to top level). 
                   13685: 
                   13686: Returns: nothing
                   13687: 
                   13688: Side effects: populates trails and allitems hash references
                   13689: 
                   13690: =cut
                   13691: 
                   13692: sub recurse_categories {
1.665     raeburn  13693:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13694:     my $shallower = $depth - 1;
                   13695:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13696:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13697:             my $name = $cats->[$depth]{$category}[$k];
                   13698:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13699:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13700:             if ($allitems->{$item} eq '') {
                   13701:                 push(@{$trails},$trailstr);
                   13702:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13703:             }
                   13704:             my $deeper = $depth+1;
                   13705:             push(@{$parents},$category);
1.665     raeburn  13706:             if (ref($subcats) eq 'HASH') {
                   13707:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13708:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13709:                     my $higher;
                   13710:                     if ($j > 0) {
                   13711:                         $higher = &escape($parents->[$j]).':'.
                   13712:                                   &escape($parents->[$j-1]).':'.$j;
                   13713:                     } else {
                   13714:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13715:                     }
                   13716:                     push(@{$subcats->{$higher}},$subcat);
                   13717:                 }
                   13718:             }
                   13719:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13720:                                 $subcats);
1.655     raeburn  13721:             pop(@{$parents});
                   13722:         }
                   13723:     } else {
                   13724:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13725:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13726:         if ($allitems->{$item} eq '') {
                   13727:             push(@{$trails},$trailstr);
                   13728:             $allitems->{$item} = scalar(@{$trails})-1;
                   13729:         }
                   13730:     }
                   13731:     return;
                   13732: }
                   13733: 
1.663     raeburn  13734: =pod
                   13735: 
1.1075.2.56  raeburn  13736: =item * &assign_categories_table()
1.663     raeburn  13737: 
                   13738: Create a datatable for display of hierarchical categories in a domain,
                   13739: with checkboxes to allow a course to be categorized. 
                   13740: 
                   13741: Inputs:
                   13742: 
                   13743: cathash - reference to hash of categories defined for the domain (from
                   13744:           configuration.db)
                   13745: 
                   13746: currcat - scalar with an & separated list of categories assigned to a course. 
                   13747: 
1.919     raeburn  13748: type    - scalar contains course type (Course or Community).
                   13749: 
1.663     raeburn  13750: Returns: $output (markup to be displayed) 
                   13751: 
                   13752: =cut
                   13753: 
                   13754: sub assign_categories_table {
1.919     raeburn  13755:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13756:     my $output;
                   13757:     if (ref($cathash) eq 'HASH') {
                   13758:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13759:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13760:         $maxdepth = scalar(@cats);
                   13761:         if (@cats > 0) {
                   13762:             my $itemcount = 0;
                   13763:             if (ref($cats[0]) eq 'ARRAY') {
                   13764:                 my @currcategories;
                   13765:                 if ($currcat ne '') {
                   13766:                     @currcategories = split('&',$currcat);
                   13767:                 }
1.919     raeburn  13768:                 my $table;
1.663     raeburn  13769:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13770:                     my $parent = $cats[0][$i];
1.919     raeburn  13771:                     next if ($parent eq 'instcode');
                   13772:                     if ($type eq 'Community') {
                   13773:                         next unless ($parent eq 'communities');
                   13774:                     } else {
                   13775:                         next if ($parent eq 'communities');
                   13776:                     }
1.663     raeburn  13777:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13778:                     my $item = &escape($parent).'::0';
                   13779:                     my $checked = '';
                   13780:                     if (@currcategories > 0) {
                   13781:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13782:                             $checked = ' checked="checked"';
1.663     raeburn  13783:                         }
                   13784:                     }
1.919     raeburn  13785:                     my $parent_title = $parent;
                   13786:                     if ($parent eq 'communities') {
                   13787:                         $parent_title = &mt('Communities');
                   13788:                     }
                   13789:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13790:                               '<input type="checkbox" name="usecategory" value="'.
                   13791:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13792:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13793:                     my $depth = 1;
                   13794:                     push(@path,$parent);
1.919     raeburn  13795:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13796:                     pop(@path);
1.919     raeburn  13797:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13798:                     $itemcount ++;
                   13799:                 }
1.919     raeburn  13800:                 if ($itemcount) {
                   13801:                     $output = &Apache::loncommon::start_data_table().
                   13802:                               $table.
                   13803:                               &Apache::loncommon::end_data_table();
                   13804:                 }
1.663     raeburn  13805:             }
                   13806:         }
                   13807:     }
                   13808:     return $output;
                   13809: }
                   13810: 
                   13811: =pod
                   13812: 
1.1075.2.56  raeburn  13813: =item * &assign_category_rows()
1.663     raeburn  13814: 
                   13815: Create a datatable row for display of nested categories in a domain,
                   13816: with checkboxes to allow a course to be categorized,called recursively.
                   13817: 
                   13818: Inputs:
                   13819: 
                   13820: itemcount - track row number for alternating colors
                   13821: 
                   13822: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13823:       categories and subcategories.
                   13824: 
                   13825: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13826: 
                   13827: parent - parent of current category item
                   13828: 
                   13829: path - Array containing all categories back up through the hierarchy from the
                   13830:        current category to the top level.
                   13831: 
                   13832: currcategories - reference to array of current categories assigned to the course
                   13833: 
                   13834: Returns: $output (markup to be displayed).
                   13835: 
                   13836: =cut
                   13837: 
                   13838: sub assign_category_rows {
                   13839:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13840:     my ($text,$name,$item,$chgstr);
                   13841:     if (ref($cats) eq 'ARRAY') {
                   13842:         my $maxdepth = scalar(@{$cats});
                   13843:         if (ref($cats->[$depth]) eq 'HASH') {
                   13844:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13845:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13846:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  13847:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  13848:                 for (my $j=0; $j<$numchildren; $j++) {
                   13849:                     $name = $cats->[$depth]{$parent}[$j];
                   13850:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13851:                     my $deeper = $depth+1;
                   13852:                     my $checked = '';
                   13853:                     if (ref($currcategories) eq 'ARRAY') {
                   13854:                         if (@{$currcategories} > 0) {
                   13855:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13856:                                 $checked = ' checked="checked"';
1.663     raeburn  13857:                             }
                   13858:                         }
                   13859:                     }
1.664     raeburn  13860:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13861:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13862:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13863:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13864:                              '</td><td>';
1.663     raeburn  13865:                     if (ref($path) eq 'ARRAY') {
                   13866:                         push(@{$path},$name);
                   13867:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13868:                         pop(@{$path});
                   13869:                     }
                   13870:                     $text .= '</td></tr>';
                   13871:                 }
                   13872:                 $text .= '</table></td>';
                   13873:             }
                   13874:         }
                   13875:     }
                   13876:     return $text;
                   13877: }
                   13878: 
1.1075.2.69  raeburn  13879: =pod
                   13880: 
                   13881: =back
                   13882: 
                   13883: =cut
                   13884: 
1.655     raeburn  13885: ############################################################
                   13886: ############################################################
                   13887: 
                   13888: 
1.443     albertel 13889: sub commit_customrole {
1.664     raeburn  13890:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13891:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13892:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13893:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13894:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13895:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13896:                  '</b><br />';
                   13897:     return $output;
                   13898: }
                   13899: 
                   13900: sub commit_standardrole {
1.1075.2.31  raeburn  13901:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13902:     my ($output,$logmsg,$linefeed);
                   13903:     if ($context eq 'auto') {
                   13904:         $linefeed = "\n";
                   13905:     } else {
                   13906:         $linefeed = "<br />\n";
                   13907:     }  
1.443     albertel 13908:     if ($three eq 'st') {
1.541     raeburn  13909:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  13910:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13911:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13912:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13913:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13914:         } else {
1.541     raeburn  13915:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13916:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13917:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13918:             if ($context eq 'auto') {
                   13919:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13920:             } else {
                   13921:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13922:                &mt('Add to classlist').': <b>ok</b>';
                   13923:             }
                   13924:             $output .= $linefeed;
1.443     albertel 13925:         }
                   13926:     } else {
                   13927:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13928:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13929:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13930:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13931:         if ($context eq 'auto') {
                   13932:             $output .= $result.$linefeed;
                   13933:         } else {
                   13934:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13935:         }
1.443     albertel 13936:     }
                   13937:     return $output;
                   13938: }
                   13939: 
                   13940: sub commit_studentrole {
1.1075.2.31  raeburn  13941:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13942:         $credits) = @_;
1.626     raeburn  13943:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13944:     if ($context eq 'auto') {
                   13945:         $linefeed = "\n";
                   13946:     } else {
                   13947:         $linefeed = '<br />'."\n";
                   13948:     }
1.443     albertel 13949:     if (defined($one) && defined($two)) {
                   13950:         my $cid=$one.'_'.$two;
                   13951:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13952:         my $secchange = 0;
                   13953:         my $expire_role_result;
                   13954:         my $modify_section_result;
1.628     raeburn  13955:         if ($oldsec ne '-1') { 
                   13956:             if ($oldsec ne $sec) {
1.443     albertel 13957:                 $secchange = 1;
1.628     raeburn  13958:                 my $now = time;
1.443     albertel 13959:                 my $uurl='/'.$cid;
                   13960:                 $uurl=~s/\_/\//g;
                   13961:                 if ($oldsec) {
                   13962:                     $uurl.='/'.$oldsec;
                   13963:                 }
1.626     raeburn  13964:                 $oldsecurl = $uurl;
1.628     raeburn  13965:                 $expire_role_result = 
1.652     raeburn  13966:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13967:                 if ($env{'request.course.sec'} ne '') { 
                   13968:                     if ($expire_role_result eq 'refused') {
                   13969:                         my @roles = ('st');
                   13970:                         my @statuses = ('previous');
                   13971:                         my @roledoms = ($one);
                   13972:                         my $withsec = 1;
                   13973:                         my %roleshash = 
                   13974:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13975:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13976:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13977:                             my ($oldstart,$oldend) = 
                   13978:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13979:                             if ($oldend > 0 && $oldend <= $now) {
                   13980:                                 $expire_role_result = 'ok';
                   13981:                             }
                   13982:                         }
                   13983:                     }
                   13984:                 }
1.443     albertel 13985:                 $result = $expire_role_result;
                   13986:             }
                   13987:         }
                   13988:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  13989:             $modify_section_result = 
                   13990:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13991:                                                            undef,undef,undef,$sec,
                   13992:                                                            $end,$start,'','',$cid,
                   13993:                                                            '',$context,$credits);
1.443     albertel 13994:             if ($modify_section_result =~ /^ok/) {
                   13995:                 if ($secchange == 1) {
1.628     raeburn  13996:                     if ($sec eq '') {
                   13997:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13998:                     } else {
                   13999:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14000:                     }
1.443     albertel 14001:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14002:                     if ($sec eq '') {
                   14003:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14004:                     } else {
                   14005:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14006:                     }
1.443     albertel 14007:                 } else {
1.628     raeburn  14008:                     if ($sec eq '') {
                   14009:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14010:                     } else {
                   14011:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14012:                     }
1.443     albertel 14013:                 }
                   14014:             } else {
1.628     raeburn  14015:                 if ($secchange) {       
                   14016:                     $$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;
                   14017:                 } else {
                   14018:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14019:                 }
1.443     albertel 14020:             }
                   14021:             $result = $modify_section_result;
                   14022:         } elsif ($secchange == 1) {
1.628     raeburn  14023:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14024:                 $$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  14025:             } else {
                   14026:                 $$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;
                   14027:             }
1.626     raeburn  14028:             if ($expire_role_result eq 'refused') {
                   14029:                 my $newsecurl = '/'.$cid;
                   14030:                 $newsecurl =~ s/\_/\//g;
                   14031:                 if ($sec ne '') {
                   14032:                     $newsecurl.='/'.$sec;
                   14033:                 }
                   14034:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14035:                     if ($sec eq '') {
                   14036:                         $$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;
                   14037:                     } else {
                   14038:                         $$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;
                   14039:                     }
                   14040:                 }
                   14041:             }
1.443     albertel 14042:         }
                   14043:     } else {
1.626     raeburn  14044:         $$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 14045:         $result = "error: incomplete course id\n";
                   14046:     }
                   14047:     return $result;
                   14048: }
                   14049: 
1.1075.2.25  raeburn  14050: sub show_role_extent {
                   14051:     my ($scope,$context,$role) = @_;
                   14052:     $scope =~ s{^/}{};
                   14053:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14054:     push(@courseroles,'co');
                   14055:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14056:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14057:         $scope =~ s{/}{_};
                   14058:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14059:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14060:         my ($audom,$auname) = split(/\//,$scope);
                   14061:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14062:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14063:     } else {
                   14064:         $scope =~ s{/$}{};
                   14065:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14066:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14067:     }
                   14068: }
                   14069: 
1.443     albertel 14070: ############################################################
                   14071: ############################################################
                   14072: 
1.566     albertel 14073: sub check_clone {
1.578     raeburn  14074:     my ($args,$linefeed) = @_;
1.566     albertel 14075:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14076:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14077:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14078:     my $clonemsg;
                   14079:     my $can_clone = 0;
1.944     raeburn  14080:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14081:     if ($lctype ne 'community') {
                   14082:         $lctype = 'course';
                   14083:     }
1.566     albertel 14084:     if ($clonehome eq 'no_host') {
1.944     raeburn  14085:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14086:             $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'});
                   14087:         } else {
                   14088:             $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'});
                   14089:         }     
1.566     albertel 14090:     } else {
                   14091: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14092:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14093:             if ($clonedesc{'type'} ne 'Community') {
                   14094:                  $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'});
                   14095:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14096:             }
                   14097:         }
1.882     raeburn  14098: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14099:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14100: 	    $can_clone = 1;
                   14101: 	} else {
                   14102: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   14103: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   14104: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  14105:             if (grep(/^\*$/,@cloners)) {
                   14106:                 $can_clone = 1;
                   14107:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14108:                 $can_clone = 1;
                   14109:             } else {
1.908     raeburn  14110:                 my $ccrole = 'cc';
1.944     raeburn  14111:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14112:                     $ccrole = 'co';
                   14113:                 }
1.578     raeburn  14114: 	        my %roleshash =
                   14115: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14116: 					 $args->{'ccdomain'},
1.908     raeburn  14117:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  14118: 					 [$args->{'clonedomain'}]);
1.908     raeburn  14119: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  14120:                     $can_clone = 1;
                   14121:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   14122:                     $can_clone = 1;
                   14123:                 } else {
1.944     raeburn  14124:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14125:                         $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'});
                   14126:                     } else {
                   14127:                         $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'});
                   14128:                     }
1.578     raeburn  14129: 	        }
1.566     albertel 14130: 	    }
1.578     raeburn  14131:         }
1.566     albertel 14132:     }
                   14133:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14134: }
                   14135: 
1.444     albertel 14136: sub construct_course {
1.1075.2.59  raeburn  14137:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14138:     my $outcome;
1.541     raeburn  14139:     my $linefeed =  '<br />'."\n";
                   14140:     if ($context eq 'auto') {
                   14141:         $linefeed = "\n";
                   14142:     }
1.566     albertel 14143: 
                   14144: #
                   14145: # Are we cloning?
                   14146: #
                   14147:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14148:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14149: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14150: 	if ($context ne 'auto') {
1.578     raeburn  14151:             if ($clonemsg ne '') {
                   14152: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14153:             }
1.566     albertel 14154: 	}
                   14155: 	$outcome .= $clonemsg.$linefeed;
                   14156: 
                   14157:         if (!$can_clone) {
                   14158: 	    return (0,$outcome);
                   14159: 	}
                   14160:     }
                   14161: 
1.444     albertel 14162: #
                   14163: # Open course
                   14164: #
                   14165:     my $crstype = lc($args->{'crstype'});
                   14166:     my %cenv=();
                   14167:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14168:                                              $args->{'cdescr'},
                   14169:                                              $args->{'curl'},
                   14170:                                              $args->{'course_home'},
                   14171:                                              $args->{'nonstandard'},
                   14172:                                              $args->{'crscode'},
                   14173:                                              $args->{'ccuname'}.':'.
                   14174:                                              $args->{'ccdomain'},
1.882     raeburn  14175:                                              $args->{'crstype'},
1.885     raeburn  14176:                                              $cnum,$context,$category);
1.444     albertel 14177: 
                   14178:     # Note: The testing routines depend on this being output; see 
                   14179:     # Utils::Course. This needs to at least be output as a comment
                   14180:     # if anyone ever decides to not show this, and Utils::Course::new
                   14181:     # will need to be suitably modified.
1.541     raeburn  14182:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14183:     if ($$courseid =~ /^error:/) {
                   14184:         return (0,$outcome);
                   14185:     }
                   14186: 
1.444     albertel 14187: #
                   14188: # Check if created correctly
                   14189: #
1.479     albertel 14190:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14191:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14192:     if ($crsuhome eq 'no_host') {
                   14193:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14194:         return (0,$outcome);
                   14195:     }
1.541     raeburn  14196:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14197: 
1.444     albertel 14198: #
1.566     albertel 14199: # Do the cloning
                   14200: #   
                   14201:     if ($can_clone && $cloneid) {
                   14202: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14203: 	if ($context ne 'auto') {
                   14204: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14205: 	}
                   14206: 	$outcome .= $clonemsg.$linefeed;
                   14207: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14208: # Copy all files
1.637     www      14209: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14210: # Restore URL
1.566     albertel 14211: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14212: # Restore title
1.566     albertel 14213: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14214: # Restore creation date, creator and creation context.
                   14215:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14216:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14217:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14218: # Mark as cloned
1.566     albertel 14219: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14220: # Need to clone grading mode
                   14221:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14222:         $cenv{'grading'}=$newenv{'grading'};
                   14223: # Do not clone these environment entries
                   14224:         &Apache::lonnet::del('environment',
                   14225:                   ['default_enrollment_start_date',
                   14226:                    'default_enrollment_end_date',
                   14227:                    'question.email',
                   14228:                    'policy.email',
                   14229:                    'comment.email',
                   14230:                    'pch.users.denied',
1.725     raeburn  14231:                    'plc.users.denied',
                   14232:                    'hidefromcat',
1.1075.2.36  raeburn  14233:                    'checkforpriv',
1.1075.2.59  raeburn  14234:                    'categories',
                   14235:                    'internal.uniquecode'],
1.638     www      14236:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14237:         if ($args->{'textbook'}) {
                   14238:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14239:         }
1.444     albertel 14240:     }
1.566     albertel 14241: 
1.444     albertel 14242: #
                   14243: # Set environment (will override cloned, if existing)
                   14244: #
                   14245:     my @sections = ();
                   14246:     my @xlists = ();
                   14247:     if ($args->{'crstype'}) {
                   14248:         $cenv{'type'}=$args->{'crstype'};
                   14249:     }
                   14250:     if ($args->{'crsid'}) {
                   14251:         $cenv{'courseid'}=$args->{'crsid'};
                   14252:     }
                   14253:     if ($args->{'crscode'}) {
                   14254:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14255:     }
                   14256:     if ($args->{'crsquota'} ne '') {
                   14257:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14258:     } else {
                   14259:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14260:     }
                   14261:     if ($args->{'ccuname'}) {
                   14262:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14263:                                         ':'.$args->{'ccdomain'};
                   14264:     } else {
                   14265:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14266:     }
1.1075.2.31  raeburn  14267:     if ($args->{'defaultcredits'}) {
                   14268:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14269:     }
1.444     albertel 14270:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14271:     if ($args->{'crssections'}) {
                   14272:         $cenv{'internal.sectionnums'} = '';
                   14273:         if ($args->{'crssections'} =~ m/,/) {
                   14274:             @sections = split/,/,$args->{'crssections'};
                   14275:         } else {
                   14276:             $sections[0] = $args->{'crssections'};
                   14277:         }
                   14278:         if (@sections > 0) {
                   14279:             foreach my $item (@sections) {
                   14280:                 my ($sec,$gp) = split/:/,$item;
                   14281:                 my $class = $args->{'crscode'}.$sec;
                   14282:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14283:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14284:                 unless ($addcheck eq 'ok') {
                   14285:                     push @badclasses, $class;
                   14286:                 }
                   14287:             }
                   14288:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14289:         }
                   14290:     }
                   14291: # do not hide course coordinator from staff listing, 
                   14292: # even if privileged
                   14293:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14294: # add course coordinator's domain to domains to check for privileged users
                   14295: # if different to course domain
                   14296:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14297:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14298:     }
1.444     albertel 14299: # add crosslistings
                   14300:     if ($args->{'crsxlist'}) {
                   14301:         $cenv{'internal.crosslistings'}='';
                   14302:         if ($args->{'crsxlist'} =~ m/,/) {
                   14303:             @xlists = split/,/,$args->{'crsxlist'};
                   14304:         } else {
                   14305:             $xlists[0] = $args->{'crsxlist'};
                   14306:         }
                   14307:         if (@xlists > 0) {
                   14308:             foreach my $item (@xlists) {
                   14309:                 my ($xl,$gp) = split/:/,$item;
                   14310:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14311:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14312:                 unless ($addcheck eq 'ok') {
                   14313:                     push @badclasses, $xl;
                   14314:                 }
                   14315:             }
                   14316:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14317:         }
                   14318:     }
                   14319:     if ($args->{'autoadds'}) {
                   14320:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14321:     }
                   14322:     if ($args->{'autodrops'}) {
                   14323:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14324:     }
                   14325: # check for notification of enrollment changes
                   14326:     my @notified = ();
                   14327:     if ($args->{'notify_owner'}) {
                   14328:         if ($args->{'ccuname'} ne '') {
                   14329:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14330:         }
                   14331:     }
                   14332:     if ($args->{'notify_dc'}) {
                   14333:         if ($uname ne '') { 
1.630     raeburn  14334:             push(@notified,$uname.':'.$udom);
1.444     albertel 14335:         }
                   14336:     }
                   14337:     if (@notified > 0) {
                   14338:         my $notifylist;
                   14339:         if (@notified > 1) {
                   14340:             $notifylist = join(',',@notified);
                   14341:         } else {
                   14342:             $notifylist = $notified[0];
                   14343:         }
                   14344:         $cenv{'internal.notifylist'} = $notifylist;
                   14345:     }
                   14346:     if (@badclasses > 0) {
                   14347:         my %lt=&Apache::lonlocal::texthash(
                   14348:                 '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',
                   14349:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14350:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14351:         );
1.541     raeburn  14352:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14353:                            ' ('.$lt{'adby'}.')';
                   14354:         if ($context eq 'auto') {
                   14355:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14356:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14357:             foreach my $item (@badclasses) {
                   14358:                 if ($context eq 'auto') {
                   14359:                     $outcome .= " - $item\n";
                   14360:                 } else {
                   14361:                     $outcome .= "<li>$item</li>\n";
                   14362:                 }
                   14363:             }
                   14364:             if ($context eq 'auto') {
                   14365:                 $outcome .= $linefeed;
                   14366:             } else {
1.566     albertel 14367:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14368:             }
                   14369:         } 
1.444     albertel 14370:     }
                   14371:     if ($args->{'no_end_date'}) {
                   14372:         $args->{'endaccess'} = 0;
                   14373:     }
                   14374:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14375:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14376:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14377:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14378:     if ($args->{'showphotos'}) {
                   14379:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14380:     }
                   14381:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14382:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14383:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14384:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14385:             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'); 
                   14386:             if ($context eq 'auto') {
                   14387:                 $outcome .= $krb_msg;
                   14388:             } else {
1.566     albertel 14389:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14390:             }
                   14391:             $outcome .= $linefeed;
1.444     albertel 14392:         }
                   14393:     }
                   14394:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14395:        if ($args->{'setpolicy'}) {
                   14396:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14397:        }
                   14398:        if ($args->{'setcontent'}) {
                   14399:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14400:        }
                   14401:     }
                   14402:     if ($args->{'reshome'}) {
                   14403: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14404: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14405:     }
                   14406: #
                   14407: # course has keyed access
                   14408: #
                   14409:     if ($args->{'setkeys'}) {
                   14410:        $cenv{'keyaccess'}='yes';
                   14411:     }
                   14412: # if specified, key authority is not course, but user
                   14413: # only active if keyaccess is yes
                   14414:     if ($args->{'keyauth'}) {
1.487     albertel 14415: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14416: 	$user = &LONCAPA::clean_username($user);
                   14417: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14418: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14419: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14420: 	}
                   14421:     }
                   14422: 
1.1075.2.59  raeburn  14423: #
                   14424: #  generate and store uniquecode (available to course requester), if course should have one.
                   14425: #
                   14426:     if ($args->{'uniquecode'}) {
                   14427:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14428:         if ($code) {
                   14429:             $cenv{'internal.uniquecode'} = $code;
                   14430:             my %crsinfo =
                   14431:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14432:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14433:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14434:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14435:             }
                   14436:             if (ref($coderef)) {
                   14437:                 $$coderef = $code;
                   14438:             }
                   14439:         }
                   14440:     }
                   14441: 
1.444     albertel 14442:     if ($args->{'disresdis'}) {
                   14443:         $cenv{'pch.roles.denied'}='st';
                   14444:     }
                   14445:     if ($args->{'disablechat'}) {
                   14446:         $cenv{'plc.roles.denied'}='st';
                   14447:     }
                   14448: 
                   14449:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14450:     # course
                   14451:     $cenv{'course.helper.not.run'} = 1;
                   14452:     #
                   14453:     # Use new Randomseed
                   14454:     #
                   14455:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14456:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14457:     #
                   14458:     # The encryption code and receipt prefix for this course
                   14459:     #
                   14460:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14461:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14462:     #
                   14463:     # By default, use standard grading
                   14464:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14465: 
1.541     raeburn  14466:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14467:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14468: #
                   14469: # Open all assignments
                   14470: #
                   14471:     if ($args->{'openall'}) {
                   14472:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14473:        my %storecontent = ($storeunder         => time,
                   14474:                            $storeunder.'.type' => 'date_start');
                   14475:        
                   14476:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14477:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14478:    }
                   14479: #
                   14480: # Set first page
                   14481: #
                   14482:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14483: 	    || ($cloneid)) {
1.445     albertel 14484: 	use LONCAPA::map;
1.444     albertel 14485: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14486: 
                   14487: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14488:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14489: 
1.444     albertel 14490:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14491:         my $title; my $url;
                   14492:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14493: 	    $title=&mt('Syllabus');
1.444     albertel 14494:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14495:         } else {
1.963     raeburn  14496:             $title=&mt('Table of Contents');
1.444     albertel 14497:             $url='/adm/navmaps';
                   14498:         }
1.445     albertel 14499: 
                   14500:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14501: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14502: 
                   14503: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14504:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14505:     }
1.566     albertel 14506: 
                   14507:     return (1,$outcome);
1.444     albertel 14508: }
                   14509: 
1.1075.2.59  raeburn  14510: sub make_unique_code {
                   14511:     my ($cdom,$cnum) = @_;
                   14512:     # get lock on uniquecodes db
                   14513:     my $lockhash = {
                   14514:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14515:                                                   ':'.$env{'user.domain'},
                   14516:                    };
                   14517:     my $tries = 0;
                   14518:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14519:     my ($code,$error);
                   14520: 
                   14521:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14522:         $tries ++;
                   14523:         sleep 1;
                   14524:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14525:     }
                   14526:     if ($gotlock eq 'ok') {
                   14527:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14528:         my $gotcode;
                   14529:         my $attempts = 0;
                   14530:         while ((!$gotcode) && ($attempts < 100)) {
                   14531:             $code = &generate_code();
                   14532:             if (!exists($currcodes{$code})) {
                   14533:                 $gotcode = 1;
                   14534:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14535:                     $error = 'nostore';
                   14536:                 }
                   14537:             }
                   14538:             $attempts ++;
                   14539:         }
                   14540:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14541:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14542:     } else {
                   14543:         $error = 'nolock';
                   14544:     }
                   14545:     return ($code,$error);
                   14546: }
                   14547: 
                   14548: sub generate_code {
                   14549:     my $code;
                   14550:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14551:     for (my $i=0; $i<6; $i++) {
                   14552:         my $lettnum = int (rand 2);
                   14553:         my $item = '';
                   14554:         if ($lettnum) {
                   14555:             $item = $letts[int( rand(18) )];
                   14556:         } else {
                   14557:             $item = 1+int( rand(8) );
                   14558:         }
                   14559:         $code .= $item;
                   14560:     }
                   14561:     return $code;
                   14562: }
                   14563: 
1.444     albertel 14564: ############################################################
                   14565: ############################################################
                   14566: 
1.953     droeschl 14567: #SD
                   14568: # only Community and Course, or anything else?
1.378     raeburn  14569: sub course_type {
                   14570:     my ($cid) = @_;
                   14571:     if (!defined($cid)) {
                   14572:         $cid = $env{'request.course.id'};
                   14573:     }
1.404     albertel 14574:     if (defined($env{'course.'.$cid.'.type'})) {
                   14575:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14576:     } else {
                   14577:         return 'Course';
1.377     raeburn  14578:     }
                   14579: }
1.156     albertel 14580: 
1.406     raeburn  14581: sub group_term {
                   14582:     my $crstype = &course_type();
                   14583:     my %names = (
                   14584:                   'Course' => 'group',
1.865     raeburn  14585:                   'Community' => 'group',
1.406     raeburn  14586:                 );
                   14587:     return $names{$crstype};
                   14588: }
                   14589: 
1.902     raeburn  14590: sub course_types {
1.1075.2.59  raeburn  14591:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14592:     my %typename = (
                   14593:                          official   => 'Official course',
                   14594:                          unofficial => 'Unofficial course',
                   14595:                          community  => 'Community',
1.1075.2.59  raeburn  14596:                          textbook   => 'Textbook course',
1.902     raeburn  14597:                    );
                   14598:     return (\@types,\%typename);
                   14599: }
                   14600: 
1.156     albertel 14601: sub icon {
                   14602:     my ($file)=@_;
1.505     albertel 14603:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14604:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14605:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14606:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14607: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14608: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14609: 	            $curfext.".gif") {
                   14610: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14611: 		$curfext.".gif";
                   14612: 	}
                   14613:     }
1.249     albertel 14614:     return &lonhttpdurl($iconname);
1.154     albertel 14615: } 
1.84      albertel 14616: 
1.575     albertel 14617: sub lonhttpdurl {
1.692     www      14618: #
                   14619: # Had been used for "small fry" static images on separate port 8080.
                   14620: # Modify here if lightweight http functionality desired again.
                   14621: # Currently eliminated due to increasing firewall issues.
                   14622: #
1.575     albertel 14623:     my ($url)=@_;
1.692     www      14624:     return $url;
1.215     albertel 14625: }
                   14626: 
1.213     albertel 14627: sub connection_aborted {
                   14628:     my ($r)=@_;
                   14629:     $r->print(" ");$r->rflush();
                   14630:     my $c = $r->connection;
                   14631:     return $c->aborted();
                   14632: }
                   14633: 
1.221     foxr     14634: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14635: #    strings as 'strings'.
                   14636: sub escape_single {
1.221     foxr     14637:     my ($input) = @_;
1.223     albertel 14638:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14639:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14640:     return $input;
                   14641: }
1.223     albertel 14642: 
1.222     foxr     14643: #  Same as escape_single, but escape's "'s  This 
                   14644: #  can be used for  "strings"
                   14645: sub escape_double {
                   14646:     my ($input) = @_;
                   14647:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14648:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14649:     return $input;
                   14650: }
1.223     albertel 14651:  
1.222     foxr     14652: #   Escapes the last element of a full URL.
                   14653: sub escape_url {
                   14654:     my ($url)   = @_;
1.238     raeburn  14655:     my @urlslices = split(/\//, $url,-1);
1.369     www      14656:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  14657:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14658: }
1.462     albertel 14659: 
1.820     raeburn  14660: sub compare_arrays {
                   14661:     my ($arrayref1,$arrayref2) = @_;
                   14662:     my (@difference,%count);
                   14663:     @difference = ();
                   14664:     %count = ();
                   14665:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14666:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14667:         foreach my $element (keys(%count)) {
                   14668:             if ($count{$element} == 1) {
                   14669:                 push(@difference,$element);
                   14670:             }
                   14671:         }
                   14672:     }
                   14673:     return @difference;
                   14674: }
                   14675: 
1.817     bisitz   14676: # -------------------------------------------------------- Initialize user login
1.462     albertel 14677: sub init_user_environment {
1.463     albertel 14678:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14679:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14680: 
                   14681:     my $public=($username eq 'public' && $domain eq 'public');
                   14682: 
                   14683: # See if old ID present, if so, remove
                   14684: 
1.1062    raeburn  14685:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14686:     my $now=time;
                   14687: 
                   14688:     if ($public) {
                   14689: 	my $max_public=100;
                   14690: 	my $oldest;
                   14691: 	my $oldest_time=0;
                   14692: 	for(my $next=1;$next<=$max_public;$next++) {
                   14693: 	    if (-e $lonids."/publicuser_$next.id") {
                   14694: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14695: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14696: 		    $oldest_time=$mtime;
                   14697: 		    $oldest=$next;
                   14698: 		}
                   14699: 	    } else {
                   14700: 		$cookie="publicuser_$next";
                   14701: 		last;
                   14702: 	    }
                   14703: 	}
                   14704: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14705:     } else {
1.463     albertel 14706: 	# if this isn't a robot, kill any existing non-robot sessions
                   14707: 	if (!$args->{'robot'}) {
                   14708: 	    opendir(DIR,$lonids);
                   14709: 	    while ($filename=readdir(DIR)) {
                   14710: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14711: 		    unlink($lonids.'/'.$filename);
                   14712: 		}
1.462     albertel 14713: 	    }
1.463     albertel 14714: 	    closedir(DIR);
1.1075.2.84  raeburn  14715: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   14716:             my $namespace = 'nohist_courseeditor';
                   14717:             my $lockingkey = 'paste'."\0".'locked_num';
                   14718:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   14719:                                                 $domain,$username);
                   14720:             if (exists($lockhash{$lockingkey})) {
                   14721:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   14722:                 unless ($delresult eq 'ok') {
                   14723:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   14724:                 }
                   14725:             }
1.462     albertel 14726: 	}
                   14727: # Give them a new cookie
1.463     albertel 14728: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14729: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14730: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14731:     
                   14732: # Initialize roles
                   14733: 
1.1062    raeburn  14734: 	($userroles,$firstaccenv,$timerintenv) = 
                   14735:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14736:     }
                   14737: # ------------------------------------ Check browser type and MathML capability
                   14738: 
1.1075.2.77  raeburn  14739:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   14740:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 14741: 
                   14742: # ------------------------------------------------------------- Get environment
                   14743: 
                   14744:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14745:     my ($tmp) = keys(%userenv);
                   14746:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14747:     } else {
                   14748: 	undef(%userenv);
                   14749:     }
                   14750:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14751: 	$form->{'interface'}=$userenv{'interface'};
                   14752:     }
                   14753:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14754: 
                   14755: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14756:     foreach my $option ('interface','localpath','localres') {
                   14757:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14758:     }
                   14759: # --------------------------------------------------------- Write first profile
                   14760: 
                   14761:     {
                   14762: 	my %initial_env = 
                   14763: 	    ("user.name"          => $username,
                   14764: 	     "user.domain"        => $domain,
                   14765: 	     "user.home"          => $authhost,
                   14766: 	     "browser.type"       => $clientbrowser,
                   14767: 	     "browser.version"    => $clientversion,
                   14768: 	     "browser.mathml"     => $clientmathml,
                   14769: 	     "browser.unicode"    => $clientunicode,
                   14770: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  14771:              "browser.mobile"     => $clientmobile,
                   14772:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  14773:              "browser.osversion"  => $clientosversion,
1.462     albertel 14774: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14775: 	     "request.course.fn"  => '',
                   14776: 	     "request.course.uri" => '',
                   14777: 	     "request.course.sec" => '',
                   14778: 	     "request.role"       => 'cm',
                   14779: 	     "request.role.adv"   => $env{'user.adv'},
                   14780: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14781: 
                   14782:         if ($form->{'localpath'}) {
                   14783: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14784: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14785:         }
                   14786: 	
                   14787: 	if ($form->{'interface'}) {
                   14788: 	    $form->{'interface'}=~s/\W//gs;
                   14789: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14790: 	    $env{'browser.interface'}=$form->{'interface'};
                   14791: 	}
                   14792: 
1.1075.2.54  raeburn  14793:         if ($form->{'iptoken'}) {
                   14794:             my $lonhost = $r->dir_config('lonHostID');
                   14795:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14796:             $env{'user.noloadbalance'} = $lonhost;
                   14797:         }
                   14798: 
1.981     raeburn  14799:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14800:         my %domdef;
                   14801:         unless ($domain eq 'public') {
                   14802:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14803:         }
1.980     raeburn  14804: 
1.1075.2.7  raeburn  14805:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14806:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14807:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14808:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14809:         }
                   14810: 
1.1075.2.59  raeburn  14811:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14812:             $userenv{'canrequest.'.$crstype} =
                   14813:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14814:                                                   'reload','requestcourses',
                   14815:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14816:         }
                   14817: 
1.1075.2.14  raeburn  14818:         $userenv{'canrequest.author'} =
                   14819:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14820:                                         'reload','requestauthor',
                   14821:                                         \%userenv,\%domdef,\%is_adv);
                   14822:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14823:                                              $domain,$username);
                   14824:         my $reqstatus = $reqauthor{'author_status'};
                   14825:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   14826:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14827:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14828:                                                   $reqauthor{'author'}{'timestamp'};
                   14829:             }
                   14830:         }
                   14831: 
1.462     albertel 14832: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14833: 
1.462     albertel 14834: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14835: 		 &GDBM_WRCREAT(),0640)) {
                   14836: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14837: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14838: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14839:             if (ref($firstaccenv) eq 'HASH') {
                   14840:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14841:             }
                   14842:             if (ref($timerintenv) eq 'HASH') {
                   14843:                 &_add_to_env(\%disk_env,$timerintenv);
                   14844:             }
1.463     albertel 14845: 	    if (ref($args->{'extra_env'})) {
                   14846: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14847: 	    }
1.462     albertel 14848: 	    untie(%disk_env);
                   14849: 	} else {
1.705     tempelho 14850: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14851: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14852: 	    return 'error: '.$!;
                   14853: 	}
                   14854:     }
                   14855:     $env{'request.role'}='cm';
                   14856:     $env{'request.role.adv'}=$env{'user.adv'};
                   14857:     $env{'browser.type'}=$clientbrowser;
                   14858: 
                   14859:     return $cookie;
                   14860: 
                   14861: }
                   14862: 
                   14863: sub _add_to_env {
                   14864:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14865:     if (ref($env_data) eq 'HASH') {
                   14866:         while (my ($key,$value) = each(%$env_data)) {
                   14867: 	    $idf->{$prefix.$key} = $value;
                   14868: 	    $env{$prefix.$key}   = $value;
                   14869:         }
1.462     albertel 14870:     }
                   14871: }
                   14872: 
1.685     tempelho 14873: # --- Get the symbolic name of a problem and the url
                   14874: sub get_symb {
                   14875:     my ($request,$silent) = @_;
1.726     raeburn  14876:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14877:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14878:     if ($symb eq '') {
                   14879:         if (!$silent) {
1.1071    raeburn  14880:             if (ref($request)) { 
                   14881:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14882:             }
1.685     tempelho 14883:             return ();
                   14884:         }
                   14885:     }
                   14886:     &Apache::lonenc::check_decrypt(\$symb);
                   14887:     return ($symb);
                   14888: }
                   14889: 
                   14890: # --------------------------------------------------------------Get annotation
                   14891: 
                   14892: sub get_annotation {
                   14893:     my ($symb,$enc) = @_;
                   14894: 
                   14895:     my $key = $symb;
                   14896:     if (!$enc) {
                   14897:         $key =
                   14898:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14899:     }
                   14900:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14901:     return $annotation{$key};
                   14902: }
                   14903: 
                   14904: sub clean_symb {
1.731     raeburn  14905:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14906: 
                   14907:     &Apache::lonenc::check_decrypt(\$symb);
                   14908:     my $enc = $env{'request.enc'};
1.731     raeburn  14909:     if ($delete_enc) {
1.730     raeburn  14910:         delete($env{'request.enc'});
                   14911:     }
1.685     tempelho 14912: 
                   14913:     return ($symb,$enc);
                   14914: }
1.462     albertel 14915: 
1.1075.2.69  raeburn  14916: ############################################################
                   14917: ############################################################
                   14918: 
                   14919: =pod
                   14920: 
                   14921: =head1 Routines for building display used to search for courses
                   14922: 
                   14923: 
                   14924: =over 4
                   14925: 
                   14926: =item * &build_filters()
                   14927: 
                   14928: Create markup for a table used to set filters to use when selecting
                   14929: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   14930: and quotacheck.pl
                   14931: 
                   14932: 
                   14933: Inputs:
                   14934: 
                   14935: filterlist - anonymous array of fields to include as potential filters
                   14936: 
                   14937: crstype - course type
                   14938: 
                   14939: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   14940:               to pop-open a course selector (will contain "extra element").
                   14941: 
                   14942: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   14943: 
                   14944: filter - anonymous hash of criteria and their values
                   14945: 
                   14946: action - form action
                   14947: 
                   14948: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   14949: 
                   14950: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   14951: 
                   14952: cloneruname - username of owner of new course who wants to clone
                   14953: 
                   14954: clonerudom - domain of owner of new course who wants to clone
                   14955: 
                   14956: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   14957: 
                   14958: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   14959: 
                   14960: codedom - domain
                   14961: 
                   14962: formname - value of form element named "form".
                   14963: 
                   14964: fixeddom - domain, if fixed.
                   14965: 
                   14966: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   14967: 
                   14968: cnameelement - name of form element in form on opener page which will receive title of selected course
                   14969: 
                   14970: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   14971: 
                   14972: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   14973: 
                   14974: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   14975: 
                   14976: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   14977: 
                   14978: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   14979: 
                   14980: 
                   14981: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   14982: 
                   14983: 
                   14984: Side Effects: None
                   14985: 
                   14986: =cut
                   14987: 
                   14988: # ---------------------------------------------- search for courses based on last activity etc.
                   14989: 
                   14990: sub build_filters {
                   14991:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   14992:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   14993:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   14994:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   14995:         $clonetext,$clonewarning) = @_;
                   14996:     my ($list,$jscript);
                   14997:     my $onchange = 'javascript:updateFilters(this)';
                   14998:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   14999:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15000:         $typeselectform,$instcodetitle);
                   15001:     if ($formname eq '') {
                   15002:         $formname = $caller;
                   15003:     }
                   15004:     foreach my $item (@{$filterlist}) {
                   15005:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15006:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15007:             if ($item eq 'domainfilter') {
                   15008:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15009:             } elsif ($item eq 'coursefilter') {
                   15010:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15011:             } elsif ($item eq 'ownerfilter') {
                   15012:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15013:             } elsif ($item eq 'ownerdomfilter') {
                   15014:                 $filter->{'ownerdomfilter'} =
                   15015:                     &LONCAPA::clean_domain($filter->{$item});
                   15016:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15017:                                                        'ownerdomfilter',1);
                   15018:             } elsif ($item eq 'personfilter') {
                   15019:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15020:             } elsif ($item eq 'persondomfilter') {
                   15021:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15022:                                                         'persondomfilter',1);
                   15023:             } else {
                   15024:                 $filter->{$item} =~ s/\W//g;
                   15025:             }
                   15026:             if (!$filter->{$item}) {
                   15027:                 $filter->{$item} = '';
                   15028:             }
                   15029:         }
                   15030:         if ($item eq 'domainfilter') {
                   15031:             my $allow_blank = 1;
                   15032:             if ($formname eq 'portform') {
                   15033:                 $allow_blank=0;
                   15034:             } elsif ($formname eq 'studentform') {
                   15035:                 $allow_blank=0;
                   15036:             }
                   15037:             if ($fixeddom) {
                   15038:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15039:                                     ' value="'.$codedom.'" />'.
                   15040:                                     &Apache::lonnet::domain($codedom,'description');
                   15041:             } else {
                   15042:                 $domainselectform = &select_dom_form($filter->{$item},
                   15043:                                                      'domainfilter',
                   15044:                                                       $allow_blank,'',$onchange);
                   15045:             }
                   15046:         } else {
                   15047:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15048:         }
                   15049:     }
                   15050: 
                   15051:     # last course activity filter and selection
                   15052:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15053: 
                   15054:     # course created filter and selection
                   15055:     if (exists($filter->{'createdfilter'})) {
                   15056:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15057:     }
                   15058: 
                   15059:     my %lt = &Apache::lonlocal::texthash(
                   15060:                 'cac' => "$crstype Activity",
                   15061:                 'ccr' => "$crstype Created",
                   15062:                 'cde' => "$crstype Title",
                   15063:                 'cdo' => "$crstype Domain",
                   15064:                 'ins' => 'Institutional Code',
                   15065:                 'inc' => 'Institutional Categorization',
                   15066:                 'cow' => "$crstype Owner/Co-owner",
                   15067:                 'cop' => "$crstype Personnel Includes",
                   15068:                 'cog' => 'Type',
                   15069:              );
                   15070: 
                   15071:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15072:         my $typeval = 'Course';
                   15073:         if ($crstype eq 'Community') {
                   15074:             $typeval = 'Community';
                   15075:         }
                   15076:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15077:     } else {
                   15078:         $typeselectform =  '<select name="type" size="1"';
                   15079:         if ($onchange) {
                   15080:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15081:         }
                   15082:         $typeselectform .= '>'."\n";
                   15083:         foreach my $posstype ('Course','Community') {
                   15084:             $typeselectform.='<option value="'.$posstype.'"'.
                   15085:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15086:         }
                   15087:         $typeselectform.="</select>";
                   15088:     }
                   15089: 
                   15090:     my ($cloneableonlyform,$cloneabletitle);
                   15091:     if (exists($filter->{'cloneableonly'})) {
                   15092:         my $cloneableon = '';
                   15093:         my $cloneableoff = ' checked="checked"';
                   15094:         if ($filter->{'cloneableonly'}) {
                   15095:             $cloneableon = $cloneableoff;
                   15096:             $cloneableoff = '';
                   15097:         }
                   15098:         $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>';
                   15099:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15100:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15101:         } else {
                   15102:             $cloneabletitle = &mt('Cloneable by you');
                   15103:         }
                   15104:     }
                   15105:     my $officialjs;
                   15106:     if ($crstype eq 'Course') {
                   15107:         if (exists($filter->{'instcodefilter'})) {
                   15108: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15109: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15110:             if ($codedom) {
                   15111:                 $officialjs = 1;
                   15112:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15113:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15114:                                                                   $officialjs,$codetitlesref);
                   15115:                 if ($jscript) {
                   15116:                     $jscript = '<script type="text/javascript">'."\n".
                   15117:                                '// <![CDATA['."\n".
                   15118:                                $jscript."\n".
                   15119:                                '// ]]>'."\n".
                   15120:                                '</script>'."\n";
                   15121:                 }
                   15122:             }
                   15123:             if ($instcodeform eq '') {
                   15124:                 $instcodeform =
                   15125:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15126:                     $list->{'instcodefilter'}.'" />';
                   15127:                 $instcodetitle = $lt{'ins'};
                   15128:             } else {
                   15129:                 $instcodetitle = $lt{'inc'};
                   15130:             }
                   15131:             if ($fixeddom) {
                   15132:                 $instcodetitle .= '<br />('.$codedom.')';
                   15133:             }
                   15134:         }
                   15135:     }
                   15136:     my $output = qq|
                   15137: <form method="post" name="filterpicker" action="$action">
                   15138: <input type="hidden" name="form" value="$formname" />
                   15139: |;
                   15140:     if ($formname eq 'modifycourse') {
                   15141:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15142:                    '<input type="hidden" name="prevphase" value="'.
                   15143:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15144:     } elsif ($formname eq 'quotacheck') {
                   15145:         $output .= qq|
                   15146: <input type="hidden" name="sortby" value="" />
                   15147: <input type="hidden" name="sortorder" value="" />
                   15148: |;
                   15149:     } else {
1.1075.2.69  raeburn  15150:         my $name_input;
                   15151:         if ($cnameelement ne '') {
                   15152:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15153:                           $cnameelement.'" />';
                   15154:         }
                   15155:         $output .= qq|
                   15156: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15157: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15158: $name_input
                   15159: $roleelement
                   15160: $multelement
                   15161: $typeelement
                   15162: |;
                   15163:         if ($formname eq 'portform') {
                   15164:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15165:         }
                   15166:     }
                   15167:     if ($fixeddom) {
                   15168:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15169:     }
                   15170:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15171:     if ($sincefilterform) {
                   15172:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15173:                   .$sincefilterform
                   15174:                   .&Apache::lonhtmlcommon::row_closure();
                   15175:     }
                   15176:     if ($createdfilterform) {
                   15177:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15178:                   .$createdfilterform
                   15179:                   .&Apache::lonhtmlcommon::row_closure();
                   15180:     }
                   15181:     if ($domainselectform) {
                   15182:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15183:                   .$domainselectform
                   15184:                   .&Apache::lonhtmlcommon::row_closure();
                   15185:     }
                   15186:     if ($typeselectform) {
                   15187:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15188:             $output .= $typeselectform;
                   15189:         } else {
                   15190:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15191:                       .$typeselectform
                   15192:                       .&Apache::lonhtmlcommon::row_closure();
                   15193:         }
                   15194:     }
                   15195:     if ($instcodeform) {
                   15196:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15197:                   .$instcodeform
                   15198:                   .&Apache::lonhtmlcommon::row_closure();
                   15199:     }
                   15200:     if (exists($filter->{'ownerfilter'})) {
                   15201:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15202:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15203:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15204:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15205:                    $ownerdomselectform.'</td></tr></table>'.
                   15206:                    &Apache::lonhtmlcommon::row_closure();
                   15207:     }
                   15208:     if (exists($filter->{'personfilter'})) {
                   15209:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15210:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15211:                    '<input type="text" name="personfilter" size="20" value="'.
                   15212:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15213:                    $persondomselectform.'</td></tr></table>'.
                   15214:                    &Apache::lonhtmlcommon::row_closure();
                   15215:     }
                   15216:     if (exists($filter->{'coursefilter'})) {
                   15217:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15218:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15219:                   .$list->{'coursefilter'}.'" />'
                   15220:                   .&Apache::lonhtmlcommon::row_closure();
                   15221:     }
                   15222:     if ($cloneableonlyform) {
                   15223:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15224:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15225:     }
                   15226:     if (exists($filter->{'descriptfilter'})) {
                   15227:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15228:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15229:                   .$list->{'descriptfilter'}.'" />'
                   15230:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15231:     }
                   15232:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15233:                '<input type="hidden" name="updater" value="" />'."\n".
                   15234:                '<input type="submit" name="gosearch" value="'.
                   15235:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15236:     return $jscript.$clonewarning.$output;
                   15237: }
                   15238: 
                   15239: =pod
                   15240: 
                   15241: =item * &timebased_select_form()
                   15242: 
                   15243: Create markup for a dropdown list used to select a time-based
                   15244: filter e.g., Course Activity, Course Created, when searching for courses
                   15245: or communities
                   15246: 
                   15247: Inputs:
                   15248: 
                   15249: item - name of form element (sincefilter or createdfilter)
                   15250: 
                   15251: filter - anonymous hash of criteria and their values
                   15252: 
                   15253: Returns: HTML for a select box contained a blank, then six time selections,
                   15254:          with value set in incoming form variables currently selected.
                   15255: 
                   15256: Side Effects: None
                   15257: 
                   15258: =cut
                   15259: 
                   15260: sub timebased_select_form {
                   15261:     my ($item,$filter) = @_;
                   15262:     if (ref($filter) eq 'HASH') {
                   15263:         $filter->{$item} =~ s/[^\d-]//g;
                   15264:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15265:         return &select_form(
                   15266:                             $filter->{$item},
                   15267:                             $item,
                   15268:                             {      '-1' => '',
                   15269:                                 '86400' => &mt('today'),
                   15270:                                '604800' => &mt('last week'),
                   15271:                               '2592000' => &mt('last month'),
                   15272:                               '7776000' => &mt('last three months'),
                   15273:                              '15552000' => &mt('last six months'),
                   15274:                              '31104000' => &mt('last year'),
                   15275:                     'select_form_order' =>
                   15276:                            ['-1','86400','604800','2592000','7776000',
                   15277:                             '15552000','31104000']});
                   15278:     }
                   15279: }
                   15280: 
                   15281: =pod
                   15282: 
                   15283: =item * &js_changer()
                   15284: 
                   15285: Create script tag containing Javascript used to submit course search form
                   15286: when course type or domain is changed, and also to hide 'Searching ...' on
                   15287: page load completion for page showing search result.
                   15288: 
                   15289: Inputs: None
                   15290: 
                   15291: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15292: 
                   15293: Side Effects: None
                   15294: 
                   15295: =cut
                   15296: 
                   15297: sub js_changer {
                   15298:     return <<ENDJS;
                   15299: <script type="text/javascript">
                   15300: // <![CDATA[
                   15301: function updateFilters(caller) {
                   15302:     if (typeof(caller) != "undefined") {
                   15303:         document.filterpicker.updater.value = caller.name;
                   15304:     }
                   15305:     document.filterpicker.submit();
                   15306: }
                   15307: 
                   15308: function hideSearching() {
                   15309:     if (document.getElementById('searching')) {
                   15310:         document.getElementById('searching').style.display = 'none';
                   15311:     }
                   15312:     return;
                   15313: }
                   15314: 
                   15315: // ]]>
                   15316: </script>
                   15317: 
                   15318: ENDJS
                   15319: }
                   15320: 
                   15321: =pod
                   15322: 
                   15323: =item * &search_courses()
                   15324: 
                   15325: Process selected filters form course search form and pass to lonnet::courseiddump
                   15326: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15327: 
                   15328: Inputs:
                   15329: 
                   15330: dom - domain being searched
                   15331: 
                   15332: type - course type ('Course' or 'Community' or '.' if any).
                   15333: 
                   15334: filter - anonymous hash of criteria and their values
                   15335: 
                   15336: numtitles - for institutional codes - number of categories
                   15337: 
                   15338: cloneruname - optional username of new course owner
                   15339: 
                   15340: clonerudom - optional domain of new course owner
                   15341: 
                   15342: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
                   15343:             (used when DC is using course creation form)
                   15344: 
                   15345: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15346: 
                   15347: 
                   15348: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15349: 
                   15350: 
                   15351: Side Effects: None
                   15352: 
                   15353: =cut
                   15354: 
                   15355: 
                   15356: sub search_courses {
                   15357:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
                   15358:     my (%courses,%showcourses,$cloner);
                   15359:     if (($filter->{'ownerfilter'} ne '') ||
                   15360:         ($filter->{'ownerdomfilter'} ne '')) {
                   15361:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15362:                                        $filter->{'ownerdomfilter'};
                   15363:     }
                   15364:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15365:         if (!$filter->{$item}) {
                   15366:             $filter->{$item}='.';
                   15367:         }
                   15368:     }
                   15369:     my $now = time;
                   15370:     my $timefilter =
                   15371:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15372:     my ($createdbefore,$createdafter);
                   15373:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15374:         $createdbefore = $now;
                   15375:         $createdafter = $now-$filter->{'createdfilter'};
                   15376:     }
                   15377:     my ($instcodefilter,$regexpok);
                   15378:     if ($numtitles) {
                   15379:         if ($env{'form.official'} eq 'on') {
                   15380:             $instcodefilter =
                   15381:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15382:             $regexpok = 1;
                   15383:         } elsif ($env{'form.official'} eq 'off') {
                   15384:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15385:             unless ($instcodefilter eq '') {
                   15386:                 $regexpok = -1;
                   15387:             }
                   15388:         }
                   15389:     } else {
                   15390:         $instcodefilter = $filter->{'instcodefilter'};
                   15391:     }
                   15392:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15393:     if ($type eq '') { $type = '.'; }
                   15394: 
                   15395:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15396:         $cloner = $cloneruname.':'.$clonerudom;
                   15397:     }
                   15398:     %courses = &Apache::lonnet::courseiddump($dom,
                   15399:                                              $filter->{'descriptfilter'},
                   15400:                                              $timefilter,
                   15401:                                              $instcodefilter,
                   15402:                                              $filter->{'combownerfilter'},
                   15403:                                              $filter->{'coursefilter'},
                   15404:                                              undef,undef,$type,$regexpok,undef,undef,
                   15405:                                              undef,undef,$cloner,$env{'form.cc_clone'},
                   15406:                                              $filter->{'cloneableonly'},
                   15407:                                              $createdbefore,$createdafter,undef,
                   15408:                                              $domcloner);
                   15409:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15410:         my $ccrole;
                   15411:         if ($type eq 'Community') {
                   15412:             $ccrole = 'co';
                   15413:         } else {
                   15414:             $ccrole = 'cc';
                   15415:         }
                   15416:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15417:                                                      $filter->{'persondomfilter'},
                   15418:                                                      'userroles',undef,
                   15419:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15420:                                                      $dom);
                   15421:         foreach my $role (keys(%rolehash)) {
                   15422:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15423:             my $cid = $cdom.'_'.$cnum;
                   15424:             if (exists($courses{$cid})) {
                   15425:                 if (ref($courses{$cid}) eq 'HASH') {
                   15426:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15427:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15428:                             push (@{$courses{$cid}{roles}},$courserole);
                   15429:                         }
                   15430:                     } else {
                   15431:                         $courses{$cid}{roles} = [$courserole];
                   15432:                     }
                   15433:                     $showcourses{$cid} = $courses{$cid};
                   15434:                 }
                   15435:             }
                   15436:         }
                   15437:         %courses = %showcourses;
                   15438:     }
                   15439:     return %courses;
                   15440: }
                   15441: 
                   15442: =pod
                   15443: 
                   15444: =back
                   15445: 
1.1075.2.88  raeburn  15446: =head1 Routines for version requirements for current course.
                   15447: 
                   15448: =over 4
                   15449: 
                   15450: =item * &check_release_required()
                   15451: 
                   15452: Compares required LON-CAPA version with version on server, and
                   15453: if required version is newer looks for a server with the required version.
                   15454: 
                   15455: Looks first at servers in user's owen domain; if none suitable, looks at
                   15456: servers in course's domain are permitted to host sessions for user's domain.
                   15457: 
                   15458: Inputs:
                   15459: 
                   15460: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15461: 
                   15462: $courseid - Course ID of current course
                   15463: 
                   15464: $rolecode - User's current role in course (for switchserver query string).
                   15465: 
                   15466: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15467: 
                   15468: 
                   15469: Returns:
                   15470: 
                   15471: $switchserver - query string tp append to /adm/switchserver call (if
                   15472:                 current server's LON-CAPA version is too old.
                   15473: 
                   15474: $warning - Message is displayed if no suitable server could be found.
                   15475: 
                   15476: =cut
                   15477: 
                   15478: sub check_release_required {
                   15479:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15480:     my ($switchserver,$warning);
                   15481:     if ($required ne '') {
                   15482:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15483:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15484:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15485:             my $otherserver;
                   15486:             if (($major eq '' && $minor eq '') ||
                   15487:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15488:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15489:                 my $switchlcrev =
                   15490:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15491:                                                            $userdomserver);
                   15492:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15493:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15494:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15495:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15496:                     if ($cdom ne $env{'user.domain'}) {
                   15497:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15498:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15499:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15500:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15501:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15502:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15503:                         my $canhost =
                   15504:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15505:                                                               $coursedomserver,
                   15506:                                                               $remoterev,
                   15507:                                                               $udomdefaults{'remotesessions'},
                   15508:                                                               $defdomdefaults{'hostedsessions'});
                   15509: 
                   15510:                         if ($canhost) {
                   15511:                             $otherserver = $coursedomserver;
                   15512:                         } else {
                   15513:                             $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.");
                   15514:                         }
                   15515:                     } else {
                   15516:                         $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).");
                   15517:                     }
                   15518:                 } else {
                   15519:                     $otherserver = $userdomserver;
                   15520:                 }
                   15521:             }
                   15522:             if ($otherserver ne '') {
                   15523:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   15524:             }
                   15525:         }
                   15526:     }
                   15527:     return ($switchserver,$warning);
                   15528: }
                   15529: 
                   15530: =pod
                   15531: 
                   15532: =item * &check_release_result()
                   15533: 
                   15534: Inputs:
                   15535: 
                   15536: $switchwarning - Warning message if no suitable server found to host session.
                   15537: 
                   15538: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15539:                 and current role.
                   15540: 
                   15541: Returns: HTML to display with information about requirement to switch server.
                   15542:          Either displaying warning with link to Roles/Courses screen or
                   15543:          display link to switchserver.
                   15544: 
1.1075.2.69  raeburn  15545: =cut
                   15546: 
1.1075.2.88  raeburn  15547: sub check_release_result {
                   15548:     my ($switchwarning,$switchserver) = @_;
                   15549:     my $output = &start_page('Selected course unavailable on this server').
                   15550:                  '<p class="LC_warning">';
                   15551:     if ($switchwarning) {
                   15552:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   15553:         if (&show_course()) {
                   15554:             $output .= &mt('Display courses');
                   15555:         } else {
                   15556:             $output .= &mt('Display roles');
                   15557:         }
                   15558:         $output .= '</a>';
                   15559:     } elsif ($switchserver) {
                   15560:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   15561:                    '<br />'.
                   15562:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   15563:                    &mt('Switch Server').
                   15564:                    '</a>';
                   15565:     }
                   15566:     $output .= '</p>'.&end_page();
                   15567:     return $output;
                   15568: }
                   15569: 
                   15570: =pod
                   15571: 
                   15572: =item * &needs_coursereinit()
                   15573: 
                   15574: Determine if course contents stored for user's session needs to be
                   15575: refreshed, because content has changed since "Big Hash" last tied.
                   15576: 
                   15577: Check for change is made if time last checked is more than 10 minutes ago
                   15578: (by default).
                   15579: 
                   15580: Inputs:
                   15581: 
                   15582: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15583: 
                   15584: $interval (optional) - Time which may elapse (in s) between last check for content
                   15585:                        change in current course. (default: 600 s).
                   15586: 
                   15587: Returns: an array; first element is:
                   15588: 
                   15589: =over 4
                   15590: 
                   15591: 'switch' - if content updates mean user's session
                   15592:            needs to be switched to a server running a newer LON-CAPA version
                   15593: 
                   15594: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   15595:            on current server hosting user's session
                   15596: 
                   15597: ''       - if no action required.
                   15598: 
                   15599: =back
                   15600: 
                   15601: If first item element is 'switch':
                   15602: 
                   15603: second item is $switchwarning - Warning message if no suitable server found to host session.
                   15604: 
                   15605: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15606:                               and current role.
                   15607: 
                   15608: otherwise: no other elements returned.
                   15609: 
                   15610: =back
                   15611: 
                   15612: =cut
                   15613: 
                   15614: sub needs_coursereinit {
                   15615:     my ($loncaparev,$interval) = @_;
                   15616:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   15617:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   15618:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   15619:     my $now = time;
                   15620:     if ($interval eq '') {
                   15621:         $interval = 600;
                   15622:     }
                   15623:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   15624:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15625:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   15626:         if ($lastchange > $env{'request.course.tied'}) {
                   15627:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15628:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   15629:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   15630:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   15631:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   15632:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   15633:                     my ($switchserver,$switchwarning) =
                   15634:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   15635:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   15636:                     if ($switchwarning ne '' || $switchserver ne '') {
                   15637:                         return ('switch',$switchwarning,$switchserver);
                   15638:                     }
                   15639:                 }
                   15640:             }
                   15641:             return ('update');
                   15642:         }
                   15643:     }
                   15644:     return ();
                   15645: }
1.1075.2.69  raeburn  15646: 
1.1075.2.11  raeburn  15647: sub update_content_constraints {
                   15648:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15649:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15650:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15651:     my %checkresponsetypes;
                   15652:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15653:         my ($item,$name,$value) = split(/:/,$key);
                   15654:         if ($item eq 'resourcetag') {
                   15655:             if ($name eq 'responsetype') {
                   15656:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15657:             }
                   15658:         }
                   15659:     }
                   15660:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15661:     if (defined($navmap)) {
                   15662:         my %allresponses;
                   15663:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15664:             my %responses = $res->responseTypes();
                   15665:             foreach my $key (keys(%responses)) {
                   15666:                 next unless(exists($checkresponsetypes{$key}));
                   15667:                 $allresponses{$key} += $responses{$key};
                   15668:             }
                   15669:         }
                   15670:         foreach my $key (keys(%allresponses)) {
                   15671:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15672:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15673:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15674:             }
                   15675:         }
                   15676:         undef($navmap);
                   15677:     }
                   15678:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15679:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15680:     }
                   15681:     return;
                   15682: }
                   15683: 
1.1075.2.27  raeburn  15684: sub allmaps_incourse {
                   15685:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15686:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15687:         $cid = $env{'request.course.id'};
                   15688:         $cdom = $env{'course.'.$cid.'.domain'};
                   15689:         $cnum = $env{'course.'.$cid.'.num'};
                   15690:         $chome = $env{'course.'.$cid.'.home'};
                   15691:     }
                   15692:     my %allmaps = ();
                   15693:     my $lastchange =
                   15694:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15695:     if ($lastchange > $env{'request.course.tied'}) {
                   15696:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15697:         unless ($ferr) {
                   15698:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15699:         }
                   15700:     }
                   15701:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15702:     if (defined($navmap)) {
                   15703:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15704:             $allmaps{$res->src()} = 1;
                   15705:         }
                   15706:     }
                   15707:     return \%allmaps;
                   15708: }
                   15709: 
1.1075.2.11  raeburn  15710: sub parse_supplemental_title {
                   15711:     my ($title) = @_;
                   15712: 
                   15713:     my ($foldertitle,$renametitle);
                   15714:     if ($title =~ /&amp;&amp;&amp;/) {
                   15715:         $title = &HTML::Entites::decode($title);
                   15716:     }
                   15717:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   15718:         $renametitle=$4;
                   15719:         my ($time,$uname,$udom) = ($1,$2,$3);
                   15720:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   15721:         my $name =  &plainname($uname,$udom);
                   15722:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   15723:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   15724:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   15725:             $name.': <br />'.$foldertitle;
                   15726:     }
                   15727:     if (wantarray) {
                   15728:         return ($title,$foldertitle,$renametitle);
                   15729:     }
                   15730:     return $title;
                   15731: }
                   15732: 
1.1075.2.43  raeburn  15733: sub recurse_supplemental {
                   15734:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   15735:     if ($suppmap) {
                   15736:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   15737:         if ($fatal) {
                   15738:             $errors ++;
                   15739:         } else {
                   15740:             if ($#LONCAPA::map::resources > 0) {
                   15741:                 foreach my $res (@LONCAPA::map::resources) {
                   15742:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   15743:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  15744:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   15745:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  15746:                         } else {
                   15747:                             $numfiles ++;
                   15748:                         }
                   15749:                     }
                   15750:                 }
                   15751:             }
                   15752:         }
                   15753:     }
                   15754:     return ($numfiles,$errors);
                   15755: }
                   15756: 
1.1075.2.18  raeburn  15757: sub symb_to_docspath {
                   15758:     my ($symb) = @_;
                   15759:     return unless ($symb);
                   15760:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   15761:     if ($resurl=~/\.(sequence|page)$/) {
                   15762:         $mapurl=$resurl;
                   15763:     } elsif ($resurl eq 'adm/navmaps') {
                   15764:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   15765:     }
                   15766:     my $mapresobj;
                   15767:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15768:     if (ref($navmap)) {
                   15769:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   15770:     }
                   15771:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   15772:     my $type=$2;
                   15773:     my $path;
                   15774:     if (ref($mapresobj)) {
                   15775:         my $pcslist = $mapresobj->map_hierarchy();
                   15776:         if ($pcslist ne '') {
                   15777:             foreach my $pc (split(/,/,$pcslist)) {
                   15778:                 next if ($pc <= 1);
                   15779:                 my $res = $navmap->getByMapPc($pc);
                   15780:                 if (ref($res)) {
                   15781:                     my $thisurl = $res->src();
                   15782:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   15783:                     my $thistitle = $res->title();
                   15784:                     $path .= '&'.
                   15785:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  15786:                              &escape($thistitle).
1.1075.2.18  raeburn  15787:                              ':'.$res->randompick().
                   15788:                              ':'.$res->randomout().
                   15789:                              ':'.$res->encrypted().
                   15790:                              ':'.$res->randomorder().
                   15791:                              ':'.$res->is_page();
                   15792:                 }
                   15793:             }
                   15794:         }
                   15795:         $path =~ s/^\&//;
                   15796:         my $maptitle = $mapresobj->title();
                   15797:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  15798:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  15799:         }
                   15800:         $path .= (($path ne '')? '&' : '').
                   15801:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  15802:                  &escape($maptitle).
1.1075.2.18  raeburn  15803:                  ':'.$mapresobj->randompick().
                   15804:                  ':'.$mapresobj->randomout().
                   15805:                  ':'.$mapresobj->encrypted().
                   15806:                  ':'.$mapresobj->randomorder().
                   15807:                  ':'.$mapresobj->is_page();
                   15808:     } else {
                   15809:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   15810:         my $ispage = (($type eq 'page')? 1 : '');
                   15811:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  15812:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  15813:         }
                   15814:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  15815:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  15816:     }
                   15817:     unless ($mapurl eq 'default') {
                   15818:         $path = 'default&'.
1.1075.2.46  raeburn  15819:                 &escape('Main Content').
1.1075.2.18  raeburn  15820:                 ':::::&'.$path;
                   15821:     }
                   15822:     return $path;
                   15823: }
                   15824: 
1.1075.2.14  raeburn  15825: sub captcha_display {
                   15826:     my ($context,$lonhost) = @_;
                   15827:     my ($output,$error);
                   15828:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   15829:     if ($captcha eq 'original') {
                   15830:         $output = &create_captcha();
                   15831:         unless ($output) {
                   15832:             $error = 'captcha';
                   15833:         }
                   15834:     } elsif ($captcha eq 'recaptcha') {
                   15835:         $output = &create_recaptcha($pubkey);
                   15836:         unless ($output) {
                   15837:             $error = 'recaptcha';
                   15838:         }
                   15839:     }
1.1075.2.66  raeburn  15840:     return ($output,$error,$captcha);
1.1075.2.14  raeburn  15841: }
                   15842: 
                   15843: sub captcha_response {
                   15844:     my ($context,$lonhost) = @_;
                   15845:     my ($captcha_chk,$captcha_error);
                   15846:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   15847:     if ($captcha eq 'original') {
                   15848:         ($captcha_chk,$captcha_error) = &check_captcha();
                   15849:     } elsif ($captcha eq 'recaptcha') {
                   15850:         $captcha_chk = &check_recaptcha($privkey);
                   15851:     } else {
                   15852:         $captcha_chk = 1;
                   15853:     }
                   15854:     return ($captcha_chk,$captcha_error);
                   15855: }
                   15856: 
                   15857: sub get_captcha_config {
                   15858:     my ($context,$lonhost) = @_;
                   15859:     my ($captcha,$pubkey,$privkey,$hashtocheck);
                   15860:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   15861:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   15862:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15863:     if ($context eq 'usercreation') {
                   15864:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   15865:         if (ref($domconfig{$context}) eq 'HASH') {
                   15866:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   15867:             if (ref($hashtocheck) eq 'HASH') {
                   15868:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   15869:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   15870:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   15871:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   15872:                     }
                   15873:                     if ($privkey && $pubkey) {
                   15874:                         $captcha = 'recaptcha';
                   15875:                     } else {
                   15876:                         $captcha = 'original';
                   15877:                     }
                   15878:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   15879:                     $captcha = 'original';
                   15880:                 }
                   15881:             }
                   15882:         } else {
                   15883:             $captcha = 'captcha';
                   15884:         }
                   15885:     } elsif ($context eq 'login') {
                   15886:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   15887:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   15888:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   15889:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   15890:             if ($privkey && $pubkey) {
                   15891:                 $captcha = 'recaptcha';
                   15892:             } else {
                   15893:                 $captcha = 'original';
                   15894:             }
                   15895:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   15896:             $captcha = 'original';
                   15897:         }
                   15898:     }
                   15899:     return ($captcha,$pubkey,$privkey);
                   15900: }
                   15901: 
                   15902: sub create_captcha {
                   15903:     my %captcha_params = &captcha_settings();
                   15904:     my ($output,$maxtries,$tries) = ('',10,0);
                   15905:     while ($tries < $maxtries) {
                   15906:         $tries ++;
                   15907:         my $captcha = Authen::Captcha->new (
                   15908:                                            output_folder => $captcha_params{'output_dir'},
                   15909:                                            data_folder   => $captcha_params{'db_dir'},
                   15910:                                           );
                   15911:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   15912: 
                   15913:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   15914:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   15915:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  15916:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   15917:                       '<br />'.
                   15918:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  15919:             last;
                   15920:         }
                   15921:     }
                   15922:     return $output;
                   15923: }
                   15924: 
                   15925: sub captcha_settings {
                   15926:     my %captcha_params = (
                   15927:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   15928:                            www_output_dir => "/captchaspool",
                   15929:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   15930:                            numchars       => '5',
                   15931:                          );
                   15932:     return %captcha_params;
                   15933: }
                   15934: 
                   15935: sub check_captcha {
                   15936:     my ($captcha_chk,$captcha_error);
                   15937:     my $code = $env{'form.code'};
                   15938:     my $md5sum = $env{'form.crypt'};
                   15939:     my %captcha_params = &captcha_settings();
                   15940:     my $captcha = Authen::Captcha->new(
                   15941:                       output_folder => $captcha_params{'output_dir'},
                   15942:                       data_folder   => $captcha_params{'db_dir'},
                   15943:                   );
1.1075.2.26  raeburn  15944:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  15945:     my %captcha_hash = (
                   15946:                         0       => 'Code not checked (file error)',
                   15947:                        -1      => 'Failed: code expired',
                   15948:                        -2      => 'Failed: invalid code (not in database)',
                   15949:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   15950:     );
                   15951:     if ($captcha_chk != 1) {
                   15952:         $captcha_error = $captcha_hash{$captcha_chk}
                   15953:     }
                   15954:     return ($captcha_chk,$captcha_error);
                   15955: }
                   15956: 
                   15957: sub create_recaptcha {
                   15958:     my ($pubkey) = @_;
1.1075.2.51  raeburn  15959:     my $use_ssl;
                   15960:     if ($ENV{'SERVER_PORT'} == 443) {
                   15961:         $use_ssl = 1;
                   15962:     }
1.1075.2.14  raeburn  15963:     my $captcha = Captcha::reCAPTCHA->new;
                   15964:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1075.2.51  raeburn  15965:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1075.2.92  raeburn  15966:            &mt('If the text is hard to read, [_1] will replace them.',
1.1075.2.39  raeburn  15967:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1075.2.14  raeburn  15968:            '<br /><br />';
                   15969: }
                   15970: 
                   15971: sub check_recaptcha {
                   15972:     my ($privkey) = @_;
                   15973:     my $captcha_chk;
                   15974:     my $captcha = Captcha::reCAPTCHA->new;
                   15975:     my $captcha_result =
                   15976:         $captcha->check_answer(
                   15977:                                 $privkey,
                   15978:                                 $ENV{'REMOTE_ADDR'},
                   15979:                                 $env{'form.recaptcha_challenge_field'},
                   15980:                                 $env{'form.recaptcha_response_field'},
                   15981:                               );
                   15982:     if ($captcha_result->{is_valid}) {
                   15983:         $captcha_chk = 1;
                   15984:     }
                   15985:     return $captcha_chk;
                   15986: }
                   15987: 
1.1075.2.64  raeburn  15988: sub emailusername_info {
1.1075.2.67  raeburn  15989:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1075.2.64  raeburn  15990:     my %titles = &Apache::lonlocal::texthash (
                   15991:                      lastname      => 'Last Name',
                   15992:                      firstname     => 'First Name',
                   15993:                      institution   => 'School/college/university',
                   15994:                      location      => "School's city, state/province, country",
                   15995:                      web           => "School's web address",
                   15996:                      officialemail => 'E-mail address at institution (if different)',
                   15997:                  );
                   15998:     return (\@fields,\%titles);
                   15999: }
                   16000: 
1.1075.2.56  raeburn  16001: sub cleanup_html {
                   16002:     my ($incoming) = @_;
                   16003:     my $outgoing;
                   16004:     if ($incoming ne '') {
                   16005:         $outgoing = $incoming;
                   16006:         $outgoing =~ s/;/&#059;/g;
                   16007:         $outgoing =~ s/\#/&#035;/g;
                   16008:         $outgoing =~ s/\&/&#038;/g;
                   16009:         $outgoing =~ s/</&#060;/g;
                   16010:         $outgoing =~ s/>/&#062;/g;
                   16011:         $outgoing =~ s/\(/&#040/g;
                   16012:         $outgoing =~ s/\)/&#041;/g;
                   16013:         $outgoing =~ s/"/&#034;/g;
                   16014:         $outgoing =~ s/'/&#039;/g;
                   16015:         $outgoing =~ s/\$/&#036;/g;
                   16016:         $outgoing =~ s{/}{&#047;}g;
                   16017:         $outgoing =~ s/=/&#061;/g;
                   16018:         $outgoing =~ s/\\/&#092;/g
                   16019:     }
                   16020:     return $outgoing;
                   16021: }
                   16022: 
1.1075.2.74  raeburn  16023: # Checks for critical messages and returns a redirect url if one exists.
                   16024: # $interval indicates how often to check for messages.
                   16025: sub critical_redirect {
                   16026:     my ($interval) = @_;
                   16027:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16028:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16029:                                         $env{'user.name'});
                   16030:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16031:         my $redirecturl;
                   16032:         if ($what[0]) {
                   16033:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16034:                 $redirecturl='/adm/email?critical=display';
                   16035:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16036:                 return (1, $url);
                   16037:             }
                   16038:         }
                   16039:     }
                   16040:     return ();
                   16041: }
                   16042: 
1.1075.2.64  raeburn  16043: # Use:
                   16044: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16045: #
                   16046: ##################################################
                   16047: #          password associated functions         #
                   16048: ##################################################
                   16049: sub des_keys {
                   16050:     # Make a new key for DES encryption.
                   16051:     # Each key has two parts which are returned separately.
                   16052:     # Please note:  Each key must be passed through the &hex function
                   16053:     # before it is output to the web browser.  The hex versions cannot
                   16054:     # be used to decrypt.
                   16055:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16056:                 '8','9','a','b','c','d','e','f');
                   16057:     my $lkey='';
                   16058:     for (0..7) {
                   16059:         $lkey.=$hexstr[rand(15)];
                   16060:     }
                   16061:     my $ukey='';
                   16062:     for (0..7) {
                   16063:         $ukey.=$hexstr[rand(15)];
                   16064:     }
                   16065:     return ($lkey,$ukey);
                   16066: }
                   16067: 
                   16068: sub des_decrypt {
                   16069:     my ($key,$cyphertext) = @_;
                   16070:     my $keybin=pack("H16",$key);
                   16071:     my $cypher;
                   16072:     if ($Crypt::DES::VERSION>=2.03) {
                   16073:         $cypher=new Crypt::DES $keybin;
                   16074:     } else {
                   16075:         $cypher=new DES $keybin;
                   16076:     }
                   16077:     my $plaintext=
                   16078:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16079:     $plaintext.=
                   16080:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16081:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16082:     return $plaintext;
                   16083: }
                   16084: 
1.112     bowersj2 16085: 1;
                   16086: __END__;
1.41      ng       16087: 

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